Revert the addition of hasNoPointerOverflow to GEPOperator.
[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 "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.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/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include <algorithm>
36 #include <map>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 //                              Constant Class
41 //===----------------------------------------------------------------------===//
42
43 // Becomes a no-op when multithreading is disabled.
44 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45
46 void Constant::destroyConstantImpl() {
47   // When a Constant is destroyed, there may be lingering
48   // references to the constant by other constants in the constant pool.  These
49   // constants are implicitly dependent on the module that is being deleted,
50   // but they don't know that.  Because we only find out when the CPV is
51   // deleted, we must now notify all of our users (that should only be
52   // Constants) that they are, in fact, invalid now and should be deleted.
53   //
54   while (!use_empty()) {
55     Value *V = use_back();
56 #ifndef NDEBUG      // Only in -g mode...
57     if (!isa<Constant>(V))
58       DOUT << "While deleting: " << *this
59            << "\n\nUse still stuck around after Def is destroyed: "
60            << *V << "\n\n";
61 #endif
62     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
63     Constant *CV = cast<Constant>(V);
64     CV->destroyConstant();
65
66     // The constant should remove itself from our use list...
67     assert((use_empty() || use_back() != V) && "Constant not removed!");
68   }
69
70   // Value has no outstanding references it is safe to delete it now...
71   delete this;
72 }
73
74 /// canTrap - Return true if evaluation of this constant could trap.  This is
75 /// true for things like constant expressions that could divide by zero.
76 bool Constant::canTrap() const {
77   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
78   // The only thing that could possibly trap are constant exprs.
79   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
80   if (!CE) return false;
81   
82   // ConstantExpr traps if any operands can trap. 
83   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
84     if (getOperand(i)->canTrap()) 
85       return true;
86
87   // Otherwise, only specific operations can trap.
88   switch (CE->getOpcode()) {
89   default:
90     return false;
91   case Instruction::UDiv:
92   case Instruction::SDiv:
93   case Instruction::FDiv:
94   case Instruction::URem:
95   case Instruction::SRem:
96   case Instruction::FRem:
97     // Div and rem can trap if the RHS is not known to be non-zero.
98     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
99       return true;
100     return false;
101   }
102 }
103
104 /// ContainsRelocations - Return true if the constant value contains relocations
105 /// which cannot be resolved at compile time. Kind argument is used to filter
106 /// only 'interesting' sorts of relocations.
107 bool Constant::ContainsRelocations(unsigned Kind) const {
108   if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
109     bool isLocal = GV->hasLocalLinkage();
110     if ((Kind & Reloc::Local) && isLocal) {
111       // Global has local linkage and 'local' kind of relocations are
112       // requested
113       return true;
114     }
115
116     if ((Kind & Reloc::Global) && !isLocal) {
117       // Global has non-local linkage and 'global' kind of relocations are
118       // requested
119       return true;
120     }
121
122     return false;
123   }
124
125   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
126     if (getOperand(i)->ContainsRelocations(Kind))
127       return true;
128
129   return false;
130 }
131
132 /// getVectorElements - This method, which is only valid on constant of vector
133 /// type, returns the elements of the vector in the specified smallvector.
134 /// This handles breaking down a vector undef into undef elements, etc.  For
135 /// constant exprs and other cases we can't handle, we return an empty vector.
136 void Constant::getVectorElements(LLVMContext &Context,
137                                  SmallVectorImpl<Constant*> &Elts) const {
138   assert(isa<VectorType>(getType()) && "Not a vector constant!");
139   
140   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
141     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
142       Elts.push_back(CV->getOperand(i));
143     return;
144   }
145   
146   const VectorType *VT = cast<VectorType>(getType());
147   if (isa<ConstantAggregateZero>(this)) {
148     Elts.assign(VT->getNumElements(), 
149                 Context.getNullValue(VT->getElementType()));
150     return;
151   }
152   
153   if (isa<UndefValue>(this)) {
154     Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
155     return;
156   }
157   
158   // Unknown type, must be constant expr etc.
159 }
160
161
162
163 //===----------------------------------------------------------------------===//
164 //                                ConstantInt
165 //===----------------------------------------------------------------------===//
166
167 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
168   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
169   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
170 }
171
172 ConstantInt *ConstantInt::TheTrueVal = 0;
173 ConstantInt *ConstantInt::TheFalseVal = 0;
174
175 namespace llvm {
176   void CleanupTrueFalse(void *) {
177     ConstantInt::ResetTrueFalse();
178   }
179 }
180
181 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182
183 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
184   assert(TheTrueVal == 0 && TheFalseVal == 0);
185   TheTrueVal  = getGlobalContext().getConstantInt(Type::Int1Ty, 1);
186   TheFalseVal = getGlobalContext().getConstantInt(Type::Int1Ty, 0);
187   
188   // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
189   TrueFalseCleanup.Register();
190   
191   return WhichOne ? TheTrueVal : TheFalseVal;
192 }
193
194 //===----------------------------------------------------------------------===//
195 //                                ConstantFP
196 //===----------------------------------------------------------------------===//
197
198 #ifndef NDEBUG 
199 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
200   if (Ty == Type::FloatTy)
201     return &APFloat::IEEEsingle;
202   if (Ty == Type::DoubleTy)
203     return &APFloat::IEEEdouble;
204   if (Ty == Type::X86_FP80Ty)
205     return &APFloat::x87DoubleExtended;
206   else if (Ty == Type::FP128Ty)
207     return &APFloat::IEEEquad;
208   
209   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
210   return &APFloat::PPCDoubleDouble;
211 }
212 #endif
213
214 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
215   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
216   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
217          "FP type Mismatch");
218 }
219
220 bool ConstantFP::isNullValue() const {
221   return Val.isZero() && !Val.isNegative();
222 }
223
224 bool ConstantFP::isExactlyValue(const APFloat& V) const {
225   return Val.bitwiseIsEqual(V);
226 }
227
228 //===----------------------------------------------------------------------===//
229 //                            ConstantXXX Classes
230 //===----------------------------------------------------------------------===//
231
232
233 ConstantArray::ConstantArray(const ArrayType *T,
234                              const std::vector<Constant*> &V)
235   : Constant(T, ConstantArrayVal,
236              OperandTraits<ConstantArray>::op_end(this) - V.size(),
237              V.size()) {
238   assert(V.size() == T->getNumElements() &&
239          "Invalid initializer vector for constant array");
240   Use *OL = OperandList;
241   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
242        I != E; ++I, ++OL) {
243     Constant *C = *I;
244     assert((C->getType() == T->getElementType() ||
245             (T->isAbstract() &&
246              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
247            "Initializer for array element doesn't match array element type!");
248     *OL = C;
249   }
250 }
251
252
253 ConstantStruct::ConstantStruct(const StructType *T,
254                                const std::vector<Constant*> &V)
255   : Constant(T, ConstantStructVal,
256              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
257              V.size()) {
258   assert(V.size() == T->getNumElements() &&
259          "Invalid initializer vector for constant structure");
260   Use *OL = OperandList;
261   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
262        I != E; ++I, ++OL) {
263     Constant *C = *I;
264     assert((C->getType() == T->getElementType(I-V.begin()) ||
265             ((T->getElementType(I-V.begin())->isAbstract() ||
266               C->getType()->isAbstract()) &&
267              T->getElementType(I-V.begin())->getTypeID() == 
268                    C->getType()->getTypeID())) &&
269            "Initializer for struct element doesn't match struct element type!");
270     *OL = C;
271   }
272 }
273
274
275 ConstantVector::ConstantVector(const VectorType *T,
276                                const std::vector<Constant*> &V)
277   : Constant(T, ConstantVectorVal,
278              OperandTraits<ConstantVector>::op_end(this) - V.size(),
279              V.size()) {
280   Use *OL = OperandList;
281     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
282          I != E; ++I, ++OL) {
283       Constant *C = *I;
284       assert((C->getType() == T->getElementType() ||
285             (T->isAbstract() &&
286              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
287            "Initializer for vector element doesn't match vector element type!");
288     *OL = C;
289   }
290 }
291
292
293 namespace llvm {
294 // We declare several classes private to this file, so use an anonymous
295 // namespace
296 namespace {
297
298 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
299 /// behind the scenes to implement unary constant exprs.
300 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
301   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
302 public:
303   // allocate space for exactly one operand
304   void *operator new(size_t s) {
305     return User::operator new(s, 1);
306   }
307   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
308     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
309     Op<0>() = C;
310   }
311   /// Transparently provide more efficient getOperand methods.
312   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
313 };
314
315 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
316 /// behind the scenes to implement binary constant exprs.
317 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
318   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
319 public:
320   // allocate space for exactly two operands
321   void *operator new(size_t s) {
322     return User::operator new(s, 2);
323   }
324   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
325     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
326     Op<0>() = C1;
327     Op<1>() = C2;
328   }
329   /// Transparently provide more efficient getOperand methods.
330   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
331 };
332
333 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
334 /// behind the scenes to implement select constant exprs.
335 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
336   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
337 public:
338   // allocate space for exactly three operands
339   void *operator new(size_t s) {
340     return User::operator new(s, 3);
341   }
342   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
343     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
344     Op<0>() = C1;
345     Op<1>() = C2;
346     Op<2>() = C3;
347   }
348   /// Transparently provide more efficient getOperand methods.
349   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
350 };
351
352 /// ExtractElementConstantExpr - This class is private to
353 /// Constants.cpp, and is used behind the scenes to implement
354 /// extractelement constant exprs.
355 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
356   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
357 public:
358   // allocate space for exactly two operands
359   void *operator new(size_t s) {
360     return User::operator new(s, 2);
361   }
362   ExtractElementConstantExpr(Constant *C1, Constant *C2)
363     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
364                    Instruction::ExtractElement, &Op<0>(), 2) {
365     Op<0>() = C1;
366     Op<1>() = C2;
367   }
368   /// Transparently provide more efficient getOperand methods.
369   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
370 };
371
372 /// InsertElementConstantExpr - This class is private to
373 /// Constants.cpp, and is used behind the scenes to implement
374 /// insertelement constant exprs.
375 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
376   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
377 public:
378   // allocate space for exactly three operands
379   void *operator new(size_t s) {
380     return User::operator new(s, 3);
381   }
382   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
383     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
384                    &Op<0>(), 3) {
385     Op<0>() = C1;
386     Op<1>() = C2;
387     Op<2>() = C3;
388   }
389   /// Transparently provide more efficient getOperand methods.
390   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
391 };
392
393 /// ShuffleVectorConstantExpr - This class is private to
394 /// Constants.cpp, and is used behind the scenes to implement
395 /// shufflevector constant exprs.
396 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
397   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
398 public:
399   // allocate space for exactly three operands
400   void *operator new(size_t s) {
401     return User::operator new(s, 3);
402   }
403   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
404   : ConstantExpr(VectorType::get(
405                    cast<VectorType>(C1->getType())->getElementType(),
406                    cast<VectorType>(C3->getType())->getNumElements()),
407                  Instruction::ShuffleVector, 
408                  &Op<0>(), 3) {
409     Op<0>() = C1;
410     Op<1>() = C2;
411     Op<2>() = C3;
412   }
413   /// Transparently provide more efficient getOperand methods.
414   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
415 };
416
417 /// ExtractValueConstantExpr - This class is private to
418 /// Constants.cpp, and is used behind the scenes to implement
419 /// extractvalue constant exprs.
420 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
421   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
422 public:
423   // allocate space for exactly one operand
424   void *operator new(size_t s) {
425     return User::operator new(s, 1);
426   }
427   ExtractValueConstantExpr(Constant *Agg,
428                            const SmallVector<unsigned, 4> &IdxList,
429                            const Type *DestTy)
430     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
431       Indices(IdxList) {
432     Op<0>() = Agg;
433   }
434
435   /// Indices - These identify which value to extract.
436   const SmallVector<unsigned, 4> Indices;
437
438   /// Transparently provide more efficient getOperand methods.
439   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
440 };
441
442 /// InsertValueConstantExpr - This class is private to
443 /// Constants.cpp, and is used behind the scenes to implement
444 /// insertvalue constant exprs.
445 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
446   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
447 public:
448   // allocate space for exactly one operand
449   void *operator new(size_t s) {
450     return User::operator new(s, 2);
451   }
452   InsertValueConstantExpr(Constant *Agg, Constant *Val,
453                           const SmallVector<unsigned, 4> &IdxList,
454                           const Type *DestTy)
455     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
456       Indices(IdxList) {
457     Op<0>() = Agg;
458     Op<1>() = Val;
459   }
460
461   /// Indices - These identify the position for the insertion.
462   const SmallVector<unsigned, 4> Indices;
463
464   /// Transparently provide more efficient getOperand methods.
465   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
466 };
467
468
469 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
470 /// used behind the scenes to implement getelementpr constant exprs.
471 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
472   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
473                             const Type *DestTy);
474 public:
475   static GetElementPtrConstantExpr *Create(Constant *C,
476                                            const std::vector<Constant*>&IdxList,
477                                            const Type *DestTy) {
478     return
479       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
480   }
481   /// Transparently provide more efficient getOperand methods.
482   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
483 };
484
485 // CompareConstantExpr - This class is private to Constants.cpp, and is used
486 // behind the scenes to implement ICmp and FCmp constant expressions. This is
487 // needed in order to store the predicate value for these instructions.
488 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
489   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
490   // allocate space for exactly two operands
491   void *operator new(size_t s) {
492     return User::operator new(s, 2);
493   }
494   unsigned short predicate;
495   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
496                       unsigned short pred,  Constant* LHS, Constant* RHS)
497     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
498     Op<0>() = LHS;
499     Op<1>() = RHS;
500   }
501   /// Transparently provide more efficient getOperand methods.
502   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
503 };
504
505 } // end anonymous namespace
506
507 template <>
508 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
509 };
510 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
511
512 template <>
513 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
514 };
515 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
516
517 template <>
518 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
519 };
520 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
521
522 template <>
523 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
524 };
525 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
526
527 template <>
528 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
529 };
530 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
531
532 template <>
533 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
534 };
535 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
536
537 template <>
538 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
539 };
540 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
541
542 template <>
543 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
544 };
545 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
546
547 template <>
548 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
549 };
550
551 GetElementPtrConstantExpr::GetElementPtrConstantExpr
552   (Constant *C,
553    const std::vector<Constant*> &IdxList,
554    const Type *DestTy)
555     : ConstantExpr(DestTy, Instruction::GetElementPtr,
556                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
557                    - (IdxList.size()+1),
558                    IdxList.size()+1) {
559   OperandList[0] = C;
560   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
561     OperandList[i+1] = IdxList[i];
562 }
563
564 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
565
566
567 template <>
568 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
569 };
570 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
571
572
573 } // End llvm namespace
574
575
576 // Utility function for determining if a ConstantExpr is a CastOp or not. This
577 // can't be inline because we don't want to #include Instruction.h into
578 // Constant.h
579 bool ConstantExpr::isCast() const {
580   return Instruction::isCast(getOpcode());
581 }
582
583 bool ConstantExpr::isCompare() const {
584   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
585 }
586
587 bool ConstantExpr::hasIndices() const {
588   return getOpcode() == Instruction::ExtractValue ||
589          getOpcode() == Instruction::InsertValue;
590 }
591
592 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
593   if (const ExtractValueConstantExpr *EVCE =
594         dyn_cast<ExtractValueConstantExpr>(this))
595     return EVCE->Indices;
596
597   return cast<InsertValueConstantExpr>(this)->Indices;
598 }
599
600 unsigned ConstantExpr::getPredicate() const {
601   assert(getOpcode() == Instruction::FCmp || 
602          getOpcode() == Instruction::ICmp);
603   return ((const CompareConstantExpr*)this)->predicate;
604 }
605
606 /// getWithOperandReplaced - Return a constant expression identical to this
607 /// one, but with the specified operand set to the specified value.
608 Constant *
609 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
610   assert(OpNo < getNumOperands() && "Operand num is out of range!");
611   assert(Op->getType() == getOperand(OpNo)->getType() &&
612          "Replacing operand with value of different type!");
613   if (getOperand(OpNo) == Op)
614     return const_cast<ConstantExpr*>(this);
615   
616   Constant *Op0, *Op1, *Op2;
617   switch (getOpcode()) {
618   case Instruction::Trunc:
619   case Instruction::ZExt:
620   case Instruction::SExt:
621   case Instruction::FPTrunc:
622   case Instruction::FPExt:
623   case Instruction::UIToFP:
624   case Instruction::SIToFP:
625   case Instruction::FPToUI:
626   case Instruction::FPToSI:
627   case Instruction::PtrToInt:
628   case Instruction::IntToPtr:
629   case Instruction::BitCast:
630     return ConstantExpr::getCast(getOpcode(), Op, getType());
631   case Instruction::Select:
632     Op0 = (OpNo == 0) ? Op : getOperand(0);
633     Op1 = (OpNo == 1) ? Op : getOperand(1);
634     Op2 = (OpNo == 2) ? Op : getOperand(2);
635     return ConstantExpr::getSelect(Op0, Op1, Op2);
636   case Instruction::InsertElement:
637     Op0 = (OpNo == 0) ? Op : getOperand(0);
638     Op1 = (OpNo == 1) ? Op : getOperand(1);
639     Op2 = (OpNo == 2) ? Op : getOperand(2);
640     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
641   case Instruction::ExtractElement:
642     Op0 = (OpNo == 0) ? Op : getOperand(0);
643     Op1 = (OpNo == 1) ? Op : getOperand(1);
644     return ConstantExpr::getExtractElement(Op0, Op1);
645   case Instruction::ShuffleVector:
646     Op0 = (OpNo == 0) ? Op : getOperand(0);
647     Op1 = (OpNo == 1) ? Op : getOperand(1);
648     Op2 = (OpNo == 2) ? Op : getOperand(2);
649     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
650   case Instruction::GetElementPtr: {
651     SmallVector<Constant*, 8> Ops;
652     Ops.resize(getNumOperands()-1);
653     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
654       Ops[i-1] = getOperand(i);
655     if (OpNo == 0)
656       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
657     Ops[OpNo-1] = Op;
658     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
659   }
660   default:
661     assert(getNumOperands() == 2 && "Must be binary operator?");
662     Op0 = (OpNo == 0) ? Op : getOperand(0);
663     Op1 = (OpNo == 1) ? Op : getOperand(1);
664     return ConstantExpr::get(getOpcode(), Op0, Op1);
665   }
666 }
667
668 /// getWithOperands - This returns the current constant expression with the
669 /// operands replaced with the specified values.  The specified operands must
670 /// match count and type with the existing ones.
671 Constant *ConstantExpr::
672 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
673   assert(NumOps == getNumOperands() && "Operand count mismatch!");
674   bool AnyChange = false;
675   for (unsigned i = 0; i != NumOps; ++i) {
676     assert(Ops[i]->getType() == getOperand(i)->getType() &&
677            "Operand type mismatch!");
678     AnyChange |= Ops[i] != getOperand(i);
679   }
680   if (!AnyChange)  // No operands changed, return self.
681     return const_cast<ConstantExpr*>(this);
682
683   switch (getOpcode()) {
684   case Instruction::Trunc:
685   case Instruction::ZExt:
686   case Instruction::SExt:
687   case Instruction::FPTrunc:
688   case Instruction::FPExt:
689   case Instruction::UIToFP:
690   case Instruction::SIToFP:
691   case Instruction::FPToUI:
692   case Instruction::FPToSI:
693   case Instruction::PtrToInt:
694   case Instruction::IntToPtr:
695   case Instruction::BitCast:
696     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
697   case Instruction::Select:
698     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
699   case Instruction::InsertElement:
700     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
701   case Instruction::ExtractElement:
702     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
703   case Instruction::ShuffleVector:
704     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
705   case Instruction::GetElementPtr:
706     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
707   case Instruction::ICmp:
708   case Instruction::FCmp:
709     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
710   default:
711     assert(getNumOperands() == 2 && "Must be binary operator?");
712     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
713   }
714 }
715
716
717 //===----------------------------------------------------------------------===//
718 //                      isValueValidForType implementations
719
720 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
721   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
722   if (Ty == Type::Int1Ty)
723     return Val == 0 || Val == 1;
724   if (NumBits >= 64)
725     return true; // always true, has to fit in largest type
726   uint64_t Max = (1ll << NumBits) - 1;
727   return Val <= Max;
728 }
729
730 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
731   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
732   if (Ty == Type::Int1Ty)
733     return Val == 0 || Val == 1 || Val == -1;
734   if (NumBits >= 64)
735     return true; // always true, has to fit in largest type
736   int64_t Min = -(1ll << (NumBits-1));
737   int64_t Max = (1ll << (NumBits-1)) - 1;
738   return (Val >= Min && Val <= Max);
739 }
740
741 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
742   // convert modifies in place, so make a copy.
743   APFloat Val2 = APFloat(Val);
744   bool losesInfo;
745   switch (Ty->getTypeID()) {
746   default:
747     return false;         // These can't be represented as floating point!
748
749   // FIXME rounding mode needs to be more flexible
750   case Type::FloatTyID: {
751     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
752       return true;
753     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
754     return !losesInfo;
755   }
756   case Type::DoubleTyID: {
757     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
758         &Val2.getSemantics() == &APFloat::IEEEdouble)
759       return true;
760     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
761     return !losesInfo;
762   }
763   case Type::X86_FP80TyID:
764     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
765            &Val2.getSemantics() == &APFloat::IEEEdouble ||
766            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
767   case Type::FP128TyID:
768     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
769            &Val2.getSemantics() == &APFloat::IEEEdouble ||
770            &Val2.getSemantics() == &APFloat::IEEEquad;
771   case Type::PPC_FP128TyID:
772     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
773            &Val2.getSemantics() == &APFloat::IEEEdouble ||
774            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
775   }
776 }
777
778 //===----------------------------------------------------------------------===//
779 //                      Factory Function Implementation
780
781
782 // The number of operands for each ConstantCreator::create method is
783 // determined by the ConstantTraits template.
784 // ConstantCreator - A class that is used to create constants by
785 // ValueMap*.  This class should be partially specialized if there is
786 // something strange that needs to be done to interface to the ctor for the
787 // constant.
788 //
789 namespace llvm {
790   template<class ValType>
791   struct ConstantTraits;
792
793   template<typename T, typename Alloc>
794   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
795     static unsigned uses(const std::vector<T, Alloc>& v) {
796       return v.size();
797     }
798   };
799
800   template<class ConstantClass, class TypeClass, class ValType>
801   struct VISIBILITY_HIDDEN ConstantCreator {
802     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
803       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
804     }
805   };
806
807   template<class ConstantClass, class TypeClass>
808   struct VISIBILITY_HIDDEN ConvertConstantType {
809     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
810       llvm_unreachable("This type cannot be converted!");
811     }
812   };
813
814   template<class ValType, class TypeClass, class ConstantClass,
815            bool HasLargeKey = false  /*true for arrays and structs*/ >
816   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
817   public:
818     typedef std::pair<const Type*, ValType> MapKey;
819     typedef std::map<MapKey, Constant *> MapTy;
820     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
821     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
822   private:
823     /// Map - This is the main map from the element descriptor to the Constants.
824     /// This is the primary way we avoid creating two of the same shape
825     /// constant.
826     MapTy Map;
827     
828     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
829     /// from the constants to their element in Map.  This is important for
830     /// removal of constants from the array, which would otherwise have to scan
831     /// through the map with very large keys.
832     InverseMapTy InverseMap;
833
834     /// AbstractTypeMap - Map for abstract type constants.
835     ///
836     AbstractTypeMapTy AbstractTypeMap;
837     
838     /// ValueMapLock - Mutex for this map.
839     sys::SmartMutex<true> ValueMapLock;
840
841   public:
842     // NOTE: This function is not locked.  It is the caller's responsibility
843     // to enforce proper synchronization.
844     typename MapTy::iterator map_end() { return Map.end(); }
845     
846     /// InsertOrGetItem - Return an iterator for the specified element.
847     /// If the element exists in the map, the returned iterator points to the
848     /// entry and Exists=true.  If not, the iterator points to the newly
849     /// inserted entry and returns Exists=false.  Newly inserted entries have
850     /// I->second == 0, and should be filled in.
851     /// NOTE: This function is not locked.  It is the caller's responsibility
852     // to enforce proper synchronization.
853     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
854                                    &InsertVal,
855                                    bool &Exists) {
856       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
857       Exists = !IP.second;
858       return IP.first;
859     }
860     
861 private:
862     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
863       if (HasLargeKey) {
864         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
865         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
866                IMI->second->second == CP &&
867                "InverseMap corrupt!");
868         return IMI->second;
869       }
870       
871       typename MapTy::iterator I =
872         Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
873                         getValType(CP)));
874       if (I == Map.end() || I->second != CP) {
875         // FIXME: This should not use a linear scan.  If this gets to be a
876         // performance problem, someone should look at this.
877         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
878           /* empty */;
879       }
880       return I;
881     }
882     
883     ConstantClass* Create(const TypeClass *Ty, const ValType &V,
884                           typename MapTy::iterator I) {
885       ConstantClass* Result =
886         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
887
888       assert(Result->getType() == Ty && "Type specified is not correct!");
889       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
890
891       if (HasLargeKey)  // Remember the reverse mapping if needed.
892         InverseMap.insert(std::make_pair(Result, I));
893
894       // If the type of the constant is abstract, make sure that an entry
895       // exists for it in the AbstractTypeMap.
896       if (Ty->isAbstract()) {
897         typename AbstractTypeMapTy::iterator TI = 
898                                                  AbstractTypeMap.find(Ty);
899
900         if (TI == AbstractTypeMap.end()) {
901           // Add ourselves to the ATU list of the type.
902           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
903
904           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
905         }
906       }
907       
908       return Result;
909     }
910 public:
911     
912     /// getOrCreate - Return the specified constant from the map, creating it if
913     /// necessary.
914     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
915       sys::SmartScopedLock<true> Lock(ValueMapLock);
916       MapKey Lookup(Ty, V);
917       ConstantClass* Result = 0;
918       
919       typename MapTy::iterator I = Map.find(Lookup);
920       // Is it in the map?  
921       if (I != Map.end())
922         Result = static_cast<ConstantClass *>(I->second);
923         
924       if (!Result) {
925         // If no preexisting value, create one now...
926         Result = Create(Ty, V, I);
927       }
928         
929       return Result;
930     }
931
932     void remove(ConstantClass *CP) {
933       sys::SmartScopedLock<true> Lock(ValueMapLock);
934       typename MapTy::iterator I = FindExistingElement(CP);
935       assert(I != Map.end() && "Constant not found in constant table!");
936       assert(I->second == CP && "Didn't find correct element?");
937
938       if (HasLargeKey)  // Remember the reverse mapping if needed.
939         InverseMap.erase(CP);
940       
941       // Now that we found the entry, make sure this isn't the entry that
942       // the AbstractTypeMap points to.
943       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
944       if (Ty->isAbstract()) {
945         assert(AbstractTypeMap.count(Ty) &&
946                "Abstract type not in AbstractTypeMap?");
947         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
948         if (ATMEntryIt == I) {
949           // Yes, we are removing the representative entry for this type.
950           // See if there are any other entries of the same type.
951           typename MapTy::iterator TmpIt = ATMEntryIt;
952
953           // First check the entry before this one...
954           if (TmpIt != Map.begin()) {
955             --TmpIt;
956             if (TmpIt->first.first != Ty) // Not the same type, move back...
957               ++TmpIt;
958           }
959
960           // If we didn't find the same type, try to move forward...
961           if (TmpIt == ATMEntryIt) {
962             ++TmpIt;
963             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
964               --TmpIt;   // No entry afterwards with the same type
965           }
966
967           // If there is another entry in the map of the same abstract type,
968           // update the AbstractTypeMap entry now.
969           if (TmpIt != ATMEntryIt) {
970             ATMEntryIt = TmpIt;
971           } else {
972             // Otherwise, we are removing the last instance of this type
973             // from the table.  Remove from the ATM, and from user list.
974             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
975             AbstractTypeMap.erase(Ty);
976           }
977         }
978       }
979
980       Map.erase(I);
981     }
982
983     
984     /// MoveConstantToNewSlot - If we are about to change C to be the element
985     /// specified by I, update our internal data structures to reflect this
986     /// fact.
987     /// NOTE: This function is not locked. It is the responsibility of the
988     /// caller to enforce proper synchronization if using this method.
989     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
990       // First, remove the old location of the specified constant in the map.
991       typename MapTy::iterator OldI = FindExistingElement(C);
992       assert(OldI != Map.end() && "Constant not found in constant table!");
993       assert(OldI->second == C && "Didn't find correct element?");
994       
995       // If this constant is the representative element for its abstract type,
996       // update the AbstractTypeMap so that the representative element is I.
997       if (C->getType()->isAbstract()) {
998         typename AbstractTypeMapTy::iterator ATI =
999             AbstractTypeMap.find(C->getType());
1000         assert(ATI != AbstractTypeMap.end() &&
1001                "Abstract type not in AbstractTypeMap?");
1002         if (ATI->second == OldI)
1003           ATI->second = I;
1004       }
1005       
1006       // Remove the old entry from the map.
1007       Map.erase(OldI);
1008       
1009       // Update the inverse map so that we know that this constant is now
1010       // located at descriptor I.
1011       if (HasLargeKey) {
1012         assert(I->second == C && "Bad inversemap entry!");
1013         InverseMap[C] = I;
1014       }
1015     }
1016     
1017     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1018       sys::SmartScopedLock<true> Lock(ValueMapLock);
1019       typename AbstractTypeMapTy::iterator I =
1020         AbstractTypeMap.find(cast<Type>(OldTy));
1021
1022       assert(I != AbstractTypeMap.end() &&
1023              "Abstract type not in AbstractTypeMap?");
1024
1025       // Convert a constant at a time until the last one is gone.  The last one
1026       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1027       // eliminated eventually.
1028       do {
1029         ConvertConstantType<ConstantClass,
1030                             TypeClass>::convert(
1031                                 static_cast<ConstantClass *>(I->second->second),
1032                                                 cast<TypeClass>(NewTy));
1033
1034         I = AbstractTypeMap.find(cast<Type>(OldTy));
1035       } while (I != AbstractTypeMap.end());
1036     }
1037
1038     // If the type became concrete without being refined to any other existing
1039     // type, we just remove ourselves from the ATU list.
1040     void typeBecameConcrete(const DerivedType *AbsTy) {
1041       AbsTy->removeAbstractTypeUser(this);
1042     }
1043
1044     void dump() const {
1045       DOUT << "Constant.cpp: ValueMap\n";
1046     }
1047   };
1048 }
1049
1050
1051
1052 //---- ConstantAggregateZero::get() implementation...
1053 //
1054 namespace llvm {
1055   // ConstantAggregateZero does not take extra "value" argument...
1056   template<class ValType>
1057   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1058     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1059       return new ConstantAggregateZero(Ty);
1060     }
1061   };
1062
1063   template<>
1064   struct ConvertConstantType<ConstantAggregateZero, Type> {
1065     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1066       // Make everyone now use a constant of the new type...
1067       Constant *New = ConstantAggregateZero::get(NewTy);
1068       assert(New != OldC && "Didn't replace constant??");
1069       OldC->uncheckedReplaceAllUsesWith(New);
1070       OldC->destroyConstant();     // This constant is now dead, destroy it.
1071     }
1072   };
1073 }
1074
1075 static ManagedStatic<ValueMap<char, Type, 
1076                               ConstantAggregateZero> > AggZeroConstants;
1077
1078 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1079
1080 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1081   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1082          "Cannot create an aggregate zero of non-aggregate type!");
1083   
1084   // Implicitly locked.
1085   return AggZeroConstants->getOrCreate(Ty, 0);
1086 }
1087
1088 /// destroyConstant - Remove the constant from the constant table...
1089 ///
1090 void ConstantAggregateZero::destroyConstant() {
1091   // Implicitly locked.
1092   AggZeroConstants->remove(this);
1093   destroyConstantImpl();
1094 }
1095
1096 //---- ConstantArray::get() implementation...
1097 //
1098 namespace llvm {
1099   template<>
1100   struct ConvertConstantType<ConstantArray, ArrayType> {
1101     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1102       // Make everyone now use a constant of the new type...
1103       std::vector<Constant*> C;
1104       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1105         C.push_back(cast<Constant>(OldC->getOperand(i)));
1106       Constant *New = ConstantArray::get(NewTy, C);
1107       assert(New != OldC && "Didn't replace constant??");
1108       OldC->uncheckedReplaceAllUsesWith(New);
1109       OldC->destroyConstant();    // This constant is now dead, destroy it.
1110     }
1111   };
1112 }
1113
1114 static std::vector<Constant*> getValType(ConstantArray *CA) {
1115   std::vector<Constant*> Elements;
1116   Elements.reserve(CA->getNumOperands());
1117   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1118     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1119   return Elements;
1120 }
1121
1122 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1123                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1124 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1125
1126 Constant *ConstantArray::get(const ArrayType *Ty,
1127                              const std::vector<Constant*> &V) {
1128   // If this is an all-zero array, return a ConstantAggregateZero object
1129   if (!V.empty()) {
1130     Constant *C = V[0];
1131     if (!C->isNullValue()) {
1132       // Implicitly locked.
1133       return ArrayConstants->getOrCreate(Ty, V);
1134     }
1135     for (unsigned i = 1, e = V.size(); i != e; ++i)
1136       if (V[i] != C) {
1137         // Implicitly locked.
1138         return ArrayConstants->getOrCreate(Ty, V);
1139       }
1140   }
1141   
1142   return ConstantAggregateZero::get(Ty);
1143 }
1144
1145 /// destroyConstant - Remove the constant from the constant table...
1146 ///
1147 void ConstantArray::destroyConstant() {
1148   // Implicitly locked.
1149   ArrayConstants->remove(this);
1150   destroyConstantImpl();
1151 }
1152
1153 /// isString - This method returns true if the array is an array of i8, and 
1154 /// if the elements of the array are all ConstantInt's.
1155 bool ConstantArray::isString() const {
1156   // Check the element type for i8...
1157   if (getType()->getElementType() != Type::Int8Ty)
1158     return false;
1159   // Check the elements to make sure they are all integers, not constant
1160   // expressions.
1161   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1162     if (!isa<ConstantInt>(getOperand(i)))
1163       return false;
1164   return true;
1165 }
1166
1167 /// isCString - This method returns true if the array is a string (see
1168 /// isString) and it ends in a null byte \\0 and does not contains any other
1169 /// null bytes except its terminator.
1170 bool ConstantArray::isCString() const {
1171   // Check the element type for i8...
1172   if (getType()->getElementType() != Type::Int8Ty)
1173     return false;
1174
1175   // Last element must be a null.
1176   if (!getOperand(getNumOperands()-1)->isNullValue())
1177     return false;
1178   // Other elements must be non-null integers.
1179   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1180     if (!isa<ConstantInt>(getOperand(i)))
1181       return false;
1182     if (getOperand(i)->isNullValue())
1183       return false;
1184   }
1185   return true;
1186 }
1187
1188
1189 /// getAsString - If the sub-element type of this array is i8
1190 /// then this method converts the array to an std::string and returns it.
1191 /// Otherwise, it asserts out.
1192 ///
1193 std::string ConstantArray::getAsString() const {
1194   assert(isString() && "Not a string!");
1195   std::string Result;
1196   Result.reserve(getNumOperands());
1197   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1198     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1199   return Result;
1200 }
1201
1202
1203 //---- ConstantStruct::get() implementation...
1204 //
1205
1206 namespace llvm {
1207   template<>
1208   struct ConvertConstantType<ConstantStruct, StructType> {
1209     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1210       // Make everyone now use a constant of the new type...
1211       std::vector<Constant*> C;
1212       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1213         C.push_back(cast<Constant>(OldC->getOperand(i)));
1214       Constant *New = ConstantStruct::get(NewTy, C);
1215       assert(New != OldC && "Didn't replace constant??");
1216
1217       OldC->uncheckedReplaceAllUsesWith(New);
1218       OldC->destroyConstant();    // This constant is now dead, destroy it.
1219     }
1220   };
1221 }
1222
1223 typedef ValueMap<std::vector<Constant*>, StructType,
1224                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1225 static ManagedStatic<StructConstantsTy> StructConstants;
1226
1227 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1228   std::vector<Constant*> Elements;
1229   Elements.reserve(CS->getNumOperands());
1230   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1231     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1232   return Elements;
1233 }
1234
1235 Constant *ConstantStruct::get(const StructType *Ty,
1236                               const std::vector<Constant*> &V) {
1237   // Create a ConstantAggregateZero value if all elements are zeros...
1238   for (unsigned i = 0, e = V.size(); i != e; ++i)
1239     if (!V[i]->isNullValue())
1240       // Implicitly locked.
1241       return StructConstants->getOrCreate(Ty, V);
1242
1243   return ConstantAggregateZero::get(Ty);
1244 }
1245
1246 // destroyConstant - Remove the constant from the constant table...
1247 //
1248 void ConstantStruct::destroyConstant() {
1249   // Implicitly locked.
1250   StructConstants->remove(this);
1251   destroyConstantImpl();
1252 }
1253
1254 //---- ConstantVector::get() implementation...
1255 //
1256 namespace llvm {
1257   template<>
1258   struct ConvertConstantType<ConstantVector, VectorType> {
1259     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1260       // Make everyone now use a constant of the new type...
1261       std::vector<Constant*> C;
1262       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1263         C.push_back(cast<Constant>(OldC->getOperand(i)));
1264       Constant *New = ConstantVector::get(NewTy, C);
1265       assert(New != OldC && "Didn't replace constant??");
1266       OldC->uncheckedReplaceAllUsesWith(New);
1267       OldC->destroyConstant();    // This constant is now dead, destroy it.
1268     }
1269   };
1270 }
1271
1272 static std::vector<Constant*> getValType(ConstantVector *CP) {
1273   std::vector<Constant*> Elements;
1274   Elements.reserve(CP->getNumOperands());
1275   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1276     Elements.push_back(CP->getOperand(i));
1277   return Elements;
1278 }
1279
1280 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1281                               ConstantVector> > VectorConstants;
1282
1283 Constant *ConstantVector::get(const VectorType *Ty,
1284                               const std::vector<Constant*> &V) {
1285   assert(!V.empty() && "Vectors can't be empty");
1286   // If this is an all-undef or alll-zero vector, return a
1287   // ConstantAggregateZero or UndefValue.
1288   Constant *C = V[0];
1289   bool isZero = C->isNullValue();
1290   bool isUndef = isa<UndefValue>(C);
1291
1292   if (isZero || isUndef) {
1293     for (unsigned i = 1, e = V.size(); i != e; ++i)
1294       if (V[i] != C) {
1295         isZero = isUndef = false;
1296         break;
1297       }
1298   }
1299   
1300   if (isZero)
1301     return ConstantAggregateZero::get(Ty);
1302   if (isUndef)
1303     return UndefValue::get(Ty);
1304     
1305   // Implicitly locked.
1306   return VectorConstants->getOrCreate(Ty, V);
1307 }
1308
1309 // destroyConstant - Remove the constant from the constant table...
1310 //
1311 void ConstantVector::destroyConstant() {
1312   // Implicitly locked.
1313   VectorConstants->remove(this);
1314   destroyConstantImpl();
1315 }
1316
1317 /// This function will return true iff every element in this vector constant
1318 /// is set to all ones.
1319 /// @returns true iff this constant's emements are all set to all ones.
1320 /// @brief Determine if the value is all ones.
1321 bool ConstantVector::isAllOnesValue() const {
1322   // Check out first element.
1323   const Constant *Elt = getOperand(0);
1324   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1325   if (!CI || !CI->isAllOnesValue()) return false;
1326   // Then make sure all remaining elements point to the same value.
1327   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1328     if (getOperand(I) != Elt) return false;
1329   }
1330   return true;
1331 }
1332
1333 /// getSplatValue - If this is a splat constant, where all of the
1334 /// elements have the same value, return that value. Otherwise return null.
1335 Constant *ConstantVector::getSplatValue() {
1336   // Check out first element.
1337   Constant *Elt = getOperand(0);
1338   // Then make sure all remaining elements point to the same value.
1339   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1340     if (getOperand(I) != Elt) return 0;
1341   return Elt;
1342 }
1343
1344 //---- ConstantPointerNull::get() implementation...
1345 //
1346
1347 namespace llvm {
1348   // ConstantPointerNull does not take extra "value" argument...
1349   template<class ValType>
1350   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1351     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1352       return new ConstantPointerNull(Ty);
1353     }
1354   };
1355
1356   template<>
1357   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1358     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1359       // Make everyone now use a constant of the new type...
1360       Constant *New = ConstantPointerNull::get(NewTy);
1361       assert(New != OldC && "Didn't replace constant??");
1362       OldC->uncheckedReplaceAllUsesWith(New);
1363       OldC->destroyConstant();     // This constant is now dead, destroy it.
1364     }
1365   };
1366 }
1367
1368 static ManagedStatic<ValueMap<char, PointerType, 
1369                               ConstantPointerNull> > NullPtrConstants;
1370
1371 static char getValType(ConstantPointerNull *) {
1372   return 0;
1373 }
1374
1375
1376 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1377   // Implicitly locked.
1378   return NullPtrConstants->getOrCreate(Ty, 0);
1379 }
1380
1381 // destroyConstant - Remove the constant from the constant table...
1382 //
1383 void ConstantPointerNull::destroyConstant() {
1384   // Implicitly locked.
1385   NullPtrConstants->remove(this);
1386   destroyConstantImpl();
1387 }
1388
1389
1390 //---- UndefValue::get() implementation...
1391 //
1392
1393 namespace llvm {
1394   // UndefValue does not take extra "value" argument...
1395   template<class ValType>
1396   struct ConstantCreator<UndefValue, Type, ValType> {
1397     static UndefValue *create(const Type *Ty, const ValType &V) {
1398       return new UndefValue(Ty);
1399     }
1400   };
1401
1402   template<>
1403   struct ConvertConstantType<UndefValue, Type> {
1404     static void convert(UndefValue *OldC, const Type *NewTy) {
1405       // Make everyone now use a constant of the new type.
1406       Constant *New = UndefValue::get(NewTy);
1407       assert(New != OldC && "Didn't replace constant??");
1408       OldC->uncheckedReplaceAllUsesWith(New);
1409       OldC->destroyConstant();     // This constant is now dead, destroy it.
1410     }
1411   };
1412 }
1413
1414 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1415
1416 static char getValType(UndefValue *) {
1417   return 0;
1418 }
1419
1420
1421 UndefValue *UndefValue::get(const Type *Ty) {
1422   // Implicitly locked.
1423   return UndefValueConstants->getOrCreate(Ty, 0);
1424 }
1425
1426 // destroyConstant - Remove the constant from the constant table.
1427 //
1428 void UndefValue::destroyConstant() {
1429   // Implicitly locked.
1430   UndefValueConstants->remove(this);
1431   destroyConstantImpl();
1432 }
1433
1434 //---- MDString::get() implementation
1435 //
1436
1437 MDString::MDString(const char *begin, const char *end)
1438   : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1439     StrBegin(begin), StrEnd(end) {}
1440
1441 void MDString::destroyConstant() {
1442   getType()->getContext().erase(this);
1443   destroyConstantImpl();
1444 }
1445
1446 //---- MDNode::get() implementation
1447 //
1448
1449 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1450   : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1451   for (unsigned i = 0; i != NumVals; ++i)
1452     Node.push_back(ElementVH(Vals[i], this));
1453 }
1454
1455 void MDNode::Profile(FoldingSetNodeID &ID) const {
1456   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1457     ID.AddPointer(*I);
1458 }
1459
1460 void MDNode::destroyConstant() {
1461   getType()->getContext().erase(this);
1462   destroyConstantImpl();
1463 }
1464
1465 //---- ConstantExpr::get() implementations...
1466 //
1467
1468 namespace {
1469
1470 struct ExprMapKeyType {
1471   typedef SmallVector<unsigned, 4> IndexList;
1472
1473   ExprMapKeyType(unsigned opc,
1474       const std::vector<Constant*> &ops,
1475       unsigned short pred = 0,
1476       const IndexList &inds = IndexList())
1477         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1478   uint16_t opcode;
1479   uint16_t predicate;
1480   std::vector<Constant*> operands;
1481   IndexList indices;
1482   bool operator==(const ExprMapKeyType& that) const {
1483     return this->opcode == that.opcode &&
1484            this->predicate == that.predicate &&
1485            this->operands == that.operands &&
1486            this->indices == that.indices;
1487   }
1488   bool operator<(const ExprMapKeyType & that) const {
1489     return this->opcode < that.opcode ||
1490       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1491       (this->opcode == that.opcode && this->predicate == that.predicate &&
1492        this->operands < that.operands) ||
1493       (this->opcode == that.opcode && this->predicate == that.predicate &&
1494        this->operands == that.operands && this->indices < that.indices);
1495   }
1496
1497   bool operator!=(const ExprMapKeyType& that) const {
1498     return !(*this == that);
1499   }
1500 };
1501
1502 }
1503
1504 namespace llvm {
1505   template<>
1506   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1507     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1508         unsigned short pred = 0) {
1509       if (Instruction::isCast(V.opcode))
1510         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1511       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1512            V.opcode < Instruction::BinaryOpsEnd))
1513         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1514       if (V.opcode == Instruction::Select)
1515         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1516                                       V.operands[2]);
1517       if (V.opcode == Instruction::ExtractElement)
1518         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1519       if (V.opcode == Instruction::InsertElement)
1520         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1521                                              V.operands[2]);
1522       if (V.opcode == Instruction::ShuffleVector)
1523         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1524                                              V.operands[2]);
1525       if (V.opcode == Instruction::InsertValue)
1526         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1527                                            V.indices, Ty);
1528       if (V.opcode == Instruction::ExtractValue)
1529         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1530       if (V.opcode == Instruction::GetElementPtr) {
1531         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1532         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1533       }
1534
1535       // The compare instructions are weird. We have to encode the predicate
1536       // value and it is combined with the instruction opcode by multiplying
1537       // the opcode by one hundred. We must decode this to get the predicate.
1538       if (V.opcode == Instruction::ICmp)
1539         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1540                                        V.operands[0], V.operands[1]);
1541       if (V.opcode == Instruction::FCmp) 
1542         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1543                                        V.operands[0], V.operands[1]);
1544       llvm_unreachable("Invalid ConstantExpr!");
1545       return 0;
1546     }
1547   };
1548
1549   template<>
1550   struct ConvertConstantType<ConstantExpr, Type> {
1551     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1552       Constant *New;
1553       switch (OldC->getOpcode()) {
1554       case Instruction::Trunc:
1555       case Instruction::ZExt:
1556       case Instruction::SExt:
1557       case Instruction::FPTrunc:
1558       case Instruction::FPExt:
1559       case Instruction::UIToFP:
1560       case Instruction::SIToFP:
1561       case Instruction::FPToUI:
1562       case Instruction::FPToSI:
1563       case Instruction::PtrToInt:
1564       case Instruction::IntToPtr:
1565       case Instruction::BitCast:
1566         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1567                                     NewTy);
1568         break;
1569       case Instruction::Select:
1570         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1571                                         OldC->getOperand(1),
1572                                         OldC->getOperand(2));
1573         break;
1574       default:
1575         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1576                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1577         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1578                                   OldC->getOperand(1));
1579         break;
1580       case Instruction::GetElementPtr:
1581         // Make everyone now use a constant of the new type...
1582         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1583         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1584                                                &Idx[0], Idx.size());
1585         break;
1586       }
1587
1588       assert(New != OldC && "Didn't replace constant??");
1589       OldC->uncheckedReplaceAllUsesWith(New);
1590       OldC->destroyConstant();    // This constant is now dead, destroy it.
1591     }
1592   };
1593 } // end namespace llvm
1594
1595
1596 static ExprMapKeyType getValType(ConstantExpr *CE) {
1597   std::vector<Constant*> Operands;
1598   Operands.reserve(CE->getNumOperands());
1599   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1600     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1601   return ExprMapKeyType(CE->getOpcode(), Operands, 
1602       CE->isCompare() ? CE->getPredicate() : 0,
1603       CE->hasIndices() ?
1604         CE->getIndices() : SmallVector<unsigned, 4>());
1605 }
1606
1607 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1608                               ConstantExpr> > ExprConstants;
1609
1610 /// This is a utility function to handle folding of casts and lookup of the
1611 /// cast in the ExprConstants map. It is used by the various get* methods below.
1612 static inline Constant *getFoldedCast(
1613   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1614   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1615   // Fold a few common cases
1616   if (Constant *FC = 
1617                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1618     return FC;
1619
1620   // Look up the constant in the table first to ensure uniqueness
1621   std::vector<Constant*> argVec(1, C);
1622   ExprMapKeyType Key(opc, argVec);
1623   
1624   // Implicitly locked.
1625   return ExprConstants->getOrCreate(Ty, Key);
1626 }
1627  
1628 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1629   Instruction::CastOps opc = Instruction::CastOps(oc);
1630   assert(Instruction::isCast(opc) && "opcode out of range");
1631   assert(C && Ty && "Null arguments to getCast");
1632   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1633
1634   switch (opc) {
1635     default:
1636       llvm_unreachable("Invalid cast opcode");
1637       break;
1638     case Instruction::Trunc:    return getTrunc(C, Ty);
1639     case Instruction::ZExt:     return getZExt(C, Ty);
1640     case Instruction::SExt:     return getSExt(C, Ty);
1641     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1642     case Instruction::FPExt:    return getFPExtend(C, Ty);
1643     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1644     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1645     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1646     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1647     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1648     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1649     case Instruction::BitCast:  return getBitCast(C, Ty);
1650   }
1651   return 0;
1652
1653
1654 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1655   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1656     return getCast(Instruction::BitCast, C, Ty);
1657   return getCast(Instruction::ZExt, C, Ty);
1658 }
1659
1660 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1661   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1662     return getCast(Instruction::BitCast, C, Ty);
1663   return getCast(Instruction::SExt, C, Ty);
1664 }
1665
1666 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1667   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1668     return getCast(Instruction::BitCast, C, Ty);
1669   return getCast(Instruction::Trunc, C, Ty);
1670 }
1671
1672 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1673   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1674   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1675
1676   if (Ty->isInteger())
1677     return getCast(Instruction::PtrToInt, S, Ty);
1678   return getCast(Instruction::BitCast, S, Ty);
1679 }
1680
1681 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1682                                        bool isSigned) {
1683   assert(C->getType()->isIntOrIntVector() &&
1684          Ty->isIntOrIntVector() && "Invalid cast");
1685   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1686   unsigned DstBits = Ty->getScalarSizeInBits();
1687   Instruction::CastOps opcode =
1688     (SrcBits == DstBits ? Instruction::BitCast :
1689      (SrcBits > DstBits ? Instruction::Trunc :
1690       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1691   return getCast(opcode, C, Ty);
1692 }
1693
1694 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1695   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1696          "Invalid cast");
1697   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1698   unsigned DstBits = Ty->getScalarSizeInBits();
1699   if (SrcBits == DstBits)
1700     return C; // Avoid a useless cast
1701   Instruction::CastOps opcode =
1702      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1703   return getCast(opcode, C, Ty);
1704 }
1705
1706 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1707 #ifndef NDEBUG
1708   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1709   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1710 #endif
1711   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1712   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1713   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1714   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1715          "SrcTy must be larger than DestTy for Trunc!");
1716
1717   return getFoldedCast(Instruction::Trunc, C, Ty);
1718 }
1719
1720 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1721 #ifndef NDEBUG
1722   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1723   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1724 #endif
1725   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1726   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1727   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1728   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1729          "SrcTy must be smaller than DestTy for SExt!");
1730
1731   return getFoldedCast(Instruction::SExt, C, Ty);
1732 }
1733
1734 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1735 #ifndef NDEBUG
1736   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1737   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1738 #endif
1739   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1740   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1741   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1742   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1743          "SrcTy must be smaller than DestTy for ZExt!");
1744
1745   return getFoldedCast(Instruction::ZExt, C, Ty);
1746 }
1747
1748 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1749 #ifndef NDEBUG
1750   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1751   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1752 #endif
1753   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1754   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1755          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1756          "This is an illegal floating point truncation!");
1757   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1758 }
1759
1760 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1761 #ifndef NDEBUG
1762   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1763   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1764 #endif
1765   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1766   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1767          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1768          "This is an illegal floating point extension!");
1769   return getFoldedCast(Instruction::FPExt, C, Ty);
1770 }
1771
1772 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1773 #ifndef NDEBUG
1774   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1775   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1776 #endif
1777   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1778   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1779          "This is an illegal uint to floating point cast!");
1780   return getFoldedCast(Instruction::UIToFP, C, Ty);
1781 }
1782
1783 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1784 #ifndef NDEBUG
1785   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1786   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1787 #endif
1788   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1789   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1790          "This is an illegal sint to floating point cast!");
1791   return getFoldedCast(Instruction::SIToFP, C, Ty);
1792 }
1793
1794 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1795 #ifndef NDEBUG
1796   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1797   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1798 #endif
1799   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1800   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1801          "This is an illegal floating point to uint cast!");
1802   return getFoldedCast(Instruction::FPToUI, C, Ty);
1803 }
1804
1805 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1806 #ifndef NDEBUG
1807   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1808   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1809 #endif
1810   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1811   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1812          "This is an illegal floating point to sint cast!");
1813   return getFoldedCast(Instruction::FPToSI, C, Ty);
1814 }
1815
1816 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1817   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1818   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1819   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1820 }
1821
1822 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1823   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1824   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1825   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1826 }
1827
1828 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1829   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1830   // can't cast pointers to anything but pointers.
1831 #ifndef NDEBUG
1832   const Type *SrcTy = C->getType();
1833   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1834          "BitCast cannot cast pointer to non-pointer and vice versa");
1835
1836   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1837   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1838   // destination bit widths are identical.
1839   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1840   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1841 #endif
1842   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1843   
1844   // It is common to ask for a bitcast of a value to its own type, handle this
1845   // speedily.
1846   if (C->getType() == DstTy) return C;
1847   
1848   return getFoldedCast(Instruction::BitCast, C, DstTy);
1849 }
1850
1851 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1852                               Constant *C1, Constant *C2) {
1853   // Check the operands for consistency first
1854   assert(Opcode >= Instruction::BinaryOpsBegin &&
1855          Opcode <  Instruction::BinaryOpsEnd   &&
1856          "Invalid opcode in binary constant expression");
1857   assert(C1->getType() == C2->getType() &&
1858          "Operand types in binary constant expression should match");
1859
1860   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1861     if (Constant *FC = ConstantFoldBinaryInstruction(
1862                                             getGlobalContext(), Opcode, C1, C2))
1863       return FC;          // Fold a few common cases...
1864
1865   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1866   ExprMapKeyType Key(Opcode, argVec);
1867   
1868   // Implicitly locked.
1869   return ExprConstants->getOrCreate(ReqTy, Key);
1870 }
1871
1872 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1873                                      Constant *C1, Constant *C2) {
1874   switch (predicate) {
1875     default: llvm_unreachable("Invalid CmpInst predicate");
1876     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1877     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1878     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1879     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1880     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1881     case CmpInst::FCMP_TRUE:
1882       return getFCmp(predicate, C1, C2);
1883
1884     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1885     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1886     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1887     case CmpInst::ICMP_SLE:
1888       return getICmp(predicate, C1, C2);
1889   }
1890 }
1891
1892 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1893   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1894   if (C1->getType()->isFPOrFPVector()) {
1895     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1896     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1897     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1898   }
1899 #ifndef NDEBUG
1900   switch (Opcode) {
1901   case Instruction::Add:
1902   case Instruction::Sub:
1903   case Instruction::Mul:
1904     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1905     assert(C1->getType()->isIntOrIntVector() &&
1906            "Tried to create an integer operation on a non-integer type!");
1907     break;
1908   case Instruction::FAdd:
1909   case Instruction::FSub:
1910   case Instruction::FMul:
1911     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1912     assert(C1->getType()->isFPOrFPVector() &&
1913            "Tried to create a floating-point operation on a "
1914            "non-floating-point type!");
1915     break;
1916   case Instruction::UDiv: 
1917   case Instruction::SDiv: 
1918     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1919     assert(C1->getType()->isIntOrIntVector() &&
1920            "Tried to create an arithmetic operation on a non-arithmetic type!");
1921     break;
1922   case Instruction::FDiv:
1923     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1924     assert(C1->getType()->isFPOrFPVector() &&
1925            "Tried to create an arithmetic operation on a non-arithmetic type!");
1926     break;
1927   case Instruction::URem: 
1928   case Instruction::SRem: 
1929     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1930     assert(C1->getType()->isIntOrIntVector() &&
1931            "Tried to create an arithmetic operation on a non-arithmetic type!");
1932     break;
1933   case Instruction::FRem:
1934     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1935     assert(C1->getType()->isFPOrFPVector() &&
1936            "Tried to create an arithmetic operation on a non-arithmetic type!");
1937     break;
1938   case Instruction::And:
1939   case Instruction::Or:
1940   case Instruction::Xor:
1941     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1942     assert(C1->getType()->isIntOrIntVector() &&
1943            "Tried to create a logical operation on a non-integral type!");
1944     break;
1945   case Instruction::Shl:
1946   case Instruction::LShr:
1947   case Instruction::AShr:
1948     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1949     assert(C1->getType()->isIntOrIntVector() &&
1950            "Tried to create a shift operation on a non-integer type!");
1951     break;
1952   default:
1953     break;
1954   }
1955 #endif
1956
1957   return getTy(C1->getType(), Opcode, C1, C2);
1958 }
1959
1960 Constant *ConstantExpr::getCompare(unsigned short pred, 
1961                             Constant *C1, Constant *C2) {
1962   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1963   return getCompareTy(pred, C1, C2);
1964 }
1965
1966 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1967                                     Constant *V1, Constant *V2) {
1968   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1969
1970   if (ReqTy == V1->getType())
1971     if (Constant *SC = ConstantFoldSelectInstruction(
1972                                                 getGlobalContext(), C, V1, V2))
1973       return SC;        // Fold common cases
1974
1975   std::vector<Constant*> argVec(3, C);
1976   argVec[1] = V1;
1977   argVec[2] = V2;
1978   ExprMapKeyType Key(Instruction::Select, argVec);
1979   
1980   // Implicitly locked.
1981   return ExprConstants->getOrCreate(ReqTy, Key);
1982 }
1983
1984 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1985                                            Value* const *Idxs,
1986                                            unsigned NumIdx) {
1987   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1988                                            Idxs+NumIdx) ==
1989          cast<PointerType>(ReqTy)->getElementType() &&
1990          "GEP indices invalid!");
1991
1992   if (Constant *FC = ConstantFoldGetElementPtr(
1993                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1994     return FC;          // Fold a few common cases...
1995
1996   assert(isa<PointerType>(C->getType()) &&
1997          "Non-pointer type for constant GetElementPtr expression");
1998   // Look up the constant in the table first to ensure uniqueness
1999   std::vector<Constant*> ArgVec;
2000   ArgVec.reserve(NumIdx+1);
2001   ArgVec.push_back(C);
2002   for (unsigned i = 0; i != NumIdx; ++i)
2003     ArgVec.push_back(cast<Constant>(Idxs[i]));
2004   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2005
2006   // Implicitly locked.
2007   return ExprConstants->getOrCreate(ReqTy, Key);
2008 }
2009
2010 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2011                                          unsigned NumIdx) {
2012   // Get the result type of the getelementptr!
2013   const Type *Ty = 
2014     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2015   assert(Ty && "GEP indices invalid!");
2016   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2017   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2018 }
2019
2020 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2021                                          unsigned NumIdx) {
2022   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2023 }
2024
2025
2026 Constant *
2027 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2028   assert(LHS->getType() == RHS->getType());
2029   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
2030          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2031
2032   if (Constant *FC = ConstantFoldCompareInstruction(
2033                                              getGlobalContext(),pred, LHS, RHS))
2034     return FC;          // Fold a few common cases...
2035
2036   // Look up the constant in the table first to ensure uniqueness
2037   std::vector<Constant*> ArgVec;
2038   ArgVec.push_back(LHS);
2039   ArgVec.push_back(RHS);
2040   // Get the key type with both the opcode and predicate
2041   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2042
2043   // Implicitly locked.
2044   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2045 }
2046
2047 Constant *
2048 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2049   assert(LHS->getType() == RHS->getType());
2050   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2051
2052   if (Constant *FC = ConstantFoldCompareInstruction(
2053                                             getGlobalContext(), pred, LHS, RHS))
2054     return FC;          // Fold a few common cases...
2055
2056   // Look up the constant in the table first to ensure uniqueness
2057   std::vector<Constant*> ArgVec;
2058   ArgVec.push_back(LHS);
2059   ArgVec.push_back(RHS);
2060   // Get the key type with both the opcode and predicate
2061   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2062   
2063   // Implicitly locked.
2064   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2065 }
2066
2067 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2068                                             Constant *Idx) {
2069   if (Constant *FC = ConstantFoldExtractElementInstruction(
2070                                                   getGlobalContext(), Val, Idx))
2071     return FC;          // Fold a few common cases...
2072   // Look up the constant in the table first to ensure uniqueness
2073   std::vector<Constant*> ArgVec(1, Val);
2074   ArgVec.push_back(Idx);
2075   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2076   
2077   // Implicitly locked.
2078   return ExprConstants->getOrCreate(ReqTy, Key);
2079 }
2080
2081 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2082   assert(isa<VectorType>(Val->getType()) &&
2083          "Tried to create extractelement operation on non-vector type!");
2084   assert(Idx->getType() == Type::Int32Ty &&
2085          "Extractelement index must be i32 type!");
2086   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2087                              Val, Idx);
2088 }
2089
2090 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2091                                            Constant *Elt, Constant *Idx) {
2092   if (Constant *FC = ConstantFoldInsertElementInstruction(
2093                                             getGlobalContext(), Val, Elt, Idx))
2094     return FC;          // Fold a few common cases...
2095   // Look up the constant in the table first to ensure uniqueness
2096   std::vector<Constant*> ArgVec(1, Val);
2097   ArgVec.push_back(Elt);
2098   ArgVec.push_back(Idx);
2099   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2100   
2101   // Implicitly locked.
2102   return ExprConstants->getOrCreate(ReqTy, Key);
2103 }
2104
2105 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
2106                                          Constant *Idx) {
2107   assert(isa<VectorType>(Val->getType()) &&
2108          "Tried to create insertelement operation on non-vector type!");
2109   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2110          && "Insertelement types must match!");
2111   assert(Idx->getType() == Type::Int32Ty &&
2112          "Insertelement index must be i32 type!");
2113   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2114 }
2115
2116 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2117                                            Constant *V2, Constant *Mask) {
2118   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2119                                               getGlobalContext(), V1, V2, Mask))
2120     return FC;          // Fold a few common cases...
2121   // Look up the constant in the table first to ensure uniqueness
2122   std::vector<Constant*> ArgVec(1, V1);
2123   ArgVec.push_back(V2);
2124   ArgVec.push_back(Mask);
2125   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2126   
2127   // Implicitly locked.
2128   return ExprConstants->getOrCreate(ReqTy, Key);
2129 }
2130
2131 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2132                                          Constant *Mask) {
2133   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2134          "Invalid shuffle vector constant expr operands!");
2135
2136   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2137   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2138   const Type *ShufTy = VectorType::get(EltTy, NElts);
2139   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2140 }
2141
2142 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2143                                          Constant *Val,
2144                                         const unsigned *Idxs, unsigned NumIdx) {
2145   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2146                                           Idxs+NumIdx) == Val->getType() &&
2147          "insertvalue indices invalid!");
2148   assert(Agg->getType() == ReqTy &&
2149          "insertvalue type invalid!");
2150   assert(Agg->getType()->isFirstClassType() &&
2151          "Non-first-class type for constant InsertValue expression");
2152   Constant *FC = ConstantFoldInsertValueInstruction(
2153                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
2154   assert(FC && "InsertValue constant expr couldn't be folded!");
2155   return FC;
2156 }
2157
2158 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2159                                      const unsigned *IdxList, unsigned NumIdx) {
2160   assert(Agg->getType()->isFirstClassType() &&
2161          "Tried to create insertelement operation on non-first-class type!");
2162
2163   const Type *ReqTy = Agg->getType();
2164 #ifndef NDEBUG
2165   const Type *ValTy =
2166     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2167 #endif
2168   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2169   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2170 }
2171
2172 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2173                                         const unsigned *Idxs, unsigned NumIdx) {
2174   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2175                                           Idxs+NumIdx) == ReqTy &&
2176          "extractvalue indices invalid!");
2177   assert(Agg->getType()->isFirstClassType() &&
2178          "Non-first-class type for constant extractvalue expression");
2179   Constant *FC = ConstantFoldExtractValueInstruction(
2180                                          getGlobalContext(), Agg, Idxs, NumIdx);
2181   assert(FC && "ExtractValue constant expr couldn't be folded!");
2182   return FC;
2183 }
2184
2185 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2186                                      const unsigned *IdxList, unsigned NumIdx) {
2187   assert(Agg->getType()->isFirstClassType() &&
2188          "Tried to create extractelement operation on non-first-class type!");
2189
2190   const Type *ReqTy =
2191     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2192   assert(ReqTy && "extractvalue indices invalid!");
2193   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2194 }
2195
2196 // destroyConstant - Remove the constant from the constant table...
2197 //
2198 void ConstantExpr::destroyConstant() {
2199   // Implicitly locked.
2200   ExprConstants->remove(this);
2201   destroyConstantImpl();
2202 }
2203
2204 const char *ConstantExpr::getOpcodeName() const {
2205   return Instruction::getOpcodeName(getOpcode());
2206 }
2207
2208 //===----------------------------------------------------------------------===//
2209 //                replaceUsesOfWithOnConstant implementations
2210
2211 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2212 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2213 /// etc.
2214 ///
2215 /// Note that we intentionally replace all uses of From with To here.  Consider
2216 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2217 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2218 /// single invocation handles all 1000 uses.  Handling them one at a time would
2219 /// work, but would be really slow because it would have to unique each updated
2220 /// array instance.
2221 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2222                                                 Use *U) {
2223   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2224   Constant *ToC = cast<Constant>(To);
2225
2226   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2227   Lookup.first.first = getType();
2228   Lookup.second = this;
2229
2230   std::vector<Constant*> &Values = Lookup.first.second;
2231   Values.reserve(getNumOperands());  // Build replacement array.
2232
2233   // Fill values with the modified operands of the constant array.  Also, 
2234   // compute whether this turns into an all-zeros array.
2235   bool isAllZeros = false;
2236   unsigned NumUpdated = 0;
2237   if (!ToC->isNullValue()) {
2238     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2239       Constant *Val = cast<Constant>(O->get());
2240       if (Val == From) {
2241         Val = ToC;
2242         ++NumUpdated;
2243       }
2244       Values.push_back(Val);
2245     }
2246   } else {
2247     isAllZeros = true;
2248     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2249       Constant *Val = cast<Constant>(O->get());
2250       if (Val == From) {
2251         Val = ToC;
2252         ++NumUpdated;
2253       }
2254       Values.push_back(Val);
2255       if (isAllZeros) isAllZeros = Val->isNullValue();
2256     }
2257   }
2258   
2259   Constant *Replacement = 0;
2260   if (isAllZeros) {
2261     Replacement = ConstantAggregateZero::get(getType());
2262   } else {
2263     // Check to see if we have this array type already.
2264     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2265     bool Exists;
2266     ArrayConstantsTy::MapTy::iterator I =
2267       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2268     
2269     if (Exists) {
2270       Replacement = I->second;
2271     } else {
2272       // Okay, the new shape doesn't exist in the system yet.  Instead of
2273       // creating a new constant array, inserting it, replaceallusesof'ing the
2274       // old with the new, then deleting the old... just update the current one
2275       // in place!
2276       ArrayConstants->MoveConstantToNewSlot(this, I);
2277       
2278       // Update to the new value.  Optimize for the case when we have a single
2279       // operand that we're changing, but handle bulk updates efficiently.
2280       if (NumUpdated == 1) {
2281         unsigned OperandToUpdate = U-OperandList;
2282         assert(getOperand(OperandToUpdate) == From &&
2283                "ReplaceAllUsesWith broken!");
2284         setOperand(OperandToUpdate, ToC);
2285       } else {
2286         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2287           if (getOperand(i) == From)
2288             setOperand(i, ToC);
2289       }
2290       return;
2291     }
2292   }
2293  
2294   // Otherwise, I do need to replace this with an existing value.
2295   assert(Replacement != this && "I didn't contain From!");
2296   
2297   // Everyone using this now uses the replacement.
2298   uncheckedReplaceAllUsesWith(Replacement);
2299   
2300   // Delete the old constant!
2301   destroyConstant();
2302 }
2303
2304 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2305                                                  Use *U) {
2306   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2307   Constant *ToC = cast<Constant>(To);
2308
2309   unsigned OperandToUpdate = U-OperandList;
2310   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2311
2312   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2313   Lookup.first.first = getType();
2314   Lookup.second = this;
2315   std::vector<Constant*> &Values = Lookup.first.second;
2316   Values.reserve(getNumOperands());  // Build replacement struct.
2317   
2318   
2319   // Fill values with the modified operands of the constant struct.  Also, 
2320   // compute whether this turns into an all-zeros struct.
2321   bool isAllZeros = false;
2322   if (!ToC->isNullValue()) {
2323     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2324       Values.push_back(cast<Constant>(O->get()));
2325   } else {
2326     isAllZeros = true;
2327     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2328       Constant *Val = cast<Constant>(O->get());
2329       Values.push_back(Val);
2330       if (isAllZeros) isAllZeros = Val->isNullValue();
2331     }
2332   }
2333   Values[OperandToUpdate] = ToC;
2334   
2335   Constant *Replacement = 0;
2336   if (isAllZeros) {
2337     Replacement = ConstantAggregateZero::get(getType());
2338   } else {
2339     // Check to see if we have this array type already.
2340     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2341     bool Exists;
2342     StructConstantsTy::MapTy::iterator I =
2343       StructConstants->InsertOrGetItem(Lookup, Exists);
2344     
2345     if (Exists) {
2346       Replacement = I->second;
2347     } else {
2348       // Okay, the new shape doesn't exist in the system yet.  Instead of
2349       // creating a new constant struct, inserting it, replaceallusesof'ing the
2350       // old with the new, then deleting the old... just update the current one
2351       // in place!
2352       StructConstants->MoveConstantToNewSlot(this, I);
2353       
2354       // Update to the new value.
2355       setOperand(OperandToUpdate, ToC);
2356       return;
2357     }
2358   }
2359   
2360   assert(Replacement != this && "I didn't contain From!");
2361   
2362   // Everyone using this now uses the replacement.
2363   uncheckedReplaceAllUsesWith(Replacement);
2364   
2365   // Delete the old constant!
2366   destroyConstant();
2367 }
2368
2369 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2370                                                  Use *U) {
2371   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2372   
2373   std::vector<Constant*> Values;
2374   Values.reserve(getNumOperands());  // Build replacement array...
2375   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2376     Constant *Val = getOperand(i);
2377     if (Val == From) Val = cast<Constant>(To);
2378     Values.push_back(Val);
2379   }
2380   
2381   Constant *Replacement = ConstantVector::get(getType(), Values);
2382   assert(Replacement != this && "I didn't contain From!");
2383   
2384   // Everyone using this now uses the replacement.
2385   uncheckedReplaceAllUsesWith(Replacement);
2386   
2387   // Delete the old constant!
2388   destroyConstant();
2389 }
2390
2391 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2392                                                Use *U) {
2393   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2394   Constant *To = cast<Constant>(ToV);
2395   
2396   Constant *Replacement = 0;
2397   if (getOpcode() == Instruction::GetElementPtr) {
2398     SmallVector<Constant*, 8> Indices;
2399     Constant *Pointer = getOperand(0);
2400     Indices.reserve(getNumOperands()-1);
2401     if (Pointer == From) Pointer = To;
2402     
2403     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2404       Constant *Val = getOperand(i);
2405       if (Val == From) Val = To;
2406       Indices.push_back(Val);
2407     }
2408     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2409                                                  &Indices[0], Indices.size());
2410   } else if (getOpcode() == Instruction::ExtractValue) {
2411     Constant *Agg = getOperand(0);
2412     if (Agg == From) Agg = To;
2413     
2414     const SmallVector<unsigned, 4> &Indices = getIndices();
2415     Replacement = ConstantExpr::getExtractValue(Agg,
2416                                                 &Indices[0], Indices.size());
2417   } else if (getOpcode() == Instruction::InsertValue) {
2418     Constant *Agg = getOperand(0);
2419     Constant *Val = getOperand(1);
2420     if (Agg == From) Agg = To;
2421     if (Val == From) Val = To;
2422     
2423     const SmallVector<unsigned, 4> &Indices = getIndices();
2424     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2425                                                &Indices[0], Indices.size());
2426   } else if (isCast()) {
2427     assert(getOperand(0) == From && "Cast only has one use!");
2428     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2429   } else if (getOpcode() == Instruction::Select) {
2430     Constant *C1 = getOperand(0);
2431     Constant *C2 = getOperand(1);
2432     Constant *C3 = getOperand(2);
2433     if (C1 == From) C1 = To;
2434     if (C2 == From) C2 = To;
2435     if (C3 == From) C3 = To;
2436     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2437   } else if (getOpcode() == Instruction::ExtractElement) {
2438     Constant *C1 = getOperand(0);
2439     Constant *C2 = getOperand(1);
2440     if (C1 == From) C1 = To;
2441     if (C2 == From) C2 = To;
2442     Replacement = ConstantExpr::getExtractElement(C1, C2);
2443   } else if (getOpcode() == Instruction::InsertElement) {
2444     Constant *C1 = getOperand(0);
2445     Constant *C2 = getOperand(1);
2446     Constant *C3 = getOperand(1);
2447     if (C1 == From) C1 = To;
2448     if (C2 == From) C2 = To;
2449     if (C3 == From) C3 = To;
2450     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2451   } else if (getOpcode() == Instruction::ShuffleVector) {
2452     Constant *C1 = getOperand(0);
2453     Constant *C2 = getOperand(1);
2454     Constant *C3 = getOperand(2);
2455     if (C1 == From) C1 = To;
2456     if (C2 == From) C2 = To;
2457     if (C3 == From) C3 = To;
2458     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2459   } else if (isCompare()) {
2460     Constant *C1 = getOperand(0);
2461     Constant *C2 = getOperand(1);
2462     if (C1 == From) C1 = To;
2463     if (C2 == From) C2 = To;
2464     if (getOpcode() == Instruction::ICmp)
2465       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2466     else {
2467       assert(getOpcode() == Instruction::FCmp);
2468       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2469     }
2470   } else if (getNumOperands() == 2) {
2471     Constant *C1 = getOperand(0);
2472     Constant *C2 = getOperand(1);
2473     if (C1 == From) C1 = To;
2474     if (C2 == From) C2 = To;
2475     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2476   } else {
2477     llvm_unreachable("Unknown ConstantExpr type!");
2478     return;
2479   }
2480   
2481   assert(Replacement != this && "I didn't contain From!");
2482   
2483   // Everyone using this now uses the replacement.
2484   uncheckedReplaceAllUsesWith(Replacement);
2485   
2486   // Delete the old constant!
2487   destroyConstant();
2488 }
2489
2490 void MDNode::replaceElement(Value *From, Value *To) {
2491   SmallVector<Value*, 4> Values;
2492   Values.reserve(getNumElements());  // Build replacement array...
2493   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2494     Value *Val = getElement(i);
2495     if (Val == From) Val = To;
2496     Values.push_back(Val);
2497   }
2498
2499   MDNode *Replacement =
2500     getType()->getContext().getMDNode(&Values[0], Values.size());
2501   assert(Replacement != this && "I didn't contain From!");
2502
2503   uncheckedReplaceAllUsesWith(Replacement);
2504
2505   destroyConstant();
2506 }