39c96c714db754588475dde227058be743acbcb3
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 #include <cstdarg>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 //                              Constant Class
41 //===----------------------------------------------------------------------===//
42
43 void Constant::anchor() { }
44
45 bool Constant::isNegativeZeroValue() const {
46   // Floating point values have an explicit -0.0 value.
47   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48     return CFP->isZero() && CFP->isNegative();
49   
50   // Otherwise, just use +0.0.
51   return isNullValue();
52 }
53
54 bool Constant::isNullValue() const {
55   // 0 is null.
56   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
57     return CI->isZero();
58   
59   // +0.0 is null.
60   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
61     return CFP->isZero() && !CFP->isNegative();
62
63   // constant zero is zero for aggregates and cpnull is null for pointers.
64   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65 }
66
67 bool Constant::isAllOnesValue() const {
68   // Check for -1 integers
69   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
70     return CI->isMinusOne();
71
72   // Check for FP which are bitcasted from -1 integers
73   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
75
76   // Check for constant vectors which are splats of -1 values.
77   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
78     if (Constant *Splat = CV->getSplatValue())
79       return Splat->isAllOnesValue();
80
81   // Check for constant vectors which are splats of -1 values.
82   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
83     if (Constant *Splat = CV->getSplatValue())
84       return Splat->isAllOnesValue();
85
86   return false;
87 }
88
89 // Constructor to create a '0' constant of arbitrary type...
90 Constant *Constant::getNullValue(Type *Ty) {
91   switch (Ty->getTypeID()) {
92   case Type::IntegerTyID:
93     return ConstantInt::get(Ty, 0);
94   case Type::HalfTyID:
95     return ConstantFP::get(Ty->getContext(),
96                            APFloat::getZero(APFloat::IEEEhalf));
97   case Type::FloatTyID:
98     return ConstantFP::get(Ty->getContext(),
99                            APFloat::getZero(APFloat::IEEEsingle));
100   case Type::DoubleTyID:
101     return ConstantFP::get(Ty->getContext(),
102                            APFloat::getZero(APFloat::IEEEdouble));
103   case Type::X86_FP80TyID:
104     return ConstantFP::get(Ty->getContext(),
105                            APFloat::getZero(APFloat::x87DoubleExtended));
106   case Type::FP128TyID:
107     return ConstantFP::get(Ty->getContext(),
108                            APFloat::getZero(APFloat::IEEEquad));
109   case Type::PPC_FP128TyID:
110     return ConstantFP::get(Ty->getContext(),
111                            APFloat(APInt::getNullValue(128)));
112   case Type::PointerTyID:
113     return ConstantPointerNull::get(cast<PointerType>(Ty));
114   case Type::StructTyID:
115   case Type::ArrayTyID:
116   case Type::VectorTyID:
117     return ConstantAggregateZero::get(Ty);
118   default:
119     // Function, Label, or Opaque type?
120     assert(0 && "Cannot create a null constant of that type!");
121     return 0;
122   }
123 }
124
125 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
126   Type *ScalarTy = Ty->getScalarType();
127
128   // Create the base integer constant.
129   Constant *C = ConstantInt::get(Ty->getContext(), V);
130
131   // Convert an integer to a pointer, if necessary.
132   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
133     C = ConstantExpr::getIntToPtr(C, PTy);
134
135   // Broadcast a scalar to a vector, if necessary.
136   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
137     C = ConstantVector::getSplat(VTy->getNumElements(), C);
138
139   return C;
140 }
141
142 Constant *Constant::getAllOnesValue(Type *Ty) {
143   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
144     return ConstantInt::get(Ty->getContext(),
145                             APInt::getAllOnesValue(ITy->getBitWidth()));
146
147   if (Ty->isFloatingPointTy()) {
148     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
149                                           !Ty->isPPC_FP128Ty());
150     return ConstantFP::get(Ty->getContext(), FL);
151   }
152
153   VectorType *VTy = cast<VectorType>(Ty);
154   return ConstantVector::getSplat(VTy->getNumElements(),
155                                   getAllOnesValue(VTy->getElementType()));
156 }
157
158 /// getAggregateElement - For aggregates (struct/array/vector) return the
159 /// constant that corresponds to the specified element if possible, or null if
160 /// not.  This can return null if the element index is a ConstantExpr, or if
161 /// 'this' is a constant expr.
162 Constant *Constant::getAggregateElement(unsigned Elt) const {
163   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
164     return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
165   
166   if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
167     return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
168   
169   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
170     return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
171   
172   if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
173     return CAZ->getElementValue(Elt);
174   
175   if (const UndefValue *UV = dyn_cast<UndefValue>(this))
176     return UV->getElementValue(Elt);
177   
178   if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
179     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
180   return 0;
181 }
182
183 Constant *Constant::getAggregateElement(Constant *Elt) const {
184   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
185   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
186     return getAggregateElement(CI->getZExtValue());
187   return 0;
188 }
189
190
191 void Constant::destroyConstantImpl() {
192   // When a Constant is destroyed, there may be lingering
193   // references to the constant by other constants in the constant pool.  These
194   // constants are implicitly dependent on the module that is being deleted,
195   // but they don't know that.  Because we only find out when the CPV is
196   // deleted, we must now notify all of our users (that should only be
197   // Constants) that they are, in fact, invalid now and should be deleted.
198   //
199   while (!use_empty()) {
200     Value *V = use_back();
201 #ifndef NDEBUG      // Only in -g mode...
202     if (!isa<Constant>(V)) {
203       dbgs() << "While deleting: " << *this
204              << "\n\nUse still stuck around after Def is destroyed: "
205              << *V << "\n\n";
206     }
207 #endif
208     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
209     cast<Constant>(V)->destroyConstant();
210
211     // The constant should remove itself from our use list...
212     assert((use_empty() || use_back() != V) && "Constant not removed!");
213   }
214
215   // Value has no outstanding references it is safe to delete it now...
216   delete this;
217 }
218
219 /// canTrap - Return true if evaluation of this constant could trap.  This is
220 /// true for things like constant expressions that could divide by zero.
221 bool Constant::canTrap() const {
222   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
223   // The only thing that could possibly trap are constant exprs.
224   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
225   if (!CE) return false;
226   
227   // ConstantExpr traps if any operands can trap. 
228   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
229     if (CE->getOperand(i)->canTrap()) 
230       return true;
231
232   // Otherwise, only specific operations can trap.
233   switch (CE->getOpcode()) {
234   default:
235     return false;
236   case Instruction::UDiv:
237   case Instruction::SDiv:
238   case Instruction::FDiv:
239   case Instruction::URem:
240   case Instruction::SRem:
241   case Instruction::FRem:
242     // Div and rem can trap if the RHS is not known to be non-zero.
243     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
244       return true;
245     return false;
246   }
247 }
248
249 /// isConstantUsed - Return true if the constant has users other than constant
250 /// exprs and other dangling things.
251 bool Constant::isConstantUsed() const {
252   for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
253     const Constant *UC = dyn_cast<Constant>(*UI);
254     if (UC == 0 || isa<GlobalValue>(UC))
255       return true;
256     
257     if (UC->isConstantUsed())
258       return true;
259   }
260   return false;
261 }
262
263
264
265 /// getRelocationInfo - This method classifies the entry according to
266 /// whether or not it may generate a relocation entry.  This must be
267 /// conservative, so if it might codegen to a relocatable entry, it should say
268 /// so.  The return values are:
269 /// 
270 ///  NoRelocation: This constant pool entry is guaranteed to never have a
271 ///     relocation applied to it (because it holds a simple constant like
272 ///     '4').
273 ///  LocalRelocation: This entry has relocations, but the entries are
274 ///     guaranteed to be resolvable by the static linker, so the dynamic
275 ///     linker will never see them.
276 ///  GlobalRelocations: This entry may have arbitrary relocations.
277 ///
278 /// FIXME: This really should not be in VMCore.
279 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
280   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
281     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
282       return LocalRelocation;  // Local to this file/library.
283     return GlobalRelocations;    // Global reference.
284   }
285   
286   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
287     return BA->getFunction()->getRelocationInfo();
288   
289   // While raw uses of blockaddress need to be relocated, differences between
290   // two of them don't when they are for labels in the same function.  This is a
291   // common idiom when creating a table for the indirect goto extension, so we
292   // handle it efficiently here.
293   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
294     if (CE->getOpcode() == Instruction::Sub) {
295       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
296       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
297       if (LHS && RHS &&
298           LHS->getOpcode() == Instruction::PtrToInt &&
299           RHS->getOpcode() == Instruction::PtrToInt &&
300           isa<BlockAddress>(LHS->getOperand(0)) &&
301           isa<BlockAddress>(RHS->getOperand(0)) &&
302           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
303             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
304         return NoRelocation;
305     }
306   
307   PossibleRelocationsTy Result = NoRelocation;
308   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309     Result = std::max(Result,
310                       cast<Constant>(getOperand(i))->getRelocationInfo());
311   
312   return Result;
313 }
314
315 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
316 /// it.  This involves recursively eliminating any dead users of the
317 /// constantexpr.
318 static bool removeDeadUsersOfConstant(const Constant *C) {
319   if (isa<GlobalValue>(C)) return false; // Cannot remove this
320   
321   while (!C->use_empty()) {
322     const Constant *User = dyn_cast<Constant>(C->use_back());
323     if (!User) return false; // Non-constant usage;
324     if (!removeDeadUsersOfConstant(User))
325       return false; // Constant wasn't dead
326   }
327   
328   const_cast<Constant*>(C)->destroyConstant();
329   return true;
330 }
331
332
333 /// removeDeadConstantUsers - If there are any dead constant users dangling
334 /// off of this constant, remove them.  This method is useful for clients
335 /// that want to check to see if a global is unused, but don't want to deal
336 /// with potentially dead constants hanging off of the globals.
337 void Constant::removeDeadConstantUsers() const {
338   Value::const_use_iterator I = use_begin(), E = use_end();
339   Value::const_use_iterator LastNonDeadUser = E;
340   while (I != E) {
341     const Constant *User = dyn_cast<Constant>(*I);
342     if (User == 0) {
343       LastNonDeadUser = I;
344       ++I;
345       continue;
346     }
347     
348     if (!removeDeadUsersOfConstant(User)) {
349       // If the constant wasn't dead, remember that this was the last live use
350       // and move on to the next constant.
351       LastNonDeadUser = I;
352       ++I;
353       continue;
354     }
355     
356     // If the constant was dead, then the iterator is invalidated.
357     if (LastNonDeadUser == E) {
358       I = use_begin();
359       if (I == E) break;
360     } else {
361       I = LastNonDeadUser;
362       ++I;
363     }
364   }
365 }
366
367
368
369 //===----------------------------------------------------------------------===//
370 //                                ConstantInt
371 //===----------------------------------------------------------------------===//
372
373 void ConstantInt::anchor() { }
374
375 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
376   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
377   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
378 }
379
380 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
381   LLVMContextImpl *pImpl = Context.pImpl;
382   if (!pImpl->TheTrueVal)
383     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
384   return pImpl->TheTrueVal;
385 }
386
387 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
388   LLVMContextImpl *pImpl = Context.pImpl;
389   if (!pImpl->TheFalseVal)
390     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
391   return pImpl->TheFalseVal;
392 }
393
394 Constant *ConstantInt::getTrue(Type *Ty) {
395   VectorType *VTy = dyn_cast<VectorType>(Ty);
396   if (!VTy) {
397     assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
398     return ConstantInt::getTrue(Ty->getContext());
399   }
400   assert(VTy->getElementType()->isIntegerTy(1) &&
401          "True must be vector of i1 or i1.");
402   return ConstantVector::getSplat(VTy->getNumElements(),
403                                   ConstantInt::getTrue(Ty->getContext()));
404 }
405
406 Constant *ConstantInt::getFalse(Type *Ty) {
407   VectorType *VTy = dyn_cast<VectorType>(Ty);
408   if (!VTy) {
409     assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
410     return ConstantInt::getFalse(Ty->getContext());
411   }
412   assert(VTy->getElementType()->isIntegerTy(1) &&
413          "False must be vector of i1 or i1.");
414   return ConstantVector::getSplat(VTy->getNumElements(),
415                                   ConstantInt::getFalse(Ty->getContext()));
416 }
417
418
419 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
420 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
421 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
422 // compare APInt's of different widths, which would violate an APInt class
423 // invariant which generates an assertion.
424 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
425   // Get the corresponding integer type for the bit width of the value.
426   IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
427   // get an existing value or the insertion position
428   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
429   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
430   if (!Slot) Slot = new ConstantInt(ITy, V);
431   return Slot;
432 }
433
434 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
435   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
436
437   // For vectors, broadcast the value.
438   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
439     return ConstantVector::getSplat(VTy->getNumElements(), C);
440
441   return C;
442 }
443
444 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, 
445                               bool isSigned) {
446   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
447 }
448
449 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
450   return get(Ty, V, true);
451 }
452
453 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
454   return get(Ty, V, true);
455 }
456
457 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
458   ConstantInt *C = get(Ty->getContext(), V);
459   assert(C->getType() == Ty->getScalarType() &&
460          "ConstantInt type doesn't match the type implied by its value!");
461
462   // For vectors, broadcast the value.
463   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
464     return ConstantVector::getSplat(VTy->getNumElements(), C);
465
466   return C;
467 }
468
469 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
470                               uint8_t radix) {
471   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
472 }
473
474 //===----------------------------------------------------------------------===//
475 //                                ConstantFP
476 //===----------------------------------------------------------------------===//
477
478 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
479   if (Ty->isHalfTy())
480     return &APFloat::IEEEhalf;
481   if (Ty->isFloatTy())
482     return &APFloat::IEEEsingle;
483   if (Ty->isDoubleTy())
484     return &APFloat::IEEEdouble;
485   if (Ty->isX86_FP80Ty())
486     return &APFloat::x87DoubleExtended;
487   else if (Ty->isFP128Ty())
488     return &APFloat::IEEEquad;
489   
490   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
491   return &APFloat::PPCDoubleDouble;
492 }
493
494 void ConstantFP::anchor() { }
495
496 /// get() - This returns a constant fp for the specified value in the
497 /// specified type.  This should only be used for simple constant values like
498 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
499 Constant *ConstantFP::get(Type *Ty, double V) {
500   LLVMContext &Context = Ty->getContext();
501   
502   APFloat FV(V);
503   bool ignored;
504   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
505              APFloat::rmNearestTiesToEven, &ignored);
506   Constant *C = get(Context, FV);
507
508   // For vectors, broadcast the value.
509   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
510     return ConstantVector::getSplat(VTy->getNumElements(), C);
511
512   return C;
513 }
514
515
516 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
517   LLVMContext &Context = Ty->getContext();
518
519   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
520   Constant *C = get(Context, FV);
521
522   // For vectors, broadcast the value.
523   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
524     return ConstantVector::getSplat(VTy->getNumElements(), C);
525
526   return C; 
527 }
528
529
530 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
531   LLVMContext &Context = Ty->getContext();
532   APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
533   apf.changeSign();
534   return get(Context, apf);
535 }
536
537
538 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
539   Type *ScalarTy = Ty->getScalarType();
540   if (ScalarTy->isFloatingPointTy()) {
541     Constant *C = getNegativeZero(ScalarTy);
542     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
543       return ConstantVector::getSplat(VTy->getNumElements(), C);
544     return C;
545   }
546
547   return Constant::getNullValue(Ty);
548 }
549
550
551 // ConstantFP accessors.
552 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
553   DenseMapAPFloatKeyInfo::KeyTy Key(V);
554   
555   LLVMContextImpl* pImpl = Context.pImpl;
556   
557   ConstantFP *&Slot = pImpl->FPConstants[Key];
558     
559   if (!Slot) {
560     Type *Ty;
561     if (&V.getSemantics() == &APFloat::IEEEhalf)
562       Ty = Type::getHalfTy(Context);
563     else if (&V.getSemantics() == &APFloat::IEEEsingle)
564       Ty = Type::getFloatTy(Context);
565     else if (&V.getSemantics() == &APFloat::IEEEdouble)
566       Ty = Type::getDoubleTy(Context);
567     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
568       Ty = Type::getX86_FP80Ty(Context);
569     else if (&V.getSemantics() == &APFloat::IEEEquad)
570       Ty = Type::getFP128Ty(Context);
571     else {
572       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
573              "Unknown FP format");
574       Ty = Type::getPPC_FP128Ty(Context);
575     }
576     Slot = new ConstantFP(Ty, V);
577   }
578   
579   return Slot;
580 }
581
582 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
583   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
584   return ConstantFP::get(Ty->getContext(),
585                          APFloat::getInf(Semantics, Negative));
586 }
587
588 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
589   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
590   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
591          "FP type Mismatch");
592 }
593
594 bool ConstantFP::isExactlyValue(const APFloat &V) const {
595   return Val.bitwiseIsEqual(V);
596 }
597
598 //===----------------------------------------------------------------------===//
599 //                   ConstantAggregateZero Implementation
600 //===----------------------------------------------------------------------===//
601
602 /// getSequentialElement - If this CAZ has array or vector type, return a zero
603 /// with the right element type.
604 Constant *ConstantAggregateZero::getSequentialElement() const {
605   return Constant::getNullValue(getType()->getSequentialElementType());
606 }
607
608 /// getStructElement - If this CAZ has struct type, return a zero with the
609 /// right element type for the specified element.
610 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
611   return Constant::getNullValue(getType()->getStructElementType(Elt));
612 }
613
614 /// getElementValue - Return a zero of the right value for the specified GEP
615 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
616 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
617   if (isa<SequentialType>(getType()))
618     return getSequentialElement();
619   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
620 }
621
622 /// getElementValue - Return a zero of the right value for the specified GEP
623 /// index.
624 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
625   if (isa<SequentialType>(getType()))
626     return getSequentialElement();
627   return getStructElement(Idx);
628 }
629
630
631 //===----------------------------------------------------------------------===//
632 //                         UndefValue Implementation
633 //===----------------------------------------------------------------------===//
634
635 /// getSequentialElement - If this undef has array or vector type, return an
636 /// undef with the right element type.
637 UndefValue *UndefValue::getSequentialElement() const {
638   return UndefValue::get(getType()->getSequentialElementType());
639 }
640
641 /// getStructElement - If this undef has struct type, return a zero with the
642 /// right element type for the specified element.
643 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
644   return UndefValue::get(getType()->getStructElementType(Elt));
645 }
646
647 /// getElementValue - Return an undef of the right value for the specified GEP
648 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
649 UndefValue *UndefValue::getElementValue(Constant *C) const {
650   if (isa<SequentialType>(getType()))
651     return getSequentialElement();
652   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
653 }
654
655 /// getElementValue - Return an undef of the right value for the specified GEP
656 /// index.
657 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
658   if (isa<SequentialType>(getType()))
659     return getSequentialElement();
660   return getStructElement(Idx);
661 }
662
663
664
665 //===----------------------------------------------------------------------===//
666 //                            ConstantXXX Classes
667 //===----------------------------------------------------------------------===//
668
669 template <typename ItTy, typename EltTy>
670 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
671   for (; Start != End; ++Start)
672     if (*Start != Elt)
673       return false;
674   return true;
675 }
676
677 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
678   : Constant(T, ConstantArrayVal,
679              OperandTraits<ConstantArray>::op_end(this) - V.size(),
680              V.size()) {
681   assert(V.size() == T->getNumElements() &&
682          "Invalid initializer vector for constant array");
683   for (unsigned i = 0, e = V.size(); i != e; ++i)
684     assert(V[i]->getType() == T->getElementType() &&
685            "Initializer for array element doesn't match array element type!");
686   std::copy(V.begin(), V.end(), op_begin());
687 }
688
689 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
690   // Empty arrays are canonicalized to ConstantAggregateZero.
691   if (V.empty())
692     return ConstantAggregateZero::get(Ty);
693
694   for (unsigned i = 0, e = V.size(); i != e; ++i) {
695     assert(V[i]->getType() == Ty->getElementType() &&
696            "Wrong type in array element initializer");
697   }
698   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
699   
700   // If this is an all-zero array, return a ConstantAggregateZero object.  If
701   // all undef, return an UndefValue, if "all simple", then return a
702   // ConstantDataArray.
703   Constant *C = V[0];
704   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
705     return UndefValue::get(Ty);
706
707   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
708     return ConstantAggregateZero::get(Ty);
709
710   // Check to see if all of the elements are ConstantFP or ConstantInt and if
711   // the element type is compatible with ConstantDataVector.  If so, use it.
712   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
713     // We speculatively build the elements here even if it turns out that there
714     // is a constantexpr or something else weird in the array, since it is so
715     // uncommon for that to happen.
716     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
717       if (CI->getType()->isIntegerTy(8)) {
718         SmallVector<uint8_t, 16> Elts;
719         for (unsigned i = 0, e = V.size(); i != e; ++i)
720           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
721             Elts.push_back(CI->getZExtValue());
722           else
723             break;
724         if (Elts.size() == V.size())
725           return ConstantDataArray::get(C->getContext(), Elts);
726       } else if (CI->getType()->isIntegerTy(16)) {
727         SmallVector<uint16_t, 16> Elts;
728         for (unsigned i = 0, e = V.size(); i != e; ++i)
729           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
730             Elts.push_back(CI->getZExtValue());
731           else
732             break;
733         if (Elts.size() == V.size())
734           return ConstantDataArray::get(C->getContext(), Elts);
735       } else if (CI->getType()->isIntegerTy(32)) {
736         SmallVector<uint32_t, 16> Elts;
737         for (unsigned i = 0, e = V.size(); i != e; ++i)
738           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
739             Elts.push_back(CI->getZExtValue());
740           else
741             break;
742         if (Elts.size() == V.size())
743           return ConstantDataArray::get(C->getContext(), Elts);
744       } else if (CI->getType()->isIntegerTy(64)) {
745         SmallVector<uint64_t, 16> Elts;
746         for (unsigned i = 0, e = V.size(); i != e; ++i)
747           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
748             Elts.push_back(CI->getZExtValue());
749           else
750             break;
751         if (Elts.size() == V.size())
752           return ConstantDataArray::get(C->getContext(), Elts);
753       }
754     }
755     
756     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
757       if (CFP->getType()->isFloatTy()) {
758         SmallVector<float, 16> Elts;
759         for (unsigned i = 0, e = V.size(); i != e; ++i)
760           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
761             Elts.push_back(CFP->getValueAPF().convertToFloat());
762           else
763             break;
764         if (Elts.size() == V.size())
765           return ConstantDataArray::get(C->getContext(), Elts);
766       } else if (CFP->getType()->isDoubleTy()) {
767         SmallVector<double, 16> Elts;
768         for (unsigned i = 0, e = V.size(); i != e; ++i)
769           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
770             Elts.push_back(CFP->getValueAPF().convertToDouble());
771           else
772             break;
773         if (Elts.size() == V.size())
774           return ConstantDataArray::get(C->getContext(), Elts);
775       }
776     }
777   }
778
779   // Otherwise, we really do want to create a ConstantArray.
780   return pImpl->ArrayConstants.getOrCreate(Ty, V);
781 }
782
783 // FIXME: Remove this method.
784 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
785                              bool AddNull) {
786   return ConstantDataArray::getString(Context, Str, AddNull);
787 }
788
789 /// getTypeForElements - Return an anonymous struct type to use for a constant
790 /// with the specified set of elements.  The list must not be empty.
791 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
792                                                ArrayRef<Constant*> V,
793                                                bool Packed) {
794   SmallVector<Type*, 16> EltTypes;
795   for (unsigned i = 0, e = V.size(); i != e; ++i)
796     EltTypes.push_back(V[i]->getType());
797   
798   return StructType::get(Context, EltTypes, Packed);
799 }
800
801
802 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
803                                                bool Packed) {
804   assert(!V.empty() &&
805          "ConstantStruct::getTypeForElements cannot be called on empty list");
806   return getTypeForElements(V[0]->getContext(), V, Packed);
807 }
808
809
810 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
811   : Constant(T, ConstantStructVal,
812              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
813              V.size()) {
814   assert(V.size() == T->getNumElements() &&
815          "Invalid initializer vector for constant structure");
816   for (unsigned i = 0, e = V.size(); i != e; ++i)
817     assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
818            "Initializer for struct element doesn't match struct element type!");
819   std::copy(V.begin(), V.end(), op_begin());
820 }
821
822 // ConstantStruct accessors.
823 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
824   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
825          "Incorrect # elements specified to ConstantStruct::get");
826
827   // Create a ConstantAggregateZero value if all elements are zeros.
828   bool isZero = true;
829   bool isUndef = false;
830   
831   if (!V.empty()) {
832     isUndef = isa<UndefValue>(V[0]);
833     isZero = V[0]->isNullValue();
834     if (isUndef || isZero) {
835       for (unsigned i = 0, e = V.size(); i != e; ++i) {
836         if (!V[i]->isNullValue())
837           isZero = false;
838         if (!isa<UndefValue>(V[i]))
839           isUndef = false;
840       }
841     }
842   }  
843   if (isZero)
844     return ConstantAggregateZero::get(ST);
845   if (isUndef)
846     return UndefValue::get(ST);
847     
848   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
849 }
850
851 Constant *ConstantStruct::get(StructType *T, ...) {
852   va_list ap;
853   SmallVector<Constant*, 8> Values;
854   va_start(ap, T);
855   while (Constant *Val = va_arg(ap, llvm::Constant*))
856     Values.push_back(Val);
857   va_end(ap);
858   return get(T, Values);
859 }
860
861 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
862   : Constant(T, ConstantVectorVal,
863              OperandTraits<ConstantVector>::op_end(this) - V.size(),
864              V.size()) {
865   for (size_t i = 0, e = V.size(); i != e; i++)
866     assert(V[i]->getType() == T->getElementType() &&
867            "Initializer for vector element doesn't match vector element type!");
868   std::copy(V.begin(), V.end(), op_begin());
869 }
870
871 // ConstantVector accessors.
872 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
873   assert(!V.empty() && "Vectors can't be empty");
874   VectorType *T = VectorType::get(V.front()->getType(), V.size());
875   LLVMContextImpl *pImpl = T->getContext().pImpl;
876
877   // If this is an all-undef or all-zero vector, return a
878   // ConstantAggregateZero or UndefValue.
879   Constant *C = V[0];
880   bool isZero = C->isNullValue();
881   bool isUndef = isa<UndefValue>(C);
882
883   if (isZero || isUndef) {
884     for (unsigned i = 1, e = V.size(); i != e; ++i)
885       if (V[i] != C) {
886         isZero = isUndef = false;
887         break;
888       }
889   }
890   
891   if (isZero)
892     return ConstantAggregateZero::get(T);
893   if (isUndef)
894     return UndefValue::get(T);
895    
896   // Check to see if all of the elements are ConstantFP or ConstantInt and if
897   // the element type is compatible with ConstantDataVector.  If so, use it.
898   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
899     // We speculatively build the elements here even if it turns out that there
900     // is a constantexpr or something else weird in the array, since it is so
901     // uncommon for that to happen.
902     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
903       if (CI->getType()->isIntegerTy(8)) {
904         SmallVector<uint8_t, 16> Elts;
905         for (unsigned i = 0, e = V.size(); i != e; ++i)
906           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
907             Elts.push_back(CI->getZExtValue());
908           else
909             break;
910         if (Elts.size() == V.size())
911           return ConstantDataVector::get(C->getContext(), Elts);
912       } else if (CI->getType()->isIntegerTy(16)) {
913         SmallVector<uint16_t, 16> Elts;
914         for (unsigned i = 0, e = V.size(); i != e; ++i)
915           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
916             Elts.push_back(CI->getZExtValue());
917           else
918             break;
919         if (Elts.size() == V.size())
920           return ConstantDataVector::get(C->getContext(), Elts);
921       } else if (CI->getType()->isIntegerTy(32)) {
922         SmallVector<uint32_t, 16> Elts;
923         for (unsigned i = 0, e = V.size(); i != e; ++i)
924           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
925             Elts.push_back(CI->getZExtValue());
926           else
927             break;
928         if (Elts.size() == V.size())
929           return ConstantDataVector::get(C->getContext(), Elts);
930       } else if (CI->getType()->isIntegerTy(64)) {
931         SmallVector<uint64_t, 16> Elts;
932         for (unsigned i = 0, e = V.size(); i != e; ++i)
933           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
934             Elts.push_back(CI->getZExtValue());
935           else
936             break;
937         if (Elts.size() == V.size())
938           return ConstantDataVector::get(C->getContext(), Elts);
939       }
940     }
941     
942     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
943       if (CFP->getType()->isFloatTy()) {
944         SmallVector<float, 16> Elts;
945         for (unsigned i = 0, e = V.size(); i != e; ++i)
946           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
947             Elts.push_back(CFP->getValueAPF().convertToFloat());
948           else
949             break;
950         if (Elts.size() == V.size())
951           return ConstantDataVector::get(C->getContext(), Elts);
952       } else if (CFP->getType()->isDoubleTy()) {
953         SmallVector<double, 16> Elts;
954         for (unsigned i = 0, e = V.size(); i != e; ++i)
955           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
956             Elts.push_back(CFP->getValueAPF().convertToDouble());
957           else
958             break;
959         if (Elts.size() == V.size())
960           return ConstantDataVector::get(C->getContext(), Elts);
961       }
962     }
963   }
964   
965   // Otherwise, the element type isn't compatible with ConstantDataVector, or
966   // the operand list constants a ConstantExpr or something else strange.
967   return pImpl->VectorConstants.getOrCreate(T, V);
968 }
969
970 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
971   // If this splat is compatible with ConstantDataVector, use it instead of
972   // ConstantVector.
973   if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
974       ConstantDataSequential::isElementTypeCompatible(V->getType()))
975     return ConstantDataVector::getSplat(NumElts, V);
976   
977   SmallVector<Constant*, 32> Elts(NumElts, V);
978   return get(Elts);
979 }
980
981
982 // Utility function for determining if a ConstantExpr is a CastOp or not. This
983 // can't be inline because we don't want to #include Instruction.h into
984 // Constant.h
985 bool ConstantExpr::isCast() const {
986   return Instruction::isCast(getOpcode());
987 }
988
989 bool ConstantExpr::isCompare() const {
990   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
991 }
992
993 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
994   if (getOpcode() != Instruction::GetElementPtr) return false;
995
996   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
997   User::const_op_iterator OI = llvm::next(this->op_begin());
998
999   // Skip the first index, as it has no static limit.
1000   ++GEPI;
1001   ++OI;
1002
1003   // The remaining indices must be compile-time known integers within the
1004   // bounds of the corresponding notional static array types.
1005   for (; GEPI != E; ++GEPI, ++OI) {
1006     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1007     if (!CI) return false;
1008     if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1009       if (CI->getValue().getActiveBits() > 64 ||
1010           CI->getZExtValue() >= ATy->getNumElements())
1011         return false;
1012   }
1013
1014   // All the indices checked out.
1015   return true;
1016 }
1017
1018 bool ConstantExpr::hasIndices() const {
1019   return getOpcode() == Instruction::ExtractValue ||
1020          getOpcode() == Instruction::InsertValue;
1021 }
1022
1023 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1024   if (const ExtractValueConstantExpr *EVCE =
1025         dyn_cast<ExtractValueConstantExpr>(this))
1026     return EVCE->Indices;
1027
1028   return cast<InsertValueConstantExpr>(this)->Indices;
1029 }
1030
1031 unsigned ConstantExpr::getPredicate() const {
1032   assert(isCompare());
1033   return ((const CompareConstantExpr*)this)->predicate;
1034 }
1035
1036 /// getWithOperandReplaced - Return a constant expression identical to this
1037 /// one, but with the specified operand set to the specified value.
1038 Constant *
1039 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1040   assert(Op->getType() == getOperand(OpNo)->getType() &&
1041          "Replacing operand with value of different type!");
1042   if (getOperand(OpNo) == Op)
1043     return const_cast<ConstantExpr*>(this);
1044
1045   SmallVector<Constant*, 8> NewOps;
1046   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1047     NewOps.push_back(i == OpNo ? Op : getOperand(i));
1048   
1049   return getWithOperands(NewOps);
1050 }
1051
1052 /// getWithOperands - This returns the current constant expression with the
1053 /// operands replaced with the specified values.  The specified array must
1054 /// have the same number of operands as our current one.
1055 Constant *ConstantExpr::
1056 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1057   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1058   bool AnyChange = Ty != getType();
1059   for (unsigned i = 0; i != Ops.size(); ++i)
1060     AnyChange |= Ops[i] != getOperand(i);
1061   
1062   if (!AnyChange)  // No operands changed, return self.
1063     return const_cast<ConstantExpr*>(this);
1064
1065   switch (getOpcode()) {
1066   case Instruction::Trunc:
1067   case Instruction::ZExt:
1068   case Instruction::SExt:
1069   case Instruction::FPTrunc:
1070   case Instruction::FPExt:
1071   case Instruction::UIToFP:
1072   case Instruction::SIToFP:
1073   case Instruction::FPToUI:
1074   case Instruction::FPToSI:
1075   case Instruction::PtrToInt:
1076   case Instruction::IntToPtr:
1077   case Instruction::BitCast:
1078     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1079   case Instruction::Select:
1080     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1081   case Instruction::InsertElement:
1082     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1083   case Instruction::ExtractElement:
1084     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1085   case Instruction::InsertValue:
1086     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1087   case Instruction::ExtractValue:
1088     return ConstantExpr::getExtractValue(Ops[0], getIndices());
1089   case Instruction::ShuffleVector:
1090     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1091   case Instruction::GetElementPtr:
1092     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1093                                       cast<GEPOperator>(this)->isInBounds());
1094   case Instruction::ICmp:
1095   case Instruction::FCmp:
1096     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1097   default:
1098     assert(getNumOperands() == 2 && "Must be binary operator?");
1099     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1100   }
1101 }
1102
1103
1104 //===----------------------------------------------------------------------===//
1105 //                      isValueValidForType implementations
1106
1107 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1108   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1109   if (Ty->isIntegerTy(1))
1110     return Val == 0 || Val == 1;
1111   if (NumBits >= 64)
1112     return true; // always true, has to fit in largest type
1113   uint64_t Max = (1ll << NumBits) - 1;
1114   return Val <= Max;
1115 }
1116
1117 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1118   unsigned NumBits = Ty->getIntegerBitWidth();
1119   if (Ty->isIntegerTy(1))
1120     return Val == 0 || Val == 1 || Val == -1;
1121   if (NumBits >= 64)
1122     return true; // always true, has to fit in largest type
1123   int64_t Min = -(1ll << (NumBits-1));
1124   int64_t Max = (1ll << (NumBits-1)) - 1;
1125   return (Val >= Min && Val <= Max);
1126 }
1127
1128 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1129   // convert modifies in place, so make a copy.
1130   APFloat Val2 = APFloat(Val);
1131   bool losesInfo;
1132   switch (Ty->getTypeID()) {
1133   default:
1134     return false;         // These can't be represented as floating point!
1135
1136   // FIXME rounding mode needs to be more flexible
1137   case Type::HalfTyID: {
1138     if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1139       return true;
1140     Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1141     return !losesInfo;
1142   }
1143   case Type::FloatTyID: {
1144     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1145       return true;
1146     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1147     return !losesInfo;
1148   }
1149   case Type::DoubleTyID: {
1150     if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1151         &Val2.getSemantics() == &APFloat::IEEEsingle ||
1152         &Val2.getSemantics() == &APFloat::IEEEdouble)
1153       return true;
1154     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1155     return !losesInfo;
1156   }
1157   case Type::X86_FP80TyID:
1158     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1159            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1160            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1161            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1162   case Type::FP128TyID:
1163     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1164            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1165            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1166            &Val2.getSemantics() == &APFloat::IEEEquad;
1167   case Type::PPC_FP128TyID:
1168     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1169            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1170            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1171            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1172   }
1173 }
1174
1175
1176 //===----------------------------------------------------------------------===//
1177 //                      Factory Function Implementation
1178
1179 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1180   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1181          "Cannot create an aggregate zero of non-aggregate type!");
1182   
1183   ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1184   if (Entry == 0)
1185     Entry = new ConstantAggregateZero(Ty);
1186   
1187   return Entry;
1188 }
1189
1190 /// destroyConstant - Remove the constant from the constant table.
1191 ///
1192 void ConstantAggregateZero::destroyConstant() {
1193   getContext().pImpl->CAZConstants.erase(getType());
1194   destroyConstantImpl();
1195 }
1196
1197 /// destroyConstant - Remove the constant from the constant table...
1198 ///
1199 void ConstantArray::destroyConstant() {
1200   getType()->getContext().pImpl->ArrayConstants.remove(this);
1201   destroyConstantImpl();
1202 }
1203
1204 /// isString - This method returns true if the array is an array of i8, and 
1205 /// if the elements of the array are all ConstantInt's.
1206 bool ConstantArray::isString() const {
1207   // Check the element type for i8...
1208   if (!getType()->getElementType()->isIntegerTy(8))
1209     return false;
1210   // Check the elements to make sure they are all integers, not constant
1211   // expressions.
1212   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1213     if (!isa<ConstantInt>(getOperand(i)))
1214       return false;
1215   return true;
1216 }
1217
1218 /// isCString - This method returns true if the array is a string (see
1219 /// isString) and it ends in a null byte \\0 and does not contains any other
1220 /// null bytes except its terminator.
1221 bool ConstantArray::isCString() const {
1222   // Check the element type for i8...
1223   if (!getType()->getElementType()->isIntegerTy(8))
1224     return false;
1225
1226   // Last element must be a null.
1227   if (!getOperand(getNumOperands()-1)->isNullValue())
1228     return false;
1229   // Other elements must be non-null integers.
1230   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1231     if (!isa<ConstantInt>(getOperand(i)))
1232       return false;
1233     if (getOperand(i)->isNullValue())
1234       return false;
1235   }
1236   return true;
1237 }
1238
1239
1240 /// convertToString - Helper function for getAsString() and getAsCString().
1241 static std::string convertToString(const User *U, unsigned len) {
1242   std::string Result;
1243   Result.reserve(len);
1244   for (unsigned i = 0; i != len; ++i)
1245     Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1246   return Result;
1247 }
1248
1249 /// getAsString - If this array is isString(), then this method converts the
1250 /// array to an std::string and returns it.  Otherwise, it asserts out.
1251 ///
1252 std::string ConstantArray::getAsString() const {
1253   assert(isString() && "Not a string!");
1254   return convertToString(this, getNumOperands());
1255 }
1256
1257
1258 /// getAsCString - If this array is isCString(), then this method converts the
1259 /// array (without the trailing null byte) to an std::string and returns it.
1260 /// Otherwise, it asserts out.
1261 ///
1262 std::string ConstantArray::getAsCString() const {
1263   assert(isCString() && "Not a string!");
1264   return convertToString(this, getNumOperands() - 1);
1265 }
1266
1267
1268 //---- ConstantStruct::get() implementation...
1269 //
1270
1271 // destroyConstant - Remove the constant from the constant table...
1272 //
1273 void ConstantStruct::destroyConstant() {
1274   getType()->getContext().pImpl->StructConstants.remove(this);
1275   destroyConstantImpl();
1276 }
1277
1278 // destroyConstant - Remove the constant from the constant table...
1279 //
1280 void ConstantVector::destroyConstant() {
1281   getType()->getContext().pImpl->VectorConstants.remove(this);
1282   destroyConstantImpl();
1283 }
1284
1285 /// getSplatValue - If this is a splat constant, where all of the
1286 /// elements have the same value, return that value. Otherwise return null.
1287 Constant *ConstantVector::getSplatValue() const {
1288   // Check out first element.
1289   Constant *Elt = getOperand(0);
1290   // Then make sure all remaining elements point to the same value.
1291   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1292     if (getOperand(I) != Elt)
1293       return 0;
1294   return Elt;
1295 }
1296
1297 //---- ConstantPointerNull::get() implementation.
1298 //
1299
1300 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1301   ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1302   if (Entry == 0)
1303     Entry = new ConstantPointerNull(Ty);
1304   
1305   return Entry;
1306 }
1307
1308 // destroyConstant - Remove the constant from the constant table...
1309 //
1310 void ConstantPointerNull::destroyConstant() {
1311   getContext().pImpl->CPNConstants.erase(getType());
1312   // Free the constant and any dangling references to it.
1313   destroyConstantImpl();
1314 }
1315
1316
1317 //---- UndefValue::get() implementation.
1318 //
1319
1320 UndefValue *UndefValue::get(Type *Ty) {
1321   UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1322   if (Entry == 0)
1323     Entry = new UndefValue(Ty);
1324   
1325   return Entry;
1326 }
1327
1328 // destroyConstant - Remove the constant from the constant table.
1329 //
1330 void UndefValue::destroyConstant() {
1331   // Free the constant and any dangling references to it.
1332   getContext().pImpl->UVConstants.erase(getType());
1333   destroyConstantImpl();
1334 }
1335
1336 //---- BlockAddress::get() implementation.
1337 //
1338
1339 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1340   assert(BB->getParent() != 0 && "Block must have a parent");
1341   return get(BB->getParent(), BB);
1342 }
1343
1344 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1345   BlockAddress *&BA =
1346     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1347   if (BA == 0)
1348     BA = new BlockAddress(F, BB);
1349   
1350   assert(BA->getFunction() == F && "Basic block moved between functions");
1351   return BA;
1352 }
1353
1354 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1355 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1356            &Op<0>(), 2) {
1357   setOperand(0, F);
1358   setOperand(1, BB);
1359   BB->AdjustBlockAddressRefCount(1);
1360 }
1361
1362
1363 // destroyConstant - Remove the constant from the constant table.
1364 //
1365 void BlockAddress::destroyConstant() {
1366   getFunction()->getType()->getContext().pImpl
1367     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1368   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1369   destroyConstantImpl();
1370 }
1371
1372 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1373   // This could be replacing either the Basic Block or the Function.  In either
1374   // case, we have to remove the map entry.
1375   Function *NewF = getFunction();
1376   BasicBlock *NewBB = getBasicBlock();
1377   
1378   if (U == &Op<0>())
1379     NewF = cast<Function>(To);
1380   else
1381     NewBB = cast<BasicBlock>(To);
1382   
1383   // See if the 'new' entry already exists, if not, just update this in place
1384   // and return early.
1385   BlockAddress *&NewBA =
1386     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1387   if (NewBA == 0) {
1388     getBasicBlock()->AdjustBlockAddressRefCount(-1);
1389     
1390     // Remove the old entry, this can't cause the map to rehash (just a
1391     // tombstone will get added).
1392     getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1393                                                             getBasicBlock()));
1394     NewBA = this;
1395     setOperand(0, NewF);
1396     setOperand(1, NewBB);
1397     getBasicBlock()->AdjustBlockAddressRefCount(1);
1398     return;
1399   }
1400
1401   // Otherwise, I do need to replace this with an existing value.
1402   assert(NewBA != this && "I didn't contain From!");
1403   
1404   // Everyone using this now uses the replacement.
1405   replaceAllUsesWith(NewBA);
1406   
1407   destroyConstant();
1408 }
1409
1410 //---- ConstantExpr::get() implementations.
1411 //
1412
1413 /// This is a utility function to handle folding of casts and lookup of the
1414 /// cast in the ExprConstants map. It is used by the various get* methods below.
1415 static inline Constant *getFoldedCast(
1416   Instruction::CastOps opc, Constant *C, Type *Ty) {
1417   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1418   // Fold a few common cases
1419   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1420     return FC;
1421
1422   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1423
1424   // Look up the constant in the table first to ensure uniqueness
1425   std::vector<Constant*> argVec(1, C);
1426   ExprMapKeyType Key(opc, argVec);
1427   
1428   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1429 }
1430  
1431 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1432   Instruction::CastOps opc = Instruction::CastOps(oc);
1433   assert(Instruction::isCast(opc) && "opcode out of range");
1434   assert(C && Ty && "Null arguments to getCast");
1435   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1436
1437   switch (opc) {
1438   default:
1439     llvm_unreachable("Invalid cast opcode");
1440   case Instruction::Trunc:    return getTrunc(C, Ty);
1441   case Instruction::ZExt:     return getZExt(C, Ty);
1442   case Instruction::SExt:     return getSExt(C, Ty);
1443   case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1444   case Instruction::FPExt:    return getFPExtend(C, Ty);
1445   case Instruction::UIToFP:   return getUIToFP(C, Ty);
1446   case Instruction::SIToFP:   return getSIToFP(C, Ty);
1447   case Instruction::FPToUI:   return getFPToUI(C, Ty);
1448   case Instruction::FPToSI:   return getFPToSI(C, Ty);
1449   case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1450   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1451   case Instruction::BitCast:  return getBitCast(C, Ty);
1452   }
1453
1454
1455 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1456   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1457     return getBitCast(C, Ty);
1458   return getZExt(C, Ty);
1459 }
1460
1461 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1462   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1463     return getBitCast(C, Ty);
1464   return getSExt(C, Ty);
1465 }
1466
1467 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1468   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1469     return getBitCast(C, Ty);
1470   return getTrunc(C, Ty);
1471 }
1472
1473 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1474   assert(S->getType()->isPointerTy() && "Invalid cast");
1475   assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1476
1477   if (Ty->isIntegerTy())
1478     return getPtrToInt(S, Ty);
1479   return getBitCast(S, Ty);
1480 }
1481
1482 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, 
1483                                        bool isSigned) {
1484   assert(C->getType()->isIntOrIntVectorTy() &&
1485          Ty->isIntOrIntVectorTy() && "Invalid cast");
1486   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1487   unsigned DstBits = Ty->getScalarSizeInBits();
1488   Instruction::CastOps opcode =
1489     (SrcBits == DstBits ? Instruction::BitCast :
1490      (SrcBits > DstBits ? Instruction::Trunc :
1491       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1492   return getCast(opcode, C, Ty);
1493 }
1494
1495 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1496   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1497          "Invalid cast");
1498   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1499   unsigned DstBits = Ty->getScalarSizeInBits();
1500   if (SrcBits == DstBits)
1501     return C; // Avoid a useless cast
1502   Instruction::CastOps opcode =
1503     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1504   return getCast(opcode, C, Ty);
1505 }
1506
1507 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1508 #ifndef NDEBUG
1509   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1510   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1511 #endif
1512   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1513   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1514   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1515   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1516          "SrcTy must be larger than DestTy for Trunc!");
1517
1518   return getFoldedCast(Instruction::Trunc, C, Ty);
1519 }
1520
1521 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1522 #ifndef NDEBUG
1523   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1524   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1525 #endif
1526   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1527   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1528   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1529   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1530          "SrcTy must be smaller than DestTy for SExt!");
1531
1532   return getFoldedCast(Instruction::SExt, C, Ty);
1533 }
1534
1535 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1536 #ifndef NDEBUG
1537   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1538   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1539 #endif
1540   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1541   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1542   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1543   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1544          "SrcTy must be smaller than DestTy for ZExt!");
1545
1546   return getFoldedCast(Instruction::ZExt, C, Ty);
1547 }
1548
1549 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1550 #ifndef NDEBUG
1551   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1552   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1553 #endif
1554   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1555   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1556          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1557          "This is an illegal floating point truncation!");
1558   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1559 }
1560
1561 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1562 #ifndef NDEBUG
1563   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1564   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1565 #endif
1566   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1567   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1568          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1569          "This is an illegal floating point extension!");
1570   return getFoldedCast(Instruction::FPExt, C, Ty);
1571 }
1572
1573 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1574 #ifndef NDEBUG
1575   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1576   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1577 #endif
1578   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1579   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1580          "This is an illegal uint to floating point cast!");
1581   return getFoldedCast(Instruction::UIToFP, C, Ty);
1582 }
1583
1584 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1585 #ifndef NDEBUG
1586   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1587   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1588 #endif
1589   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1590   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1591          "This is an illegal sint to floating point cast!");
1592   return getFoldedCast(Instruction::SIToFP, C, Ty);
1593 }
1594
1595 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1596 #ifndef NDEBUG
1597   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1598   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1599 #endif
1600   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1601   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1602          "This is an illegal floating point to uint cast!");
1603   return getFoldedCast(Instruction::FPToUI, C, Ty);
1604 }
1605
1606 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1607 #ifndef NDEBUG
1608   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1609   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1610 #endif
1611   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1612   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1613          "This is an illegal floating point to sint cast!");
1614   return getFoldedCast(Instruction::FPToSI, C, Ty);
1615 }
1616
1617 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1618   assert(C->getType()->getScalarType()->isPointerTy() &&
1619          "PtrToInt source must be pointer or pointer vector");
1620   assert(DstTy->getScalarType()->isIntegerTy() && 
1621          "PtrToInt destination must be integer or integer vector");
1622   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1623   if (isa<VectorType>(C->getType()))
1624     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1625            "Invalid cast between a different number of vector elements");
1626   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1627 }
1628
1629 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1630   assert(C->getType()->getScalarType()->isIntegerTy() &&
1631          "IntToPtr source must be integer or integer vector");
1632   assert(DstTy->getScalarType()->isPointerTy() &&
1633          "IntToPtr destination must be a pointer or pointer vector");
1634   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1635   if (isa<VectorType>(C->getType()))
1636     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1637            "Invalid cast between a different number of vector elements");
1638   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1639 }
1640
1641 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1642   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1643          "Invalid constantexpr bitcast!");
1644   
1645   // It is common to ask for a bitcast of a value to its own type, handle this
1646   // speedily.
1647   if (C->getType() == DstTy) return C;
1648   
1649   return getFoldedCast(Instruction::BitCast, C, DstTy);
1650 }
1651
1652 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1653                             unsigned Flags) {
1654   // Check the operands for consistency first.
1655   assert(Opcode >= Instruction::BinaryOpsBegin &&
1656          Opcode <  Instruction::BinaryOpsEnd   &&
1657          "Invalid opcode in binary constant expression");
1658   assert(C1->getType() == C2->getType() &&
1659          "Operand types in binary constant expression should match");
1660   
1661 #ifndef NDEBUG
1662   switch (Opcode) {
1663   case Instruction::Add:
1664   case Instruction::Sub:
1665   case Instruction::Mul:
1666     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1667     assert(C1->getType()->isIntOrIntVectorTy() &&
1668            "Tried to create an integer operation on a non-integer type!");
1669     break;
1670   case Instruction::FAdd:
1671   case Instruction::FSub:
1672   case Instruction::FMul:
1673     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1674     assert(C1->getType()->isFPOrFPVectorTy() &&
1675            "Tried to create a floating-point operation on a "
1676            "non-floating-point type!");
1677     break;
1678   case Instruction::UDiv: 
1679   case Instruction::SDiv: 
1680     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1681     assert(C1->getType()->isIntOrIntVectorTy() &&
1682            "Tried to create an arithmetic operation on a non-arithmetic type!");
1683     break;
1684   case Instruction::FDiv:
1685     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686     assert(C1->getType()->isFPOrFPVectorTy() &&
1687            "Tried to create an arithmetic operation on a non-arithmetic type!");
1688     break;
1689   case Instruction::URem: 
1690   case Instruction::SRem: 
1691     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1692     assert(C1->getType()->isIntOrIntVectorTy() &&
1693            "Tried to create an arithmetic operation on a non-arithmetic type!");
1694     break;
1695   case Instruction::FRem:
1696     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697     assert(C1->getType()->isFPOrFPVectorTy() &&
1698            "Tried to create an arithmetic operation on a non-arithmetic type!");
1699     break;
1700   case Instruction::And:
1701   case Instruction::Or:
1702   case Instruction::Xor:
1703     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1704     assert(C1->getType()->isIntOrIntVectorTy() &&
1705            "Tried to create a logical operation on a non-integral type!");
1706     break;
1707   case Instruction::Shl:
1708   case Instruction::LShr:
1709   case Instruction::AShr:
1710     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1711     assert(C1->getType()->isIntOrIntVectorTy() &&
1712            "Tried to create a shift operation on a non-integer type!");
1713     break;
1714   default:
1715     break;
1716   }
1717 #endif
1718
1719   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1720     return FC;          // Fold a few common cases.
1721   
1722   std::vector<Constant*> argVec(1, C1);
1723   argVec.push_back(C2);
1724   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1725   
1726   LLVMContextImpl *pImpl = C1->getContext().pImpl;
1727   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1728 }
1729
1730 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1731   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1732   // Note that a non-inbounds gep is used, as null isn't within any object.
1733   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1734   Constant *GEP = getGetElementPtr(
1735                  Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1736   return getPtrToInt(GEP, 
1737                      Type::getInt64Ty(Ty->getContext()));
1738 }
1739
1740 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1741   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1742   // Note that a non-inbounds gep is used, as null isn't within any object.
1743   Type *AligningTy = 
1744     StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1745   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1746   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1747   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1748   Constant *Indices[2] = { Zero, One };
1749   Constant *GEP = getGetElementPtr(NullPtr, Indices);
1750   return getPtrToInt(GEP,
1751                      Type::getInt64Ty(Ty->getContext()));
1752 }
1753
1754 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1755   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1756                                            FieldNo));
1757 }
1758
1759 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1760   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1761   // Note that a non-inbounds gep is used, as null isn't within any object.
1762   Constant *GEPIdx[] = {
1763     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1764     FieldNo
1765   };
1766   Constant *GEP = getGetElementPtr(
1767                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1768   return getPtrToInt(GEP,
1769                      Type::getInt64Ty(Ty->getContext()));
1770 }
1771
1772 Constant *ConstantExpr::getCompare(unsigned short Predicate, 
1773                                    Constant *C1, Constant *C2) {
1774   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1775   
1776   switch (Predicate) {
1777   default: llvm_unreachable("Invalid CmpInst predicate");
1778   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1779   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1780   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1781   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1782   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1783   case CmpInst::FCMP_TRUE:
1784     return getFCmp(Predicate, C1, C2);
1785     
1786   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1787   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1788   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1789   case CmpInst::ICMP_SLE:
1790     return getICmp(Predicate, C1, C2);
1791   }
1792 }
1793
1794 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1795   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1796
1797   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1798     return SC;        // Fold common cases
1799
1800   std::vector<Constant*> argVec(3, C);
1801   argVec[1] = V1;
1802   argVec[2] = V2;
1803   ExprMapKeyType Key(Instruction::Select, argVec);
1804   
1805   LLVMContextImpl *pImpl = C->getContext().pImpl;
1806   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1807 }
1808
1809 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1810                                          bool InBounds) {
1811   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1812     return FC;          // Fold a few common cases.
1813
1814   // Get the result type of the getelementptr!
1815   Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1816   assert(Ty && "GEP indices invalid!");
1817   unsigned AS = C->getType()->getPointerAddressSpace();
1818   Type *ReqTy = Ty->getPointerTo(AS);
1819   
1820   assert(C->getType()->isPointerTy() &&
1821          "Non-pointer type for constant GetElementPtr expression");
1822   // Look up the constant in the table first to ensure uniqueness
1823   std::vector<Constant*> ArgVec;
1824   ArgVec.reserve(1 + Idxs.size());
1825   ArgVec.push_back(C);
1826   for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1827     ArgVec.push_back(cast<Constant>(Idxs[i]));
1828   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1829                            InBounds ? GEPOperator::IsInBounds : 0);
1830   
1831   LLVMContextImpl *pImpl = C->getContext().pImpl;
1832   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1833 }
1834
1835 Constant *
1836 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1837   assert(LHS->getType() == RHS->getType());
1838   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1839          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1840
1841   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1842     return FC;          // Fold a few common cases...
1843
1844   // Look up the constant in the table first to ensure uniqueness
1845   std::vector<Constant*> ArgVec;
1846   ArgVec.push_back(LHS);
1847   ArgVec.push_back(RHS);
1848   // Get the key type with both the opcode and predicate
1849   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1850
1851   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1852   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1853     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1854
1855   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1856   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1857 }
1858
1859 Constant *
1860 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1861   assert(LHS->getType() == RHS->getType());
1862   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1863
1864   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1865     return FC;          // Fold a few common cases...
1866
1867   // Look up the constant in the table first to ensure uniqueness
1868   std::vector<Constant*> ArgVec;
1869   ArgVec.push_back(LHS);
1870   ArgVec.push_back(RHS);
1871   // Get the key type with both the opcode and predicate
1872   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1873
1874   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1875   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1876     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1877
1878   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1879   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1880 }
1881
1882 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1883   assert(Val->getType()->isVectorTy() &&
1884          "Tried to create extractelement operation on non-vector type!");
1885   assert(Idx->getType()->isIntegerTy(32) &&
1886          "Extractelement index must be i32 type!");
1887   
1888   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1889     return FC;          // Fold a few common cases.
1890   
1891   // Look up the constant in the table first to ensure uniqueness
1892   std::vector<Constant*> ArgVec(1, Val);
1893   ArgVec.push_back(Idx);
1894   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1895   
1896   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1897   Type *ReqTy = Val->getType()->getVectorElementType();
1898   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1899 }
1900
1901 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1902                                          Constant *Idx) {
1903   assert(Val->getType()->isVectorTy() &&
1904          "Tried to create insertelement operation on non-vector type!");
1905   assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1906          "Insertelement types must match!");
1907   assert(Idx->getType()->isIntegerTy(32) &&
1908          "Insertelement index must be i32 type!");
1909
1910   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1911     return FC;          // Fold a few common cases.
1912   // Look up the constant in the table first to ensure uniqueness
1913   std::vector<Constant*> ArgVec(1, Val);
1914   ArgVec.push_back(Elt);
1915   ArgVec.push_back(Idx);
1916   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1917   
1918   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1919   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1920 }
1921
1922 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1923                                          Constant *Mask) {
1924   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1925          "Invalid shuffle vector constant expr operands!");
1926
1927   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1928     return FC;          // Fold a few common cases.
1929
1930   unsigned NElts = Mask->getType()->getVectorNumElements();
1931   Type *EltTy = V1->getType()->getVectorElementType();
1932   Type *ShufTy = VectorType::get(EltTy, NElts);
1933
1934   // Look up the constant in the table first to ensure uniqueness
1935   std::vector<Constant*> ArgVec(1, V1);
1936   ArgVec.push_back(V2);
1937   ArgVec.push_back(Mask);
1938   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1939   
1940   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1941   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1942 }
1943
1944 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1945                                        ArrayRef<unsigned> Idxs) {
1946   assert(ExtractValueInst::getIndexedType(Agg->getType(),
1947                                           Idxs) == Val->getType() &&
1948          "insertvalue indices invalid!");
1949   assert(Agg->getType()->isFirstClassType() &&
1950          "Non-first-class type for constant insertvalue expression");
1951   Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1952   assert(FC && "insertvalue constant expr couldn't be folded!");
1953   return FC;
1954 }
1955
1956 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1957                                         ArrayRef<unsigned> Idxs) {
1958   assert(Agg->getType()->isFirstClassType() &&
1959          "Tried to create extractelement operation on non-first-class type!");
1960
1961   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1962   (void)ReqTy;
1963   assert(ReqTy && "extractvalue indices invalid!");
1964   
1965   assert(Agg->getType()->isFirstClassType() &&
1966          "Non-first-class type for constant extractvalue expression");
1967   Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1968   assert(FC && "ExtractValue constant expr couldn't be folded!");
1969   return FC;
1970 }
1971
1972 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1973   assert(C->getType()->isIntOrIntVectorTy() &&
1974          "Cannot NEG a nonintegral value!");
1975   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1976                 C, HasNUW, HasNSW);
1977 }
1978
1979 Constant *ConstantExpr::getFNeg(Constant *C) {
1980   assert(C->getType()->isFPOrFPVectorTy() &&
1981          "Cannot FNEG a non-floating-point value!");
1982   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1983 }
1984
1985 Constant *ConstantExpr::getNot(Constant *C) {
1986   assert(C->getType()->isIntOrIntVectorTy() &&
1987          "Cannot NOT a nonintegral value!");
1988   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1989 }
1990
1991 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1992                                bool HasNUW, bool HasNSW) {
1993   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1994                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1995   return get(Instruction::Add, C1, C2, Flags);
1996 }
1997
1998 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1999   return get(Instruction::FAdd, C1, C2);
2000 }
2001
2002 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2003                                bool HasNUW, bool HasNSW) {
2004   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2005                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2006   return get(Instruction::Sub, C1, C2, Flags);
2007 }
2008
2009 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2010   return get(Instruction::FSub, C1, C2);
2011 }
2012
2013 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2014                                bool HasNUW, bool HasNSW) {
2015   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2016                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2017   return get(Instruction::Mul, C1, C2, Flags);
2018 }
2019
2020 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2021   return get(Instruction::FMul, C1, C2);
2022 }
2023
2024 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2025   return get(Instruction::UDiv, C1, C2,
2026              isExact ? PossiblyExactOperator::IsExact : 0);
2027 }
2028
2029 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2030   return get(Instruction::SDiv, C1, C2,
2031              isExact ? PossiblyExactOperator::IsExact : 0);
2032 }
2033
2034 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2035   return get(Instruction::FDiv, C1, C2);
2036 }
2037
2038 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2039   return get(Instruction::URem, C1, C2);
2040 }
2041
2042 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2043   return get(Instruction::SRem, C1, C2);
2044 }
2045
2046 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2047   return get(Instruction::FRem, C1, C2);
2048 }
2049
2050 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2051   return get(Instruction::And, C1, C2);
2052 }
2053
2054 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2055   return get(Instruction::Or, C1, C2);
2056 }
2057
2058 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2059   return get(Instruction::Xor, C1, C2);
2060 }
2061
2062 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2063                                bool HasNUW, bool HasNSW) {
2064   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2065                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2066   return get(Instruction::Shl, C1, C2, Flags);
2067 }
2068
2069 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2070   return get(Instruction::LShr, C1, C2,
2071              isExact ? PossiblyExactOperator::IsExact : 0);
2072 }
2073
2074 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2075   return get(Instruction::AShr, C1, C2,
2076              isExact ? PossiblyExactOperator::IsExact : 0);
2077 }
2078
2079 // destroyConstant - Remove the constant from the constant table...
2080 //
2081 void ConstantExpr::destroyConstant() {
2082   getType()->getContext().pImpl->ExprConstants.remove(this);
2083   destroyConstantImpl();
2084 }
2085
2086 const char *ConstantExpr::getOpcodeName() const {
2087   return Instruction::getOpcodeName(getOpcode());
2088 }
2089
2090
2091
2092 GetElementPtrConstantExpr::
2093 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2094                           Type *DestTy)
2095   : ConstantExpr(DestTy, Instruction::GetElementPtr,
2096                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2097                  - (IdxList.size()+1), IdxList.size()+1) {
2098   OperandList[0] = C;
2099   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2100     OperandList[i+1] = IdxList[i];
2101 }
2102
2103 //===----------------------------------------------------------------------===//
2104 //                       ConstantData* implementations
2105
2106 void ConstantDataArray::anchor() {}
2107 void ConstantDataVector::anchor() {}
2108
2109 /// getElementType - Return the element type of the array/vector.
2110 Type *ConstantDataSequential::getElementType() const {
2111   return getType()->getElementType();
2112 }
2113
2114 StringRef ConstantDataSequential::getRawDataValues() const {
2115   return StringRef(DataElements, getNumElements()*getElementByteSize());
2116 }
2117
2118 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2119 /// formed with a vector or array of the specified element type.
2120 /// ConstantDataArray only works with normal float and int types that are
2121 /// stored densely in memory, not with things like i42 or x86_f80.
2122 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2123   if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2124   if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2125     switch (IT->getBitWidth()) {
2126     case 8:
2127     case 16:
2128     case 32:
2129     case 64:
2130       return true;
2131     default: break;
2132     }
2133   }
2134   return false;
2135 }
2136
2137 /// getNumElements - Return the number of elements in the array or vector.
2138 unsigned ConstantDataSequential::getNumElements() const {
2139   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2140     return AT->getNumElements();
2141   return getType()->getVectorNumElements();
2142 }
2143
2144
2145 /// getElementByteSize - Return the size in bytes of the elements in the data.
2146 uint64_t ConstantDataSequential::getElementByteSize() const {
2147   return getElementType()->getPrimitiveSizeInBits()/8;
2148 }
2149
2150 /// getElementPointer - Return the start of the specified element.
2151 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2152   assert(Elt < getNumElements() && "Invalid Elt");
2153   return DataElements+Elt*getElementByteSize();
2154 }
2155
2156
2157 /// isAllZeros - return true if the array is empty or all zeros.
2158 static bool isAllZeros(StringRef Arr) {
2159   for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2160     if (*I != 0)
2161       return false;
2162   return true;
2163 }
2164
2165 /// getImpl - This is the underlying implementation of all of the
2166 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
2167 /// the correct element type.  We take the bytes in as a StringRef because
2168 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2169 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2170   assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2171   // If the elements are all zero or there are no elements, return a CAZ, which
2172   // is more dense and canonical.
2173   if (isAllZeros(Elements))
2174     return ConstantAggregateZero::get(Ty);
2175
2176   // Do a lookup to see if we have already formed one of these.
2177   StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2178     Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2179   
2180   // The bucket can point to a linked list of different CDS's that have the same
2181   // body but different types.  For example, 0,0,0,1 could be a 4 element array
2182   // of i8, or a 1-element array of i32.  They'll both end up in the same
2183   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
2184   ConstantDataSequential **Entry = &Slot.getValue();
2185   for (ConstantDataSequential *Node = *Entry; Node != 0;
2186        Entry = &Node->Next, Node = *Entry)
2187     if (Node->getType() == Ty)
2188       return Node;
2189   
2190   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
2191   // and return it.
2192   if (isa<ArrayType>(Ty))
2193     return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2194
2195   assert(isa<VectorType>(Ty));
2196   return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2197 }
2198
2199 void ConstantDataSequential::destroyConstant() {
2200   // Remove the constant from the StringMap.
2201   StringMap<ConstantDataSequential*> &CDSConstants = 
2202     getType()->getContext().pImpl->CDSConstants;
2203   
2204   StringMap<ConstantDataSequential*>::iterator Slot =
2205     CDSConstants.find(getRawDataValues());
2206
2207   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2208
2209   ConstantDataSequential **Entry = &Slot->getValue();
2210
2211   // Remove the entry from the hash table.
2212   if ((*Entry)->Next == 0) {
2213     // If there is only one value in the bucket (common case) it must be this
2214     // entry, and removing the entry should remove the bucket completely.
2215     assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2216     getContext().pImpl->CDSConstants.erase(Slot);
2217   } else {
2218     // Otherwise, there are multiple entries linked off the bucket, unlink the 
2219     // node we care about but keep the bucket around.
2220     for (ConstantDataSequential *Node = *Entry; ;
2221          Entry = &Node->Next, Node = *Entry) {
2222       assert(Node && "Didn't find entry in its uniquing hash table!");
2223       // If we found our entry, unlink it from the list and we're done.
2224       if (Node == this) {
2225         *Entry = Node->Next;
2226         break;
2227       }
2228     }
2229   }
2230   
2231   // If we were part of a list, make sure that we don't delete the list that is
2232   // still owned by the uniquing map.
2233   Next = 0;
2234   
2235   // Finally, actually delete it.
2236   destroyConstantImpl();
2237 }
2238
2239 /// get() constructors - Return a constant with array type with an element
2240 /// count and element type matching the ArrayRef passed in.  Note that this
2241 /// can return a ConstantAggregateZero object.
2242 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2243   Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2244   return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2245 }
2246 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2247   Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2248   return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2249 }
2250 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2251   Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2252   return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2253 }
2254 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2255   Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2256   return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2257 }
2258 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2259   Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2260   return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2261 }
2262 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2263   Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2264   return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2265 }
2266
2267 /// getString - This method constructs a CDS and initializes it with a text
2268 /// string. The default behavior (AddNull==true) causes a null terminator to
2269 /// be placed at the end of the array (increasing the length of the string by
2270 /// one more than the StringRef would normally indicate.  Pass AddNull=false
2271 /// to disable this behavior.
2272 Constant *ConstantDataArray::getString(LLVMContext &Context,
2273                                        StringRef Str, bool AddNull) {
2274   if (!AddNull)
2275     return get(Context, ArrayRef<uint8_t>((uint8_t*)Str.data(), Str.size()));
2276   
2277   SmallVector<uint8_t, 64> ElementVals;
2278   ElementVals.append(Str.begin(), Str.end());
2279   ElementVals.push_back(0);
2280   return get(Context, ElementVals);
2281 }
2282
2283 /// get() constructors - Return a constant with vector type with an element
2284 /// count and element type matching the ArrayRef passed in.  Note that this
2285 /// can return a ConstantAggregateZero object.
2286 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2287   Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2288   return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2289 }
2290 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2291   Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2292   return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2293 }
2294 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2295   Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2296   return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2297 }
2298 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2299   Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2300   return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2301 }
2302 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2303   Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2304   return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2305 }
2306 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2307   Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2308   return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2309 }
2310
2311 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2312   assert(isElementTypeCompatible(V->getType()) &&
2313          "Element type not compatible with ConstantData");
2314   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2315     if (CI->getType()->isIntegerTy(8)) {
2316       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2317       return get(V->getContext(), Elts);
2318     }
2319     if (CI->getType()->isIntegerTy(16)) {
2320       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2321       return get(V->getContext(), Elts);
2322     }
2323     if (CI->getType()->isIntegerTy(32)) {
2324       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2325       return get(V->getContext(), Elts);
2326     }
2327     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2328     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2329     return get(V->getContext(), Elts);
2330   }
2331
2332   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2333     if (CFP->getType()->isFloatTy()) {
2334       SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2335       return get(V->getContext(), Elts);
2336     }
2337     if (CFP->getType()->isDoubleTy()) {
2338       SmallVector<double, 16> Elts(NumElts,
2339                                    CFP->getValueAPF().convertToDouble());
2340       return get(V->getContext(), Elts);
2341     }
2342   }
2343   return ConstantVector::getSplat(NumElts, V);
2344 }
2345
2346
2347 /// getElementAsInteger - If this is a sequential container of integers (of
2348 /// any size), return the specified element in the low bits of a uint64_t.
2349 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2350   assert(isa<IntegerType>(getElementType()) &&
2351          "Accessor can only be used when element is an integer");
2352   const char *EltPtr = getElementPointer(Elt);
2353   
2354   // The data is stored in host byte order, make sure to cast back to the right
2355   // type to load with the right endianness.
2356   switch (getElementType()->getIntegerBitWidth()) {
2357   default: assert(0 && "Invalid bitwidth for CDS");
2358   case 8:  return *(uint8_t*)EltPtr;
2359   case 16: return *(uint16_t*)EltPtr;
2360   case 32: return *(uint32_t*)EltPtr;
2361   case 64: return *(uint64_t*)EltPtr;
2362   }
2363 }
2364
2365 /// getElementAsAPFloat - If this is a sequential container of floating point
2366 /// type, return the specified element as an APFloat.
2367 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2368   const char *EltPtr = getElementPointer(Elt);
2369
2370   switch (getElementType()->getTypeID()) {
2371   default:
2372     assert(0 && "Accessor can only be used when element is float/double!");
2373   case Type::FloatTyID: return APFloat(*(float*)EltPtr);
2374   case Type::DoubleTyID: return APFloat(*(double*)EltPtr);
2375   }
2376 }
2377
2378 /// getElementAsFloat - If this is an sequential container of floats, return
2379 /// the specified element as a float.
2380 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2381   assert(getElementType()->isFloatTy() &&
2382          "Accessor can only be used when element is a 'float'");
2383   return *(float*)getElementPointer(Elt);
2384 }
2385
2386 /// getElementAsDouble - If this is an sequential container of doubles, return
2387 /// the specified element as a float.
2388 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2389   assert(getElementType()->isDoubleTy() &&
2390          "Accessor can only be used when element is a 'float'");
2391   return *(double*)getElementPointer(Elt);
2392 }
2393
2394 /// getElementAsConstant - Return a Constant for a specified index's element.
2395 /// Note that this has to compute a new constant to return, so it isn't as
2396 /// efficient as getElementAsInteger/Float/Double.
2397 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2398   if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2399     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2400   
2401   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2402 }
2403
2404 /// isString - This method returns true if this is an array of i8.
2405 bool ConstantDataSequential::isString() const {
2406   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2407 }
2408
2409 /// isCString - This method returns true if the array "isString", ends with a
2410 /// nul byte, and does not contains any other nul bytes.
2411 bool ConstantDataSequential::isCString() const {
2412   if (!isString())
2413     return false;
2414   
2415   StringRef Str = getAsString();
2416   
2417   // The last value must be nul.
2418   if (Str.back() != 0) return false;
2419   
2420   // Other elements must be non-nul.
2421   return Str.drop_back().find(0) == StringRef::npos;
2422 }
2423
2424 /// getSplatValue - If this is a splat constant, meaning that all of the
2425 /// elements have the same value, return that value. Otherwise return NULL.
2426 Constant *ConstantDataVector::getSplatValue() const {
2427   const char *Base = getRawDataValues().data();
2428   
2429   // Compare elements 1+ to the 0'th element.
2430   unsigned EltSize = getElementByteSize();
2431   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2432     if (memcmp(Base, Base+i*EltSize, EltSize))
2433       return 0;
2434   
2435   // If they're all the same, return the 0th one as a representative.
2436   return getElementAsConstant(0);
2437 }
2438
2439 //===----------------------------------------------------------------------===//
2440 //                replaceUsesOfWithOnConstant implementations
2441
2442 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2443 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2444 /// etc.
2445 ///
2446 /// Note that we intentionally replace all uses of From with To here.  Consider
2447 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2448 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2449 /// single invocation handles all 1000 uses.  Handling them one at a time would
2450 /// work, but would be really slow because it would have to unique each updated
2451 /// array instance.
2452 ///
2453 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2454                                                 Use *U) {
2455   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2456   Constant *ToC = cast<Constant>(To);
2457
2458   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2459
2460   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
2461   Lookup.first.first = cast<ArrayType>(getType());
2462   Lookup.second = this;
2463
2464   std::vector<Constant*> &Values = Lookup.first.second;
2465   Values.reserve(getNumOperands());  // Build replacement array.
2466
2467   // Fill values with the modified operands of the constant array.  Also, 
2468   // compute whether this turns into an all-zeros array.
2469   unsigned NumUpdated = 0;
2470   
2471   // Keep track of whether all the values in the array are "ToC".
2472   bool AllSame = true;
2473   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2474     Constant *Val = cast<Constant>(O->get());
2475     if (Val == From) {
2476       Val = ToC;
2477       ++NumUpdated;
2478     }
2479     Values.push_back(Val);
2480     AllSame = Val == ToC;
2481   }
2482   
2483   Constant *Replacement = 0;
2484   if (AllSame && ToC->isNullValue()) {
2485     Replacement = ConstantAggregateZero::get(getType());
2486   } else if (AllSame && isa<UndefValue>(ToC)) {
2487     Replacement = UndefValue::get(getType());
2488   } else {
2489     // Check to see if we have this array type already.
2490     bool Exists;
2491     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2492       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2493     
2494     if (Exists) {
2495       Replacement = I->second;
2496     } else {
2497       // Okay, the new shape doesn't exist in the system yet.  Instead of
2498       // creating a new constant array, inserting it, replaceallusesof'ing the
2499       // old with the new, then deleting the old... just update the current one
2500       // in place!
2501       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2502       
2503       // Update to the new value.  Optimize for the case when we have a single
2504       // operand that we're changing, but handle bulk updates efficiently.
2505       if (NumUpdated == 1) {
2506         unsigned OperandToUpdate = U - OperandList;
2507         assert(getOperand(OperandToUpdate) == From &&
2508                "ReplaceAllUsesWith broken!");
2509         setOperand(OperandToUpdate, ToC);
2510       } else {
2511         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2512           if (getOperand(i) == From)
2513             setOperand(i, ToC);
2514       }
2515       return;
2516     }
2517   }
2518  
2519   // Otherwise, I do need to replace this with an existing value.
2520   assert(Replacement != this && "I didn't contain From!");
2521   
2522   // Everyone using this now uses the replacement.
2523   replaceAllUsesWith(Replacement);
2524   
2525   // Delete the old constant!
2526   destroyConstant();
2527 }
2528
2529 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2530                                                  Use *U) {
2531   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2532   Constant *ToC = cast<Constant>(To);
2533
2534   unsigned OperandToUpdate = U-OperandList;
2535   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2536
2537   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2538   Lookup.first.first = cast<StructType>(getType());
2539   Lookup.second = this;
2540   std::vector<Constant*> &Values = Lookup.first.second;
2541   Values.reserve(getNumOperands());  // Build replacement struct.
2542   
2543   
2544   // Fill values with the modified operands of the constant struct.  Also, 
2545   // compute whether this turns into an all-zeros struct.
2546   bool isAllZeros = false;
2547   bool isAllUndef = false;
2548   if (ToC->isNullValue()) {
2549     isAllZeros = true;
2550     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2551       Constant *Val = cast<Constant>(O->get());
2552       Values.push_back(Val);
2553       if (isAllZeros) isAllZeros = Val->isNullValue();
2554     }
2555   } else if (isa<UndefValue>(ToC)) {
2556     isAllUndef = true;
2557     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2558       Constant *Val = cast<Constant>(O->get());
2559       Values.push_back(Val);
2560       if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2561     }
2562   } else {
2563     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2564       Values.push_back(cast<Constant>(O->get()));
2565   }
2566   Values[OperandToUpdate] = ToC;
2567   
2568   LLVMContextImpl *pImpl = getContext().pImpl;
2569   
2570   Constant *Replacement = 0;
2571   if (isAllZeros) {
2572     Replacement = ConstantAggregateZero::get(getType());
2573   } else if (isAllUndef) {
2574     Replacement = UndefValue::get(getType());
2575   } else {
2576     // Check to see if we have this struct type already.
2577     bool Exists;
2578     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2579       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2580     
2581     if (Exists) {
2582       Replacement = I->second;
2583     } else {
2584       // Okay, the new shape doesn't exist in the system yet.  Instead of
2585       // creating a new constant struct, inserting it, replaceallusesof'ing the
2586       // old with the new, then deleting the old... just update the current one
2587       // in place!
2588       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2589       
2590       // Update to the new value.
2591       setOperand(OperandToUpdate, ToC);
2592       return;
2593     }
2594   }
2595   
2596   assert(Replacement != this && "I didn't contain From!");
2597   
2598   // Everyone using this now uses the replacement.
2599   replaceAllUsesWith(Replacement);
2600   
2601   // Delete the old constant!
2602   destroyConstant();
2603 }
2604
2605 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2606                                                  Use *U) {
2607   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2608   
2609   SmallVector<Constant*, 8> Values;
2610   Values.reserve(getNumOperands());  // Build replacement array...
2611   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2612     Constant *Val = getOperand(i);
2613     if (Val == From) Val = cast<Constant>(To);
2614     Values.push_back(Val);
2615   }
2616   
2617   Constant *Replacement = get(Values);
2618   assert(Replacement != this && "I didn't contain From!");
2619   
2620   // Everyone using this now uses the replacement.
2621   replaceAllUsesWith(Replacement);
2622   
2623   // Delete the old constant!
2624   destroyConstant();
2625 }
2626
2627 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2628                                                Use *U) {
2629   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2630   Constant *To = cast<Constant>(ToV);
2631   
2632   SmallVector<Constant*, 8> NewOps;
2633   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2634     Constant *Op = getOperand(i);
2635     NewOps.push_back(Op == From ? To : Op);
2636   }
2637   
2638   Constant *Replacement = getWithOperands(NewOps);
2639   assert(Replacement != this && "I didn't contain From!");
2640   
2641   // Everyone using this now uses the replacement.
2642   replaceAllUsesWith(Replacement);
2643   
2644   // Delete the old constant!
2645   destroyConstant();
2646 }