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