Revert "Include optional subclass flags, such as inbounds, nsw, etc., ...", this
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
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 all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/ConstantRange.h"
24 #include "llvm/Support/MathExtras.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //                            CallSite Class
29 //===----------------------------------------------------------------------===//
30
31 #define CALLSITE_DELEGATE_GETTER(METHOD) \
32   Instruction *II(getInstruction());     \
33   return isCall()                        \
34     ? cast<CallInst>(II)->METHOD         \
35     : cast<InvokeInst>(II)->METHOD
36
37 #define CALLSITE_DELEGATE_SETTER(METHOD) \
38   Instruction *II(getInstruction());     \
39   if (isCall())                          \
40     cast<CallInst>(II)->METHOD;          \
41   else                                   \
42     cast<InvokeInst>(II)->METHOD
43
44 CallSite::CallSite(Instruction *C) {
45   assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
46   I.setPointer(C);
47   I.setInt(isa<CallInst>(C));
48 }
49 CallingConv::ID CallSite::getCallingConv() const {
50   CALLSITE_DELEGATE_GETTER(getCallingConv());
51 }
52 void CallSite::setCallingConv(CallingConv::ID CC) {
53   CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
54 }
55 const AttrListPtr &CallSite::getAttributes() const {
56   CALLSITE_DELEGATE_GETTER(getAttributes());
57 }
58 void CallSite::setAttributes(const AttrListPtr &PAL) {
59   CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
60 }
61 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
62   CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
63 }
64 uint16_t CallSite::getParamAlignment(uint16_t i) const {
65   CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
66 }
67 bool CallSite::doesNotAccessMemory() const {
68   CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
69 }
70 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
71   CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
72 }
73 bool CallSite::onlyReadsMemory() const {
74   CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
75 }
76 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
77   CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
78 }
79 bool CallSite::doesNotReturn() const {
80  CALLSITE_DELEGATE_GETTER(doesNotReturn());
81 }
82 void CallSite::setDoesNotReturn(bool doesNotReturn) {
83   CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
84 }
85 bool CallSite::doesNotThrow() const {
86   CALLSITE_DELEGATE_GETTER(doesNotThrow());
87 }
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89   CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
90 }
91
92 bool CallSite::hasArgument(const Value *Arg) const {
93   for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
94     if (AI->get() == Arg)
95       return true;
96   return false;
97 }
98
99 #undef CALLSITE_DELEGATE_GETTER
100 #undef CALLSITE_DELEGATE_SETTER
101
102 //===----------------------------------------------------------------------===//
103 //                            TerminatorInst Class
104 //===----------------------------------------------------------------------===//
105
106 // Out of line virtual method, so the vtable, etc has a home.
107 TerminatorInst::~TerminatorInst() {
108 }
109
110 //===----------------------------------------------------------------------===//
111 //                           UnaryInstruction Class
112 //===----------------------------------------------------------------------===//
113
114 // Out of line virtual method, so the vtable, etc has a home.
115 UnaryInstruction::~UnaryInstruction() {
116 }
117
118 //===----------------------------------------------------------------------===//
119 //                              SelectInst Class
120 //===----------------------------------------------------------------------===//
121
122 /// areInvalidOperands - Return a string if the specified operands are invalid
123 /// for a select operation, otherwise return null.
124 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
125   if (Op1->getType() != Op2->getType())
126     return "both values to select must have same type";
127   
128   if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
129     // Vector select.
130     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
131       return "vector select condition element type must be i1";
132     const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
133     if (ET == 0)
134       return "selected values for vector select must be vectors";
135     if (ET->getNumElements() != VT->getNumElements())
136       return "vector select requires selected vectors to have "
137                    "the same vector length as select condition";
138   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
139     return "select condition must be i1 or <n x i1>";
140   }
141   return 0;
142 }
143
144
145 //===----------------------------------------------------------------------===//
146 //                               PHINode Class
147 //===----------------------------------------------------------------------===//
148
149 PHINode::PHINode(const PHINode &PN)
150   : Instruction(PN.getType(), Instruction::PHI,
151                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
152     ReservedSpace(PN.getNumOperands()) {
153   Use *OL = OperandList;
154   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
155     OL[i] = PN.getOperand(i);
156     OL[i+1] = PN.getOperand(i+1);
157   }
158   SubclassOptionalData = PN.SubclassOptionalData;
159 }
160
161 PHINode::~PHINode() {
162   if (OperandList)
163     dropHungoffUses(OperandList);
164 }
165
166 // removeIncomingValue - Remove an incoming value.  This is useful if a
167 // predecessor basic block is deleted.
168 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
169   unsigned NumOps = getNumOperands();
170   Use *OL = OperandList;
171   assert(Idx*2 < NumOps && "BB not in PHI node!");
172   Value *Removed = OL[Idx*2];
173
174   // Move everything after this operand down.
175   //
176   // FIXME: we could just swap with the end of the list, then erase.  However,
177   // client might not expect this to happen.  The code as it is thrashes the
178   // use/def lists, which is kinda lame.
179   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
180     OL[i-2] = OL[i];
181     OL[i-2+1] = OL[i+1];
182   }
183
184   // Nuke the last value.
185   OL[NumOps-2].set(0);
186   OL[NumOps-2+1].set(0);
187   NumOperands = NumOps-2;
188
189   // If the PHI node is dead, because it has zero entries, nuke it now.
190   if (NumOps == 2 && DeletePHIIfEmpty) {
191     // If anyone is using this PHI, make them use a dummy value instead...
192     replaceAllUsesWith(UndefValue::get(getType()));
193     eraseFromParent();
194   }
195   return Removed;
196 }
197
198 /// resizeOperands - resize operands - This adjusts the length of the operands
199 /// list according to the following behavior:
200 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
201 ///      of operation.  This grows the number of ops by 1.5 times.
202 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
203 ///   3. If NumOps == NumOperands, trim the reserved space.
204 ///
205 void PHINode::resizeOperands(unsigned NumOps) {
206   unsigned e = getNumOperands();
207   if (NumOps == 0) {
208     NumOps = e*3/2;
209     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
210   } else if (NumOps*2 > NumOperands) {
211     // No resize needed.
212     if (ReservedSpace >= NumOps) return;
213   } else if (NumOps == NumOperands) {
214     if (ReservedSpace == NumOps) return;
215   } else {
216     return;
217   }
218
219   ReservedSpace = NumOps;
220   Use *OldOps = OperandList;
221   Use *NewOps = allocHungoffUses(NumOps);
222   std::copy(OldOps, OldOps + e, NewOps);
223   OperandList = NewOps;
224   if (OldOps) Use::zap(OldOps, OldOps + e, true);
225 }
226
227 /// hasConstantValue - If the specified PHI node always merges together the same
228 /// value, return the value, otherwise return null.
229 ///
230 /// If the PHI has undef operands, but all the rest of the operands are
231 /// some unique value, return that value if it can be proved that the
232 /// value dominates the PHI. If DT is null, use a conservative check,
233 /// otherwise use DT to test for dominance.
234 ///
235 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
236   // If the PHI node only has one incoming value, eliminate the PHI node...
237   if (getNumIncomingValues() == 1) {
238     if (getIncomingValue(0) != this)   // not  X = phi X
239       return getIncomingValue(0);
240     else
241       return UndefValue::get(getType());  // Self cycle is dead.
242   }
243       
244   // Otherwise if all of the incoming values are the same for the PHI, replace
245   // the PHI node with the incoming value.
246   //
247   Value *InVal = 0;
248   bool HasUndefInput = false;
249   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
250     if (isa<UndefValue>(getIncomingValue(i))) {
251       HasUndefInput = true;
252     } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
253       if (InVal && getIncomingValue(i) != InVal)
254         return 0;  // Not the same, bail out.
255       else
256         InVal = getIncomingValue(i);
257     }
258   
259   // The only case that could cause InVal to be null is if we have a PHI node
260   // that only has entries for itself.  In this case, there is no entry into the
261   // loop, so kill the PHI.
262   //
263   if (InVal == 0) InVal = UndefValue::get(getType());
264   
265   // If we have a PHI node like phi(X, undef, X), where X is defined by some
266   // instruction, we cannot always return X as the result of the PHI node.  Only
267   // do this if X is not an instruction (thus it must dominate the PHI block),
268   // or if the client is prepared to deal with this possibility.
269   if (HasUndefInput)
270     if (Instruction *IV = dyn_cast<Instruction>(InVal)) {
271       if (DT) {
272         // We have a DominatorTree. Do a precise test.
273         if (!DT->dominates(IV, this))
274           return 0;
275       } else {
276         // If it's in the entry block, it dominates everything.
277         if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
278             isa<InvokeInst>(IV))
279           return 0;   // Cannot guarantee that InVal dominates this PHINode.
280       }
281     }
282
283   // All of the incoming values are the same, return the value now.
284   return InVal;
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 //                        CallInst Implementation
290 //===----------------------------------------------------------------------===//
291
292 CallInst::~CallInst() {
293 }
294
295 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
296   assert(NumOperands == NumParams+1 && "NumOperands not set up?");
297   Use *OL = OperandList;
298   OL[0] = Func;
299
300   const FunctionType *FTy =
301     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
302   FTy = FTy;  // silence warning.
303
304   assert((NumParams == FTy->getNumParams() ||
305           (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
306          "Calling a function with bad signature!");
307   for (unsigned i = 0; i != NumParams; ++i) {
308     assert((i >= FTy->getNumParams() || 
309             FTy->getParamType(i) == Params[i]->getType()) &&
310            "Calling a function with a bad signature!");
311     OL[i+1] = Params[i];
312   }
313 }
314
315 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
316   assert(NumOperands == 3 && "NumOperands not set up?");
317   Use *OL = OperandList;
318   OL[0] = Func;
319   OL[1] = Actual1;
320   OL[2] = Actual2;
321
322   const FunctionType *FTy =
323     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
324   FTy = FTy;  // silence warning.
325
326   assert((FTy->getNumParams() == 2 ||
327           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
328          "Calling a function with bad signature");
329   assert((0 >= FTy->getNumParams() || 
330           FTy->getParamType(0) == Actual1->getType()) &&
331          "Calling a function with a bad signature!");
332   assert((1 >= FTy->getNumParams() || 
333           FTy->getParamType(1) == Actual2->getType()) &&
334          "Calling a function with a bad signature!");
335 }
336
337 void CallInst::init(Value *Func, Value *Actual) {
338   assert(NumOperands == 2 && "NumOperands not set up?");
339   Use *OL = OperandList;
340   OL[0] = Func;
341   OL[1] = Actual;
342
343   const FunctionType *FTy =
344     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
345   FTy = FTy;  // silence warning.
346
347   assert((FTy->getNumParams() == 1 ||
348           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
349          "Calling a function with bad signature");
350   assert((0 == FTy->getNumParams() || 
351           FTy->getParamType(0) == Actual->getType()) &&
352          "Calling a function with a bad signature!");
353 }
354
355 void CallInst::init(Value *Func) {
356   assert(NumOperands == 1 && "NumOperands not set up?");
357   Use *OL = OperandList;
358   OL[0] = Func;
359
360   const FunctionType *FTy =
361     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
362   FTy = FTy;  // silence warning.
363
364   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
365 }
366
367 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
368                    Instruction *InsertBefore)
369   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
370                                    ->getElementType())->getReturnType(),
371                 Instruction::Call,
372                 OperandTraits<CallInst>::op_end(this) - 2,
373                 2, InsertBefore) {
374   init(Func, Actual);
375   setName(Name);
376 }
377
378 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
379                    BasicBlock  *InsertAtEnd)
380   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
381                                    ->getElementType())->getReturnType(),
382                 Instruction::Call,
383                 OperandTraits<CallInst>::op_end(this) - 2,
384                 2, InsertAtEnd) {
385   init(Func, Actual);
386   setName(Name);
387 }
388 CallInst::CallInst(Value *Func, const Twine &Name,
389                    Instruction *InsertBefore)
390   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
391                                    ->getElementType())->getReturnType(),
392                 Instruction::Call,
393                 OperandTraits<CallInst>::op_end(this) - 1,
394                 1, InsertBefore) {
395   init(Func);
396   setName(Name);
397 }
398
399 CallInst::CallInst(Value *Func, const Twine &Name,
400                    BasicBlock *InsertAtEnd)
401   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
402                                    ->getElementType())->getReturnType(),
403                 Instruction::Call,
404                 OperandTraits<CallInst>::op_end(this) - 1,
405                 1, InsertAtEnd) {
406   init(Func);
407   setName(Name);
408 }
409
410 CallInst::CallInst(const CallInst &CI)
411   : Instruction(CI.getType(), Instruction::Call,
412                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
413                 CI.getNumOperands()) {
414   setAttributes(CI.getAttributes());
415   SubclassData = CI.SubclassData;
416   Use *OL = OperandList;
417   Use *InOL = CI.OperandList;
418   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
419     OL[i] = InOL[i];
420   SubclassOptionalData = CI.SubclassOptionalData;
421 }
422
423 void CallInst::addAttribute(unsigned i, Attributes attr) {
424   AttrListPtr PAL = getAttributes();
425   PAL = PAL.addAttr(i, attr);
426   setAttributes(PAL);
427 }
428
429 void CallInst::removeAttribute(unsigned i, Attributes attr) {
430   AttrListPtr PAL = getAttributes();
431   PAL = PAL.removeAttr(i, attr);
432   setAttributes(PAL);
433 }
434
435 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
436   if (AttributeList.paramHasAttr(i, attr))
437     return true;
438   if (const Function *F = getCalledFunction())
439     return F->paramHasAttr(i, attr);
440   return false;
441 }
442
443
444 //===----------------------------------------------------------------------===//
445 //                        InvokeInst Implementation
446 //===----------------------------------------------------------------------===//
447
448 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
449                       Value* const *Args, unsigned NumArgs) {
450   assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
451   Use *OL = OperandList;
452   OL[0] = Fn;
453   OL[1] = IfNormal;
454   OL[2] = IfException;
455   const FunctionType *FTy =
456     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
457   FTy = FTy;  // silence warning.
458
459   assert(((NumArgs == FTy->getNumParams()) ||
460           (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
461          "Calling a function with bad signature");
462
463   for (unsigned i = 0, e = NumArgs; i != e; i++) {
464     assert((i >= FTy->getNumParams() || 
465             FTy->getParamType(i) == Args[i]->getType()) &&
466            "Invoking a function with a bad signature!");
467     
468     OL[i+3] = Args[i];
469   }
470 }
471
472 InvokeInst::InvokeInst(const InvokeInst &II)
473   : TerminatorInst(II.getType(), Instruction::Invoke,
474                    OperandTraits<InvokeInst>::op_end(this)
475                    - II.getNumOperands(),
476                    II.getNumOperands()) {
477   setAttributes(II.getAttributes());
478   SubclassData = II.SubclassData;
479   Use *OL = OperandList, *InOL = II.OperandList;
480   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
481     OL[i] = InOL[i];
482   SubclassOptionalData = II.SubclassOptionalData;
483 }
484
485 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
486   return getSuccessor(idx);
487 }
488 unsigned InvokeInst::getNumSuccessorsV() const {
489   return getNumSuccessors();
490 }
491 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
492   return setSuccessor(idx, B);
493 }
494
495 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
496   if (AttributeList.paramHasAttr(i, attr))
497     return true;
498   if (const Function *F = getCalledFunction())
499     return F->paramHasAttr(i, attr);
500   return false;
501 }
502
503 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
504   AttrListPtr PAL = getAttributes();
505   PAL = PAL.addAttr(i, attr);
506   setAttributes(PAL);
507 }
508
509 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
510   AttrListPtr PAL = getAttributes();
511   PAL = PAL.removeAttr(i, attr);
512   setAttributes(PAL);
513 }
514
515
516 //===----------------------------------------------------------------------===//
517 //                        ReturnInst Implementation
518 //===----------------------------------------------------------------------===//
519
520 ReturnInst::ReturnInst(const ReturnInst &RI)
521   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
522                    OperandTraits<ReturnInst>::op_end(this) -
523                      RI.getNumOperands(),
524                    RI.getNumOperands()) {
525   if (RI.getNumOperands())
526     Op<0>() = RI.Op<0>();
527   SubclassOptionalData = RI.SubclassOptionalData;
528 }
529
530 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
531   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
532                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
533                    InsertBefore) {
534   if (retVal)
535     Op<0>() = retVal;
536 }
537 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
538   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
539                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
540                    InsertAtEnd) {
541   if (retVal)
542     Op<0>() = retVal;
543 }
544 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
545   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
546                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
547 }
548
549 unsigned ReturnInst::getNumSuccessorsV() const {
550   return getNumSuccessors();
551 }
552
553 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
554 /// emit the vtable for the class in this translation unit.
555 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
556   llvm_unreachable("ReturnInst has no successors!");
557 }
558
559 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
560   llvm_unreachable("ReturnInst has no successors!");
561   return 0;
562 }
563
564 ReturnInst::~ReturnInst() {
565 }
566
567 //===----------------------------------------------------------------------===//
568 //                        UnwindInst Implementation
569 //===----------------------------------------------------------------------===//
570
571 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
572   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
573                    0, 0, InsertBefore) {
574 }
575 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
576   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
577                    0, 0, InsertAtEnd) {
578 }
579
580
581 unsigned UnwindInst::getNumSuccessorsV() const {
582   return getNumSuccessors();
583 }
584
585 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
586   llvm_unreachable("UnwindInst has no successors!");
587 }
588
589 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
590   llvm_unreachable("UnwindInst has no successors!");
591   return 0;
592 }
593
594 //===----------------------------------------------------------------------===//
595 //                      UnreachableInst Implementation
596 //===----------------------------------------------------------------------===//
597
598 UnreachableInst::UnreachableInst(LLVMContext &Context, 
599                                  Instruction *InsertBefore)
600   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
601                    0, 0, InsertBefore) {
602 }
603 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
604   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
605                    0, 0, InsertAtEnd) {
606 }
607
608 unsigned UnreachableInst::getNumSuccessorsV() const {
609   return getNumSuccessors();
610 }
611
612 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
613   llvm_unreachable("UnwindInst has no successors!");
614 }
615
616 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
617   llvm_unreachable("UnwindInst has no successors!");
618   return 0;
619 }
620
621 //===----------------------------------------------------------------------===//
622 //                        BranchInst Implementation
623 //===----------------------------------------------------------------------===//
624
625 void BranchInst::AssertOK() {
626   if (isConditional())
627     assert(getCondition()->getType() == Type::getInt1Ty(getContext()) &&
628            "May only branch on boolean predicates!");
629 }
630
631 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
632   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
633                    OperandTraits<BranchInst>::op_end(this) - 1,
634                    1, InsertBefore) {
635   assert(IfTrue != 0 && "Branch destination may not be null!");
636   Op<-1>() = IfTrue;
637 }
638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
639                        Instruction *InsertBefore)
640   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
641                    OperandTraits<BranchInst>::op_end(this) - 3,
642                    3, InsertBefore) {
643   Op<-1>() = IfTrue;
644   Op<-2>() = IfFalse;
645   Op<-3>() = Cond;
646 #ifndef NDEBUG
647   AssertOK();
648 #endif
649 }
650
651 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
652   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
653                    OperandTraits<BranchInst>::op_end(this) - 1,
654                    1, InsertAtEnd) {
655   assert(IfTrue != 0 && "Branch destination may not be null!");
656   Op<-1>() = IfTrue;
657 }
658
659 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
660            BasicBlock *InsertAtEnd)
661   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
662                    OperandTraits<BranchInst>::op_end(this) - 3,
663                    3, InsertAtEnd) {
664   Op<-1>() = IfTrue;
665   Op<-2>() = IfFalse;
666   Op<-3>() = Cond;
667 #ifndef NDEBUG
668   AssertOK();
669 #endif
670 }
671
672
673 BranchInst::BranchInst(const BranchInst &BI) :
674   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
675                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
676                  BI.getNumOperands()) {
677   Op<-1>() = BI.Op<-1>();
678   if (BI.getNumOperands() != 1) {
679     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
680     Op<-3>() = BI.Op<-3>();
681     Op<-2>() = BI.Op<-2>();
682   }
683   SubclassOptionalData = BI.SubclassOptionalData;
684 }
685
686
687 Use* Use::getPrefix() {
688   PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
689   if (PotentialPrefix.getOpaqueValue())
690     return 0;
691
692   return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
693 }
694
695 BranchInst::~BranchInst() {
696   if (NumOperands == 1) {
697     if (Use *Prefix = OperandList->getPrefix()) {
698       Op<-1>() = 0;
699       //
700       // mark OperandList to have a special value for scrutiny
701       // by baseclass destructors and operator delete
702       OperandList = Prefix;
703     } else {
704       NumOperands = 3;
705       OperandList = op_begin();
706     }
707   }
708 }
709
710
711 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
712   return getSuccessor(idx);
713 }
714 unsigned BranchInst::getNumSuccessorsV() const {
715   return getNumSuccessors();
716 }
717 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
718   setSuccessor(idx, B);
719 }
720
721
722 //===----------------------------------------------------------------------===//
723 //                        AllocationInst Implementation
724 //===----------------------------------------------------------------------===//
725
726 static Value *getAISize(LLVMContext &Context, Value *Amt) {
727   if (!Amt)
728     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
729   else {
730     assert(!isa<BasicBlock>(Amt) &&
731            "Passed basic block into allocation size parameter! Use other ctor");
732     assert(Amt->getType() == Type::getInt32Ty(Context) &&
733            "Malloc/Allocation array size is not a 32-bit integer!");
734   }
735   return Amt;
736 }
737
738 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
739                                unsigned Align, const Twine &Name,
740                                Instruction *InsertBefore)
741   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
742                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
743   setAlignment(Align);
744   assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
745   setName(Name);
746 }
747
748 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
749                                unsigned Align, const Twine &Name,
750                                BasicBlock *InsertAtEnd)
751   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
752                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
753   setAlignment(Align);
754   assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
755   setName(Name);
756 }
757
758 // Out of line virtual method, so the vtable, etc has a home.
759 AllocationInst::~AllocationInst() {
760 }
761
762 void AllocationInst::setAlignment(unsigned Align) {
763   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
764   SubclassData = Log2_32(Align) + 1;
765   assert(getAlignment() == Align && "Alignment representation error!");
766 }
767
768 bool AllocationInst::isArrayAllocation() const {
769   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
770     return CI->getZExtValue() != 1;
771   return true;
772 }
773
774 const Type *AllocationInst::getAllocatedType() const {
775   return getType()->getElementType();
776 }
777
778 /// isStaticAlloca - Return true if this alloca is in the entry block of the
779 /// function and is a constant size.  If so, the code generator will fold it
780 /// into the prolog/epilog code, so it is basically free.
781 bool AllocaInst::isStaticAlloca() const {
782   // Must be constant size.
783   if (!isa<ConstantInt>(getArraySize())) return false;
784   
785   // Must be in the entry block.
786   const BasicBlock *Parent = getParent();
787   return Parent == &Parent->getParent()->front();
788 }
789
790 //===----------------------------------------------------------------------===//
791 //                             FreeInst Implementation
792 //===----------------------------------------------------------------------===//
793
794 void FreeInst::AssertOK() {
795   assert(isa<PointerType>(getOperand(0)->getType()) &&
796          "Can not free something of nonpointer type!");
797 }
798
799 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
800   : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
801                      Free, Ptr, InsertBefore) {
802   AssertOK();
803 }
804
805 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
806   : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
807                      Free, Ptr, InsertAtEnd) {
808   AssertOK();
809 }
810
811
812 //===----------------------------------------------------------------------===//
813 //                           LoadInst Implementation
814 //===----------------------------------------------------------------------===//
815
816 void LoadInst::AssertOK() {
817   assert(isa<PointerType>(getOperand(0)->getType()) &&
818          "Ptr must have pointer type.");
819 }
820
821 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
822   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823                      Load, Ptr, InsertBef) {
824   setVolatile(false);
825   setAlignment(0);
826   AssertOK();
827   setName(Name);
828 }
829
830 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
831   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
832                      Load, Ptr, InsertAE) {
833   setVolatile(false);
834   setAlignment(0);
835   AssertOK();
836   setName(Name);
837 }
838
839 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
840                    Instruction *InsertBef)
841   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
842                      Load, Ptr, InsertBef) {
843   setVolatile(isVolatile);
844   setAlignment(0);
845   AssertOK();
846   setName(Name);
847 }
848
849 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
850                    unsigned Align, Instruction *InsertBef)
851   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
852                      Load, Ptr, InsertBef) {
853   setVolatile(isVolatile);
854   setAlignment(Align);
855   AssertOK();
856   setName(Name);
857 }
858
859 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
860                    unsigned Align, BasicBlock *InsertAE)
861   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
862                      Load, Ptr, InsertAE) {
863   setVolatile(isVolatile);
864   setAlignment(Align);
865   AssertOK();
866   setName(Name);
867 }
868
869 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
870                    BasicBlock *InsertAE)
871   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872                      Load, Ptr, InsertAE) {
873   setVolatile(isVolatile);
874   setAlignment(0);
875   AssertOK();
876   setName(Name);
877 }
878
879
880
881 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
882   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
883                      Load, Ptr, InsertBef) {
884   setVolatile(false);
885   setAlignment(0);
886   AssertOK();
887   if (Name && Name[0]) setName(Name);
888 }
889
890 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
891   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
892                      Load, Ptr, InsertAE) {
893   setVolatile(false);
894   setAlignment(0);
895   AssertOK();
896   if (Name && Name[0]) setName(Name);
897 }
898
899 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
900                    Instruction *InsertBef)
901 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
902                    Load, Ptr, InsertBef) {
903   setVolatile(isVolatile);
904   setAlignment(0);
905   AssertOK();
906   if (Name && Name[0]) setName(Name);
907 }
908
909 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
910                    BasicBlock *InsertAE)
911   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
912                      Load, Ptr, InsertAE) {
913   setVolatile(isVolatile);
914   setAlignment(0);
915   AssertOK();
916   if (Name && Name[0]) setName(Name);
917 }
918
919 void LoadInst::setAlignment(unsigned Align) {
920   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
921   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
922 }
923
924 //===----------------------------------------------------------------------===//
925 //                           StoreInst Implementation
926 //===----------------------------------------------------------------------===//
927
928 void StoreInst::AssertOK() {
929   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
930   assert(isa<PointerType>(getOperand(1)->getType()) &&
931          "Ptr must have pointer type!");
932   assert(getOperand(0)->getType() ==
933                  cast<PointerType>(getOperand(1)->getType())->getElementType()
934          && "Ptr must be a pointer to Val type!");
935 }
936
937
938 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
939   : Instruction(Type::getVoidTy(val->getContext()), Store,
940                 OperandTraits<StoreInst>::op_begin(this),
941                 OperandTraits<StoreInst>::operands(this),
942                 InsertBefore) {
943   Op<0>() = val;
944   Op<1>() = addr;
945   setVolatile(false);
946   setAlignment(0);
947   AssertOK();
948 }
949
950 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
951   : Instruction(Type::getVoidTy(val->getContext()), Store,
952                 OperandTraits<StoreInst>::op_begin(this),
953                 OperandTraits<StoreInst>::operands(this),
954                 InsertAtEnd) {
955   Op<0>() = val;
956   Op<1>() = addr;
957   setVolatile(false);
958   setAlignment(0);
959   AssertOK();
960 }
961
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963                      Instruction *InsertBefore)
964   : Instruction(Type::getVoidTy(val->getContext()), Store,
965                 OperandTraits<StoreInst>::op_begin(this),
966                 OperandTraits<StoreInst>::operands(this),
967                 InsertBefore) {
968   Op<0>() = val;
969   Op<1>() = addr;
970   setVolatile(isVolatile);
971   setAlignment(0);
972   AssertOK();
973 }
974
975 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
976                      unsigned Align, Instruction *InsertBefore)
977   : Instruction(Type::getVoidTy(val->getContext()), Store,
978                 OperandTraits<StoreInst>::op_begin(this),
979                 OperandTraits<StoreInst>::operands(this),
980                 InsertBefore) {
981   Op<0>() = val;
982   Op<1>() = addr;
983   setVolatile(isVolatile);
984   setAlignment(Align);
985   AssertOK();
986 }
987
988 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
989                      unsigned Align, BasicBlock *InsertAtEnd)
990   : Instruction(Type::getVoidTy(val->getContext()), Store,
991                 OperandTraits<StoreInst>::op_begin(this),
992                 OperandTraits<StoreInst>::operands(this),
993                 InsertAtEnd) {
994   Op<0>() = val;
995   Op<1>() = addr;
996   setVolatile(isVolatile);
997   setAlignment(Align);
998   AssertOK();
999 }
1000
1001 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1002                      BasicBlock *InsertAtEnd)
1003   : Instruction(Type::getVoidTy(val->getContext()), Store,
1004                 OperandTraits<StoreInst>::op_begin(this),
1005                 OperandTraits<StoreInst>::operands(this),
1006                 InsertAtEnd) {
1007   Op<0>() = val;
1008   Op<1>() = addr;
1009   setVolatile(isVolatile);
1010   setAlignment(0);
1011   AssertOK();
1012 }
1013
1014 void StoreInst::setAlignment(unsigned Align) {
1015   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1016   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1017 }
1018
1019 //===----------------------------------------------------------------------===//
1020 //                       GetElementPtrInst Implementation
1021 //===----------------------------------------------------------------------===//
1022
1023 static unsigned retrieveAddrSpace(const Value *Val) {
1024   return cast<PointerType>(Val->getType())->getAddressSpace();
1025 }
1026
1027 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1028                              const Twine &Name) {
1029   assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1030   Use *OL = OperandList;
1031   OL[0] = Ptr;
1032
1033   for (unsigned i = 0; i != NumIdx; ++i)
1034     OL[i+1] = Idx[i];
1035
1036   setName(Name);
1037 }
1038
1039 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1040   assert(NumOperands == 2 && "NumOperands not initialized?");
1041   Use *OL = OperandList;
1042   OL[0] = Ptr;
1043   OL[1] = Idx;
1044
1045   setName(Name);
1046 }
1047
1048 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1049   : Instruction(GEPI.getType(), GetElementPtr,
1050                 OperandTraits<GetElementPtrInst>::op_end(this)
1051                 - GEPI.getNumOperands(),
1052                 GEPI.getNumOperands()) {
1053   Use *OL = OperandList;
1054   Use *GEPIOL = GEPI.OperandList;
1055   for (unsigned i = 0, E = NumOperands; i != E; ++i)
1056     OL[i] = GEPIOL[i];
1057   SubclassOptionalData = GEPI.SubclassOptionalData;
1058 }
1059
1060 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1061                                      const Twine &Name, Instruction *InBe)
1062   : Instruction(PointerType::get(
1063       checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1064                 GetElementPtr,
1065                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1066                 2, InBe) {
1067   init(Ptr, Idx, Name);
1068 }
1069
1070 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1071                                      const Twine &Name, BasicBlock *IAE)
1072   : Instruction(PointerType::get(
1073             checkType(getIndexedType(Ptr->getType(),Idx)),  
1074                 retrieveAddrSpace(Ptr)),
1075                 GetElementPtr,
1076                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1077                 2, IAE) {
1078   init(Ptr, Idx, Name);
1079 }
1080
1081 /// getIndexedType - Returns the type of the element that would be accessed with
1082 /// a gep instruction with the specified parameters.
1083 ///
1084 /// The Idxs pointer should point to a continuous piece of memory containing the
1085 /// indices, either as Value* or uint64_t.
1086 ///
1087 /// A null type is returned if the indices are invalid for the specified
1088 /// pointer type.
1089 ///
1090 template <typename IndexTy>
1091 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1092                                           unsigned NumIdx) {
1093   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1094   if (!PTy) return 0;   // Type isn't a pointer type!
1095   const Type *Agg = PTy->getElementType();
1096
1097   // Handle the special case of the empty set index set, which is always valid.
1098   if (NumIdx == 0)
1099     return Agg;
1100   
1101   // If there is at least one index, the top level type must be sized, otherwise
1102   // it cannot be 'stepped over'.  We explicitly allow abstract types (those
1103   // that contain opaque types) under the assumption that it will be resolved to
1104   // a sane type later.
1105   if (!Agg->isSized() && !Agg->isAbstract())
1106     return 0;
1107
1108   unsigned CurIdx = 1;
1109   for (; CurIdx != NumIdx; ++CurIdx) {
1110     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1111     if (!CT || isa<PointerType>(CT)) return 0;
1112     IndexTy Index = Idxs[CurIdx];
1113     if (!CT->indexValid(Index)) return 0;
1114     Agg = CT->getTypeAtIndex(Index);
1115
1116     // If the new type forwards to another type, then it is in the middle
1117     // of being refined to another type (and hence, may have dropped all
1118     // references to what it was using before).  So, use the new forwarded
1119     // type.
1120     if (const Type *Ty = Agg->getForwardedType())
1121       Agg = Ty;
1122   }
1123   return CurIdx == NumIdx ? Agg : 0;
1124 }
1125
1126 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1127                                               Value* const *Idxs,
1128                                               unsigned NumIdx) {
1129   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1130 }
1131
1132 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1133                                               uint64_t const *Idxs,
1134                                               unsigned NumIdx) {
1135   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1136 }
1137
1138 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1139   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1140   if (!PTy) return 0;   // Type isn't a pointer type!
1141
1142   // Check the pointer index.
1143   if (!PTy->indexValid(Idx)) return 0;
1144
1145   return PTy->getElementType();
1146 }
1147
1148
1149 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1150 /// zeros.  If so, the result pointer and the first operand have the same
1151 /// value, just potentially different types.
1152 bool GetElementPtrInst::hasAllZeroIndices() const {
1153   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1154     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1155       if (!CI->isZero()) return false;
1156     } else {
1157       return false;
1158     }
1159   }
1160   return true;
1161 }
1162
1163 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1164 /// constant integers.  If so, the result pointer and the first operand have
1165 /// a constant offset between them.
1166 bool GetElementPtrInst::hasAllConstantIndices() const {
1167   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1168     if (!isa<ConstantInt>(getOperand(i)))
1169       return false;
1170   }
1171   return true;
1172 }
1173
1174
1175 //===----------------------------------------------------------------------===//
1176 //                           ExtractElementInst Implementation
1177 //===----------------------------------------------------------------------===//
1178
1179 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1180                                        const Twine &Name,
1181                                        Instruction *InsertBef)
1182   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1183                 ExtractElement,
1184                 OperandTraits<ExtractElementInst>::op_begin(this),
1185                 2, InsertBef) {
1186   assert(isValidOperands(Val, Index) &&
1187          "Invalid extractelement instruction operands!");
1188   Op<0>() = Val;
1189   Op<1>() = Index;
1190   setName(Name);
1191 }
1192
1193 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1194                                        const Twine &Name,
1195                                        BasicBlock *InsertAE)
1196   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1197                 ExtractElement,
1198                 OperandTraits<ExtractElementInst>::op_begin(this),
1199                 2, InsertAE) {
1200   assert(isValidOperands(Val, Index) &&
1201          "Invalid extractelement instruction operands!");
1202
1203   Op<0>() = Val;
1204   Op<1>() = Index;
1205   setName(Name);
1206 }
1207
1208
1209 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1210   if (!isa<VectorType>(Val->getType()) ||
1211       Index->getType() != Type::getInt32Ty(Val->getContext()))
1212     return false;
1213   return true;
1214 }
1215
1216
1217 //===----------------------------------------------------------------------===//
1218 //                           InsertElementInst Implementation
1219 //===----------------------------------------------------------------------===//
1220
1221 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1222                                      const Twine &Name,
1223                                      Instruction *InsertBef)
1224   : Instruction(Vec->getType(), InsertElement,
1225                 OperandTraits<InsertElementInst>::op_begin(this),
1226                 3, InsertBef) {
1227   assert(isValidOperands(Vec, Elt, Index) &&
1228          "Invalid insertelement instruction operands!");
1229   Op<0>() = Vec;
1230   Op<1>() = Elt;
1231   Op<2>() = Index;
1232   setName(Name);
1233 }
1234
1235 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1236                                      const Twine &Name,
1237                                      BasicBlock *InsertAE)
1238   : Instruction(Vec->getType(), InsertElement,
1239                 OperandTraits<InsertElementInst>::op_begin(this),
1240                 3, InsertAE) {
1241   assert(isValidOperands(Vec, Elt, Index) &&
1242          "Invalid insertelement instruction operands!");
1243
1244   Op<0>() = Vec;
1245   Op<1>() = Elt;
1246   Op<2>() = Index;
1247   setName(Name);
1248 }
1249
1250 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1251                                         const Value *Index) {
1252   if (!isa<VectorType>(Vec->getType()))
1253     return false;   // First operand of insertelement must be vector type.
1254   
1255   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1256     return false;// Second operand of insertelement must be vector element type.
1257     
1258   if (Index->getType() != Type::getInt32Ty(Vec->getContext()))
1259     return false;  // Third operand of insertelement must be i32.
1260   return true;
1261 }
1262
1263
1264 //===----------------------------------------------------------------------===//
1265 //                      ShuffleVectorInst Implementation
1266 //===----------------------------------------------------------------------===//
1267
1268 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1269                                      const Twine &Name,
1270                                      Instruction *InsertBefore)
1271 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1272                 cast<VectorType>(Mask->getType())->getNumElements()),
1273               ShuffleVector,
1274               OperandTraits<ShuffleVectorInst>::op_begin(this),
1275               OperandTraits<ShuffleVectorInst>::operands(this),
1276               InsertBefore) {
1277   assert(isValidOperands(V1, V2, Mask) &&
1278          "Invalid shuffle vector instruction operands!");
1279   Op<0>() = V1;
1280   Op<1>() = V2;
1281   Op<2>() = Mask;
1282   setName(Name);
1283 }
1284
1285 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1286                                      const Twine &Name,
1287                                      BasicBlock *InsertAtEnd)
1288 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1289                 cast<VectorType>(Mask->getType())->getNumElements()),
1290               ShuffleVector,
1291               OperandTraits<ShuffleVectorInst>::op_begin(this),
1292               OperandTraits<ShuffleVectorInst>::operands(this),
1293               InsertAtEnd) {
1294   assert(isValidOperands(V1, V2, Mask) &&
1295          "Invalid shuffle vector instruction operands!");
1296
1297   Op<0>() = V1;
1298   Op<1>() = V2;
1299   Op<2>() = Mask;
1300   setName(Name);
1301 }
1302
1303 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1304                                         const Value *Mask) {
1305   if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1306     return false;
1307   
1308   const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1309   if (!isa<Constant>(Mask) || MaskTy == 0 ||
1310       MaskTy->getElementType() != Type::getInt32Ty(V1->getContext()))
1311     return false;
1312   return true;
1313 }
1314
1315 /// getMaskValue - Return the index from the shuffle mask for the specified
1316 /// output result.  This is either -1 if the element is undef or a number less
1317 /// than 2*numelements.
1318 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1319   const Constant *Mask = cast<Constant>(getOperand(2));
1320   if (isa<UndefValue>(Mask)) return -1;
1321   if (isa<ConstantAggregateZero>(Mask)) return 0;
1322   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1323   assert(i < MaskCV->getNumOperands() && "Index out of range");
1324
1325   if (isa<UndefValue>(MaskCV->getOperand(i)))
1326     return -1;
1327   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1328 }
1329
1330 //===----------------------------------------------------------------------===//
1331 //                             InsertValueInst Class
1332 //===----------------------------------------------------------------------===//
1333
1334 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 
1335                            unsigned NumIdx, const Twine &Name) {
1336   assert(NumOperands == 2 && "NumOperands not initialized?");
1337   Op<0>() = Agg;
1338   Op<1>() = Val;
1339
1340   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1341   setName(Name);
1342 }
1343
1344 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 
1345                            const Twine &Name) {
1346   assert(NumOperands == 2 && "NumOperands not initialized?");
1347   Op<0>() = Agg;
1348   Op<1>() = Val;
1349
1350   Indices.push_back(Idx);
1351   setName(Name);
1352 }
1353
1354 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1355   : Instruction(IVI.getType(), InsertValue,
1356                 OperandTraits<InsertValueInst>::op_begin(this), 2),
1357     Indices(IVI.Indices) {
1358   Op<0>() = IVI.getOperand(0);
1359   Op<1>() = IVI.getOperand(1);
1360   SubclassOptionalData = IVI.SubclassOptionalData;
1361 }
1362
1363 InsertValueInst::InsertValueInst(Value *Agg,
1364                                  Value *Val,
1365                                  unsigned Idx, 
1366                                  const Twine &Name,
1367                                  Instruction *InsertBefore)
1368   : Instruction(Agg->getType(), InsertValue,
1369                 OperandTraits<InsertValueInst>::op_begin(this),
1370                 2, InsertBefore) {
1371   init(Agg, Val, Idx, Name);
1372 }
1373
1374 InsertValueInst::InsertValueInst(Value *Agg,
1375                                  Value *Val,
1376                                  unsigned Idx, 
1377                                  const Twine &Name,
1378                                  BasicBlock *InsertAtEnd)
1379   : Instruction(Agg->getType(), InsertValue,
1380                 OperandTraits<InsertValueInst>::op_begin(this),
1381                 2, InsertAtEnd) {
1382   init(Agg, Val, Idx, Name);
1383 }
1384
1385 //===----------------------------------------------------------------------===//
1386 //                             ExtractValueInst Class
1387 //===----------------------------------------------------------------------===//
1388
1389 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1390                             const Twine &Name) {
1391   assert(NumOperands == 1 && "NumOperands not initialized?");
1392
1393   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1394   setName(Name);
1395 }
1396
1397 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1398   assert(NumOperands == 1 && "NumOperands not initialized?");
1399
1400   Indices.push_back(Idx);
1401   setName(Name);
1402 }
1403
1404 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1405   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1406     Indices(EVI.Indices) {
1407   SubclassOptionalData = EVI.SubclassOptionalData;
1408 }
1409
1410 // getIndexedType - Returns the type of the element that would be extracted
1411 // with an extractvalue instruction with the specified parameters.
1412 //
1413 // A null type is returned if the indices are invalid for the specified
1414 // pointer type.
1415 //
1416 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1417                                              const unsigned *Idxs,
1418                                              unsigned NumIdx) {
1419   unsigned CurIdx = 0;
1420   for (; CurIdx != NumIdx; ++CurIdx) {
1421     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1422     if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1423     unsigned Index = Idxs[CurIdx];
1424     if (!CT->indexValid(Index)) return 0;
1425     Agg = CT->getTypeAtIndex(Index);
1426
1427     // If the new type forwards to another type, then it is in the middle
1428     // of being refined to another type (and hence, may have dropped all
1429     // references to what it was using before).  So, use the new forwarded
1430     // type.
1431     if (const Type *Ty = Agg->getForwardedType())
1432       Agg = Ty;
1433   }
1434   return CurIdx == NumIdx ? Agg : 0;
1435 }
1436
1437 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1438                                              unsigned Idx) {
1439   return getIndexedType(Agg, &Idx, 1);
1440 }
1441
1442 //===----------------------------------------------------------------------===//
1443 //                             BinaryOperator Class
1444 //===----------------------------------------------------------------------===//
1445
1446 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1447 /// type is floating-point, to help provide compatibility with an older API.
1448 ///
1449 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1450                                              const Type *Ty) {
1451   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1452   if (Ty->isFPOrFPVector()) {
1453     if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1454     else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1455     else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1456   }
1457   return iType;
1458 }
1459
1460 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1461                                const Type *Ty, const Twine &Name,
1462                                Instruction *InsertBefore)
1463   : Instruction(Ty, AdjustIType(iType, Ty),
1464                 OperandTraits<BinaryOperator>::op_begin(this),
1465                 OperandTraits<BinaryOperator>::operands(this),
1466                 InsertBefore) {
1467   Op<0>() = S1;
1468   Op<1>() = S2;
1469   init(AdjustIType(iType, Ty));
1470   setName(Name);
1471 }
1472
1473 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1474                                const Type *Ty, const Twine &Name,
1475                                BasicBlock *InsertAtEnd)
1476   : Instruction(Ty, AdjustIType(iType, Ty),
1477                 OperandTraits<BinaryOperator>::op_begin(this),
1478                 OperandTraits<BinaryOperator>::operands(this),
1479                 InsertAtEnd) {
1480   Op<0>() = S1;
1481   Op<1>() = S2;
1482   init(AdjustIType(iType, Ty));
1483   setName(Name);
1484 }
1485
1486
1487 void BinaryOperator::init(BinaryOps iType) {
1488   Value *LHS = getOperand(0), *RHS = getOperand(1);
1489   LHS = LHS; RHS = RHS; // Silence warnings.
1490   assert(LHS->getType() == RHS->getType() &&
1491          "Binary operator operand types must match!");
1492 #ifndef NDEBUG
1493   switch (iType) {
1494   case Add: case Sub:
1495   case Mul:
1496     assert(getType() == LHS->getType() &&
1497            "Arithmetic operation should return same type as operands!");
1498     assert(getType()->isIntOrIntVector() &&
1499            "Tried to create an integer operation on a non-integer type!");
1500     break;
1501   case FAdd: case FSub:
1502   case FMul:
1503     assert(getType() == LHS->getType() &&
1504            "Arithmetic operation should return same type as operands!");
1505     assert(getType()->isFPOrFPVector() &&
1506            "Tried to create a floating-point operation on a "
1507            "non-floating-point type!");
1508     break;
1509   case UDiv: 
1510   case SDiv: 
1511     assert(getType() == LHS->getType() &&
1512            "Arithmetic operation should return same type as operands!");
1513     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1514             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1515            "Incorrect operand type (not integer) for S/UDIV");
1516     break;
1517   case FDiv:
1518     assert(getType() == LHS->getType() &&
1519            "Arithmetic operation should return same type as operands!");
1520     assert(getType()->isFPOrFPVector() &&
1521            "Incorrect operand type (not floating point) for FDIV");
1522     break;
1523   case URem: 
1524   case SRem: 
1525     assert(getType() == LHS->getType() &&
1526            "Arithmetic operation should return same type as operands!");
1527     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1528             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1529            "Incorrect operand type (not integer) for S/UREM");
1530     break;
1531   case FRem:
1532     assert(getType() == LHS->getType() &&
1533            "Arithmetic operation should return same type as operands!");
1534     assert(getType()->isFPOrFPVector() &&
1535            "Incorrect operand type (not floating point) for FREM");
1536     break;
1537   case Shl:
1538   case LShr:
1539   case AShr:
1540     assert(getType() == LHS->getType() &&
1541            "Shift operation should return same type as operands!");
1542     assert((getType()->isInteger() ||
1543             (isa<VectorType>(getType()) && 
1544              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1545            "Tried to create a shift operation on a non-integral type!");
1546     break;
1547   case And: case Or:
1548   case Xor:
1549     assert(getType() == LHS->getType() &&
1550            "Logical operation should return same type as operands!");
1551     assert((getType()->isInteger() ||
1552             (isa<VectorType>(getType()) && 
1553              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1554            "Tried to create a logical operation on a non-integral type!");
1555     break;
1556   default:
1557     break;
1558   }
1559 #endif
1560 }
1561
1562 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1563                                        const Twine &Name,
1564                                        Instruction *InsertBefore) {
1565   assert(S1->getType() == S2->getType() &&
1566          "Cannot create binary operator with two operands of differing type!");
1567   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1568 }
1569
1570 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1571                                        const Twine &Name,
1572                                        BasicBlock *InsertAtEnd) {
1573   BinaryOperator *Res = Create(Op, S1, S2, Name);
1574   InsertAtEnd->getInstList().push_back(Res);
1575   return Res;
1576 }
1577
1578 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1579                                           Instruction *InsertBefore) {
1580   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1581   return new BinaryOperator(Instruction::Sub,
1582                             zero, Op,
1583                             Op->getType(), Name, InsertBefore);
1584 }
1585
1586 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1587                                           BasicBlock *InsertAtEnd) {
1588   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1589   return new BinaryOperator(Instruction::Sub,
1590                             zero, Op,
1591                             Op->getType(), Name, InsertAtEnd);
1592 }
1593
1594 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1595                                            Instruction *InsertBefore) {
1596   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1597   return new BinaryOperator(Instruction::FSub,
1598                             zero, Op,
1599                             Op->getType(), Name, InsertBefore);
1600 }
1601
1602 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1603                                            BasicBlock *InsertAtEnd) {
1604   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1605   return new BinaryOperator(Instruction::FSub,
1606                             zero, Op,
1607                             Op->getType(), Name, InsertAtEnd);
1608 }
1609
1610 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1611                                           Instruction *InsertBefore) {
1612   Constant *C;
1613   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1614     C = Constant::getAllOnesValue(PTy->getElementType());
1615     C = ConstantVector::get(
1616                               std::vector<Constant*>(PTy->getNumElements(), C));
1617   } else {
1618     C = Constant::getAllOnesValue(Op->getType());
1619   }
1620   
1621   return new BinaryOperator(Instruction::Xor, Op, C,
1622                             Op->getType(), Name, InsertBefore);
1623 }
1624
1625 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1626                                           BasicBlock *InsertAtEnd) {
1627   Constant *AllOnes;
1628   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1629     // Create a vector of all ones values.
1630     Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1631     AllOnes = ConstantVector::get(
1632                             std::vector<Constant*>(PTy->getNumElements(), Elt));
1633   } else {
1634     AllOnes = Constant::getAllOnesValue(Op->getType());
1635   }
1636   
1637   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1638                             Op->getType(), Name, InsertAtEnd);
1639 }
1640
1641
1642 // isConstantAllOnes - Helper function for several functions below
1643 static inline bool isConstantAllOnes(const Value *V) {
1644   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1645     return CI->isAllOnesValue();
1646   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1647     return CV->isAllOnesValue();
1648   return false;
1649 }
1650
1651 bool BinaryOperator::isNeg(const Value *V) {
1652   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1653     if (Bop->getOpcode() == Instruction::Sub)
1654       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1655         return C->isNegativeZeroValue();
1656   return false;
1657 }
1658
1659 bool BinaryOperator::isFNeg(const Value *V) {
1660   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1661     if (Bop->getOpcode() == Instruction::FSub)
1662       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1663       return C->isNegativeZeroValue();
1664   return false;
1665 }
1666
1667 bool BinaryOperator::isNot(const Value *V) {
1668   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1669     return (Bop->getOpcode() == Instruction::Xor &&
1670             (isConstantAllOnes(Bop->getOperand(1)) ||
1671              isConstantAllOnes(Bop->getOperand(0))));
1672   return false;
1673 }
1674
1675 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1676   return cast<BinaryOperator>(BinOp)->getOperand(1);
1677 }
1678
1679 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1680   return getNegArgument(const_cast<Value*>(BinOp));
1681 }
1682
1683 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1684   return cast<BinaryOperator>(BinOp)->getOperand(1);
1685 }
1686
1687 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1688   return getFNegArgument(const_cast<Value*>(BinOp));
1689 }
1690
1691 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1692   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1693   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1694   Value *Op0 = BO->getOperand(0);
1695   Value *Op1 = BO->getOperand(1);
1696   if (isConstantAllOnes(Op0)) return Op1;
1697
1698   assert(isConstantAllOnes(Op1));
1699   return Op0;
1700 }
1701
1702 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1703   return getNotArgument(const_cast<Value*>(BinOp));
1704 }
1705
1706
1707 // swapOperands - Exchange the two operands to this instruction.  This
1708 // instruction is safe to use on any binary instruction and does not
1709 // modify the semantics of the instruction.  If the instruction is
1710 // order dependent (SetLT f.e.) the opcode is changed.
1711 //
1712 bool BinaryOperator::swapOperands() {
1713   if (!isCommutative())
1714     return true; // Can't commute operands
1715   Op<0>().swap(Op<1>());
1716   return false;
1717 }
1718
1719 //===----------------------------------------------------------------------===//
1720 //                                CastInst Class
1721 //===----------------------------------------------------------------------===//
1722
1723 // Just determine if this cast only deals with integral->integral conversion.
1724 bool CastInst::isIntegerCast() const {
1725   switch (getOpcode()) {
1726     default: return false;
1727     case Instruction::ZExt:
1728     case Instruction::SExt:
1729     case Instruction::Trunc:
1730       return true;
1731     case Instruction::BitCast:
1732       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1733   }
1734 }
1735
1736 bool CastInst::isLosslessCast() const {
1737   // Only BitCast can be lossless, exit fast if we're not BitCast
1738   if (getOpcode() != Instruction::BitCast)
1739     return false;
1740
1741   // Identity cast is always lossless
1742   const Type* SrcTy = getOperand(0)->getType();
1743   const Type* DstTy = getType();
1744   if (SrcTy == DstTy)
1745     return true;
1746   
1747   // Pointer to pointer is always lossless.
1748   if (isa<PointerType>(SrcTy))
1749     return isa<PointerType>(DstTy);
1750   return false;  // Other types have no identity values
1751 }
1752
1753 /// This function determines if the CastInst does not require any bits to be
1754 /// changed in order to effect the cast. Essentially, it identifies cases where
1755 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
1756 /// example, the following are all no-op casts:
1757 /// # bitcast i32* %x to i8*
1758 /// # bitcast <2 x i32> %x to <4 x i16> 
1759 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
1760 /// @brief Determine if a cast is a no-op.
1761 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1762   switch (getOpcode()) {
1763     default:
1764       assert(!"Invalid CastOp");
1765     case Instruction::Trunc:
1766     case Instruction::ZExt:
1767     case Instruction::SExt: 
1768     case Instruction::FPTrunc:
1769     case Instruction::FPExt:
1770     case Instruction::UIToFP:
1771     case Instruction::SIToFP:
1772     case Instruction::FPToUI:
1773     case Instruction::FPToSI:
1774       return false; // These always modify bits
1775     case Instruction::BitCast:
1776       return true;  // BitCast never modifies bits.
1777     case Instruction::PtrToInt:
1778       return IntPtrTy->getScalarSizeInBits() ==
1779              getType()->getScalarSizeInBits();
1780     case Instruction::IntToPtr:
1781       return IntPtrTy->getScalarSizeInBits() ==
1782              getOperand(0)->getType()->getScalarSizeInBits();
1783   }
1784 }
1785
1786 /// This function determines if a pair of casts can be eliminated and what 
1787 /// opcode should be used in the elimination. This assumes that there are two 
1788 /// instructions like this:
1789 /// *  %F = firstOpcode SrcTy %x to MidTy
1790 /// *  %S = secondOpcode MidTy %F to DstTy
1791 /// The function returns a resultOpcode so these two casts can be replaced with:
1792 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
1793 /// If no such cast is permited, the function returns 0.
1794 unsigned CastInst::isEliminableCastPair(
1795   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1796   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1797 {
1798   // Define the 144 possibilities for these two cast instructions. The values
1799   // in this matrix determine what to do in a given situation and select the
1800   // case in the switch below.  The rows correspond to firstOp, the columns 
1801   // correspond to secondOp.  In looking at the table below, keep in  mind
1802   // the following cast properties:
1803   //
1804   //          Size Compare       Source               Destination
1805   // Operator  Src ? Size   Type       Sign         Type       Sign
1806   // -------- ------------ -------------------   ---------------------
1807   // TRUNC         >       Integer      Any        Integral     Any
1808   // ZEXT          <       Integral   Unsigned     Integer      Any
1809   // SEXT          <       Integral    Signed      Integer      Any
1810   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
1811   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
1812   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
1813   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
1814   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
1815   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
1816   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
1817   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
1818   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
1819   //
1820   // NOTE: some transforms are safe, but we consider them to be non-profitable.
1821   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1822   // into "fptoui double to i64", but this loses information about the range
1823   // of the produced value (we no longer know the top-part is all zeros). 
1824   // Further this conversion is often much more expensive for typical hardware,
1825   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
1826   // same reason.
1827   const unsigned numCastOps = 
1828     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1829   static const uint8_t CastResults[numCastOps][numCastOps] = {
1830     // T        F  F  U  S  F  F  P  I  B   -+
1831     // R  Z  S  P  P  I  I  T  P  2  N  T    |
1832     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
1833     // N  X  X  U  S  F  F  N  X  N  2  V    |
1834     // C  T  T  I  I  P  P  C  T  T  P  T   -+
1835     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
1836     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
1837     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
1838     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
1839     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
1840     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
1841     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
1842     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
1843     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
1844     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
1845     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
1846     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
1847   };
1848
1849   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1850                             [secondOp-Instruction::CastOpsBegin];
1851   switch (ElimCase) {
1852     case 0: 
1853       // categorically disallowed
1854       return 0;
1855     case 1: 
1856       // allowed, use first cast's opcode
1857       return firstOp;
1858     case 2: 
1859       // allowed, use second cast's opcode
1860       return secondOp;
1861     case 3: 
1862       // no-op cast in second op implies firstOp as long as the DestTy 
1863       // is integer
1864       if (DstTy->isInteger())
1865         return firstOp;
1866       return 0;
1867     case 4:
1868       // no-op cast in second op implies firstOp as long as the DestTy
1869       // is floating point
1870       if (DstTy->isFloatingPoint())
1871         return firstOp;
1872       return 0;
1873     case 5: 
1874       // no-op cast in first op implies secondOp as long as the SrcTy
1875       // is an integer
1876       if (SrcTy->isInteger())
1877         return secondOp;
1878       return 0;
1879     case 6:
1880       // no-op cast in first op implies secondOp as long as the SrcTy
1881       // is a floating point
1882       if (SrcTy->isFloatingPoint())
1883         return secondOp;
1884       return 0;
1885     case 7: { 
1886       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1887       if (!IntPtrTy)
1888         return 0;
1889       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1890       unsigned MidSize = MidTy->getScalarSizeInBits();
1891       if (MidSize >= PtrSize)
1892         return Instruction::BitCast;
1893       return 0;
1894     }
1895     case 8: {
1896       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
1897       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
1898       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
1899       unsigned SrcSize = SrcTy->getScalarSizeInBits();
1900       unsigned DstSize = DstTy->getScalarSizeInBits();
1901       if (SrcSize == DstSize)
1902         return Instruction::BitCast;
1903       else if (SrcSize < DstSize)
1904         return firstOp;
1905       return secondOp;
1906     }
1907     case 9: // zext, sext -> zext, because sext can't sign extend after zext
1908       return Instruction::ZExt;
1909     case 10:
1910       // fpext followed by ftrunc is allowed if the bit size returned to is
1911       // the same as the original, in which case its just a bitcast
1912       if (SrcTy == DstTy)
1913         return Instruction::BitCast;
1914       return 0; // If the types are not the same we can't eliminate it.
1915     case 11:
1916       // bitcast followed by ptrtoint is allowed as long as the bitcast
1917       // is a pointer to pointer cast.
1918       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1919         return secondOp;
1920       return 0;
1921     case 12:
1922       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
1923       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1924         return firstOp;
1925       return 0;
1926     case 13: {
1927       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1928       if (!IntPtrTy)
1929         return 0;
1930       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1931       unsigned SrcSize = SrcTy->getScalarSizeInBits();
1932       unsigned DstSize = DstTy->getScalarSizeInBits();
1933       if (SrcSize <= PtrSize && SrcSize == DstSize)
1934         return Instruction::BitCast;
1935       return 0;
1936     }
1937     case 99: 
1938       // cast combination can't happen (error in input). This is for all cases
1939       // where the MidTy is not the same for the two cast instructions.
1940       assert(!"Invalid Cast Combination");
1941       return 0;
1942     default:
1943       assert(!"Error in CastResults table!!!");
1944       return 0;
1945   }
1946   return 0;
1947 }
1948
1949 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 
1950   const Twine &Name, Instruction *InsertBefore) {
1951   // Construct and return the appropriate CastInst subclass
1952   switch (op) {
1953     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
1954     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
1955     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
1956     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
1957     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
1958     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
1959     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
1960     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
1961     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
1962     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1963     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1964     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
1965     default:
1966       assert(!"Invalid opcode provided");
1967   }
1968   return 0;
1969 }
1970
1971 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1972   const Twine &Name, BasicBlock *InsertAtEnd) {
1973   // Construct and return the appropriate CastInst subclass
1974   switch (op) {
1975     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
1976     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
1977     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
1978     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
1979     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
1980     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
1981     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
1982     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
1983     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
1984     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1985     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1986     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
1987     default:
1988       assert(!"Invalid opcode provided");
1989   }
1990   return 0;
1991 }
1992
1993 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
1994                                         const Twine &Name,
1995                                         Instruction *InsertBefore) {
1996   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1997     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1998   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1999 }
2000
2001 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
2002                                         const Twine &Name,
2003                                         BasicBlock *InsertAtEnd) {
2004   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2005     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2006   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2007 }
2008
2009 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
2010                                         const Twine &Name,
2011                                         Instruction *InsertBefore) {
2012   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2013     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2014   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2015 }
2016
2017 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
2018                                         const Twine &Name,
2019                                         BasicBlock *InsertAtEnd) {
2020   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2021     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2022   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2023 }
2024
2025 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2026                                          const Twine &Name,
2027                                          Instruction *InsertBefore) {
2028   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2029     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2030   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2031 }
2032
2033 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2034                                          const Twine &Name, 
2035                                          BasicBlock *InsertAtEnd) {
2036   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2037     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2038   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2039 }
2040
2041 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2042                                       const Twine &Name,
2043                                       BasicBlock *InsertAtEnd) {
2044   assert(isa<PointerType>(S->getType()) && "Invalid cast");
2045   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2046          "Invalid cast");
2047
2048   if (Ty->isInteger())
2049     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2050   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2051 }
2052
2053 /// @brief Create a BitCast or a PtrToInt cast instruction
2054 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 
2055                                       const Twine &Name, 
2056                                       Instruction *InsertBefore) {
2057   assert(isa<PointerType>(S->getType()) && "Invalid cast");
2058   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2059          "Invalid cast");
2060
2061   if (Ty->isInteger())
2062     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2063   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2064 }
2065
2066 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
2067                                       bool isSigned, const Twine &Name,
2068                                       Instruction *InsertBefore) {
2069   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2070   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2071   unsigned DstBits = Ty->getScalarSizeInBits();
2072   Instruction::CastOps opcode =
2073     (SrcBits == DstBits ? Instruction::BitCast :
2074      (SrcBits > DstBits ? Instruction::Trunc :
2075       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2076   return Create(opcode, C, Ty, Name, InsertBefore);
2077 }
2078
2079 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
2080                                       bool isSigned, const Twine &Name,
2081                                       BasicBlock *InsertAtEnd) {
2082   assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2083          "Invalid cast");
2084   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2085   unsigned DstBits = Ty->getScalarSizeInBits();
2086   Instruction::CastOps opcode =
2087     (SrcBits == DstBits ? Instruction::BitCast :
2088      (SrcBits > DstBits ? Instruction::Trunc :
2089       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2090   return Create(opcode, C, Ty, Name, InsertAtEnd);
2091 }
2092
2093 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
2094                                  const Twine &Name, 
2095                                  Instruction *InsertBefore) {
2096   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2097          "Invalid cast");
2098   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2099   unsigned DstBits = Ty->getScalarSizeInBits();
2100   Instruction::CastOps opcode =
2101     (SrcBits == DstBits ? Instruction::BitCast :
2102      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2103   return Create(opcode, C, Ty, Name, InsertBefore);
2104 }
2105
2106 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
2107                                  const Twine &Name, 
2108                                  BasicBlock *InsertAtEnd) {
2109   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2110          "Invalid cast");
2111   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2112   unsigned DstBits = Ty->getScalarSizeInBits();
2113   Instruction::CastOps opcode =
2114     (SrcBits == DstBits ? Instruction::BitCast :
2115      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2116   return Create(opcode, C, Ty, Name, InsertAtEnd);
2117 }
2118
2119 // Check whether it is valid to call getCastOpcode for these types.
2120 // This routine must be kept in sync with getCastOpcode.
2121 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2122   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2123     return false;
2124
2125   if (SrcTy == DestTy)
2126     return true;
2127
2128   // Get the bit sizes, we'll need these
2129   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
2130   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2131
2132   // Run through the possibilities ...
2133   if (DestTy->isInteger()) {                   // Casting to integral
2134     if (SrcTy->isInteger()) {                  // Casting from integral
2135         return true;
2136     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
2137       return true;
2138     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2139                                                // Casting from vector
2140       return DestBits == PTy->getBitWidth();
2141     } else {                                   // Casting from something else
2142       return isa<PointerType>(SrcTy);
2143     }
2144   } else if (DestTy->isFloatingPoint()) {      // Casting to floating pt
2145     if (SrcTy->isInteger()) {                  // Casting from integral
2146       return true;
2147     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
2148       return true;
2149     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2150                                                // Casting from vector
2151       return DestBits == PTy->getBitWidth();
2152     } else {                                   // Casting from something else
2153       return false;
2154     }
2155   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2156                                                 // Casting to vector
2157     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2158                                                 // Casting from vector
2159       return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2160     } else {                                    // Casting from something else
2161       return DestPTy->getBitWidth() == SrcBits;
2162     }
2163   } else if (isa<PointerType>(DestTy)) {        // Casting to pointer
2164     if (isa<PointerType>(SrcTy)) {              // Casting from pointer
2165       return true;
2166     } else if (SrcTy->isInteger()) {            // Casting from integral
2167       return true;
2168     } else {                                    // Casting from something else
2169       return false;
2170     }
2171   } else {                                      // Casting to something else
2172     return false;
2173   }
2174 }
2175
2176 // Provide a way to get a "cast" where the cast opcode is inferred from the 
2177 // types and size of the operand. This, basically, is a parallel of the 
2178 // logic in the castIsValid function below.  This axiom should hold:
2179 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2180 // should not assert in castIsValid. In other words, this produces a "correct"
2181 // casting opcode for the arguments passed to it.
2182 // This routine must be kept in sync with isCastable.
2183 Instruction::CastOps
2184 CastInst::getCastOpcode(
2185   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2186   // Get the bit sizes, we'll need these
2187   const Type *SrcTy = Src->getType();
2188   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
2189   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2190
2191   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2192          "Only first class types are castable!");
2193
2194   // Run through the possibilities ...
2195   if (DestTy->isInteger()) {                       // Casting to integral
2196     if (SrcTy->isInteger()) {                      // Casting from integral
2197       if (DestBits < SrcBits)
2198         return Trunc;                               // int -> smaller int
2199       else if (DestBits > SrcBits) {                // its an extension
2200         if (SrcIsSigned)
2201           return SExt;                              // signed -> SEXT
2202         else
2203           return ZExt;                              // unsigned -> ZEXT
2204       } else {
2205         return BitCast;                             // Same size, No-op cast
2206       }
2207     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
2208       if (DestIsSigned) 
2209         return FPToSI;                              // FP -> sint
2210       else
2211         return FPToUI;                              // FP -> uint 
2212     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2213       assert(DestBits == PTy->getBitWidth() &&
2214                "Casting vector to integer of different width");
2215       PTy = NULL;
2216       return BitCast;                             // Same size, no-op cast
2217     } else {
2218       assert(isa<PointerType>(SrcTy) &&
2219              "Casting from a value that is not first-class type");
2220       return PtrToInt;                              // ptr -> int
2221     }
2222   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
2223     if (SrcTy->isInteger()) {                      // Casting from integral
2224       if (SrcIsSigned)
2225         return SIToFP;                              // sint -> FP
2226       else
2227         return UIToFP;                              // uint -> FP
2228     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
2229       if (DestBits < SrcBits) {
2230         return FPTrunc;                             // FP -> smaller FP
2231       } else if (DestBits > SrcBits) {
2232         return FPExt;                               // FP -> larger FP
2233       } else  {
2234         return BitCast;                             // same size, no-op cast
2235       }
2236     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2237       assert(DestBits == PTy->getBitWidth() &&
2238              "Casting vector to floating point of different width");
2239       PTy = NULL;
2240       return BitCast;                             // same size, no-op cast
2241     } else {
2242       llvm_unreachable("Casting pointer or non-first class to float");
2243     }
2244   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2245     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2246       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2247              "Casting vector to vector of different widths");
2248       SrcPTy = NULL;
2249       return BitCast;                             // vector -> vector
2250     } else if (DestPTy->getBitWidth() == SrcBits) {
2251       return BitCast;                               // float/int -> vector
2252     } else {
2253       assert(!"Illegal cast to vector (wrong type or size)");
2254     }
2255   } else if (isa<PointerType>(DestTy)) {
2256     if (isa<PointerType>(SrcTy)) {
2257       return BitCast;                               // ptr -> ptr
2258     } else if (SrcTy->isInteger()) {
2259       return IntToPtr;                              // int -> ptr
2260     } else {
2261       assert(!"Casting pointer to other than pointer or int");
2262     }
2263   } else {
2264     assert(!"Casting to type that is not first-class");
2265   }
2266
2267   // If we fall through to here we probably hit an assertion cast above
2268   // and assertions are not turned on. Anything we return is an error, so
2269   // BitCast is as good a choice as any.
2270   return BitCast;
2271 }
2272
2273 //===----------------------------------------------------------------------===//
2274 //                    CastInst SubClass Constructors
2275 //===----------------------------------------------------------------------===//
2276
2277 /// Check that the construction parameters for a CastInst are correct. This
2278 /// could be broken out into the separate constructors but it is useful to have
2279 /// it in one place and to eliminate the redundant code for getting the sizes
2280 /// of the types involved.
2281 bool 
2282 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2283
2284   // Check for type sanity on the arguments
2285   const Type *SrcTy = S->getType();
2286   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2287     return false;
2288
2289   // Get the size of the types in bits, we'll need this later
2290   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2291   unsigned DstBitSize = DstTy->getScalarSizeInBits();
2292
2293   // Switch on the opcode provided
2294   switch (op) {
2295   default: return false; // This is an input error
2296   case Instruction::Trunc:
2297     return SrcTy->isIntOrIntVector() &&
2298            DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2299   case Instruction::ZExt:
2300     return SrcTy->isIntOrIntVector() &&
2301            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2302   case Instruction::SExt: 
2303     return SrcTy->isIntOrIntVector() &&
2304            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2305   case Instruction::FPTrunc:
2306     return SrcTy->isFPOrFPVector() &&
2307            DstTy->isFPOrFPVector() && 
2308            SrcBitSize > DstBitSize;
2309   case Instruction::FPExt:
2310     return SrcTy->isFPOrFPVector() &&
2311            DstTy->isFPOrFPVector() && 
2312            SrcBitSize < DstBitSize;
2313   case Instruction::UIToFP:
2314   case Instruction::SIToFP:
2315     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2316       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2317         return SVTy->getElementType()->isIntOrIntVector() &&
2318                DVTy->getElementType()->isFPOrFPVector() &&
2319                SVTy->getNumElements() == DVTy->getNumElements();
2320       }
2321     }
2322     return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2323   case Instruction::FPToUI:
2324   case Instruction::FPToSI:
2325     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2326       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2327         return SVTy->getElementType()->isFPOrFPVector() &&
2328                DVTy->getElementType()->isIntOrIntVector() &&
2329                SVTy->getNumElements() == DVTy->getNumElements();
2330       }
2331     }
2332     return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2333   case Instruction::PtrToInt:
2334     return isa<PointerType>(SrcTy) && DstTy->isInteger();
2335   case Instruction::IntToPtr:
2336     return SrcTy->isInteger() && isa<PointerType>(DstTy);
2337   case Instruction::BitCast:
2338     // BitCast implies a no-op cast of type only. No bits change.
2339     // However, you can't cast pointers to anything but pointers.
2340     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2341       return false;
2342
2343     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2344     // these cases, the cast is okay if the source and destination bit widths
2345     // are identical.
2346     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2347   }
2348 }
2349
2350 TruncInst::TruncInst(
2351   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2352 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2353   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2354 }
2355
2356 TruncInst::TruncInst(
2357   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2358 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2359   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2360 }
2361
2362 ZExtInst::ZExtInst(
2363   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2364 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2365   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2366 }
2367
2368 ZExtInst::ZExtInst(
2369   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2370 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2371   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2372 }
2373 SExtInst::SExtInst(
2374   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2375 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2376   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2377 }
2378
2379 SExtInst::SExtInst(
2380   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2381 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2382   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2383 }
2384
2385 FPTruncInst::FPTruncInst(
2386   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2387 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2388   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2389 }
2390
2391 FPTruncInst::FPTruncInst(
2392   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2393 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2394   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2395 }
2396
2397 FPExtInst::FPExtInst(
2398   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2399 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2400   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2401 }
2402
2403 FPExtInst::FPExtInst(
2404   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2405 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2406   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2407 }
2408
2409 UIToFPInst::UIToFPInst(
2410   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2411 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2412   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2413 }
2414
2415 UIToFPInst::UIToFPInst(
2416   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2417 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2418   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2419 }
2420
2421 SIToFPInst::SIToFPInst(
2422   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2423 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2424   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2425 }
2426
2427 SIToFPInst::SIToFPInst(
2428   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2429 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2430   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2431 }
2432
2433 FPToUIInst::FPToUIInst(
2434   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2435 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2436   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2437 }
2438
2439 FPToUIInst::FPToUIInst(
2440   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2441 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2442   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2443 }
2444
2445 FPToSIInst::FPToSIInst(
2446   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2447 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2448   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2449 }
2450
2451 FPToSIInst::FPToSIInst(
2452   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2453 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2454   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2455 }
2456
2457 PtrToIntInst::PtrToIntInst(
2458   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2459 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2460   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2461 }
2462
2463 PtrToIntInst::PtrToIntInst(
2464   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2465 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2466   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2467 }
2468
2469 IntToPtrInst::IntToPtrInst(
2470   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2471 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2472   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2473 }
2474
2475 IntToPtrInst::IntToPtrInst(
2476   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2477 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2478   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2479 }
2480
2481 BitCastInst::BitCastInst(
2482   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2483 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2484   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2485 }
2486
2487 BitCastInst::BitCastInst(
2488   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2489 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2490   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2491 }
2492
2493 //===----------------------------------------------------------------------===//
2494 //                               CmpInst Classes
2495 //===----------------------------------------------------------------------===//
2496
2497 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2498                  Value *LHS, Value *RHS, const Twine &Name,
2499                  Instruction *InsertBefore)
2500   : Instruction(ty, op,
2501                 OperandTraits<CmpInst>::op_begin(this),
2502                 OperandTraits<CmpInst>::operands(this),
2503                 InsertBefore) {
2504     Op<0>() = LHS;
2505     Op<1>() = RHS;
2506   SubclassData = predicate;
2507   setName(Name);
2508 }
2509
2510 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2511                  Value *LHS, Value *RHS, const Twine &Name,
2512                  BasicBlock *InsertAtEnd)
2513   : Instruction(ty, op,
2514                 OperandTraits<CmpInst>::op_begin(this),
2515                 OperandTraits<CmpInst>::operands(this),
2516                 InsertAtEnd) {
2517   Op<0>() = LHS;
2518   Op<1>() = RHS;
2519   SubclassData = predicate;
2520   setName(Name);
2521 }
2522
2523 CmpInst *
2524 CmpInst::Create(OtherOps Op, unsigned short predicate,
2525                 Value *S1, Value *S2, 
2526                 const Twine &Name, Instruction *InsertBefore) {
2527   if (Op == Instruction::ICmp) {
2528     if (InsertBefore)
2529       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2530                           S1, S2, Name);
2531     else
2532       return new ICmpInst(CmpInst::Predicate(predicate),
2533                           S1, S2, Name);
2534   }
2535   
2536   if (InsertBefore)
2537     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2538                         S1, S2, Name);
2539   else
2540     return new FCmpInst(CmpInst::Predicate(predicate),
2541                         S1, S2, Name);
2542 }
2543
2544 CmpInst *
2545 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2546                 const Twine &Name, BasicBlock *InsertAtEnd) {
2547   if (Op == Instruction::ICmp) {
2548     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2549                         S1, S2, Name);
2550   }
2551   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2552                       S1, S2, Name);
2553 }
2554
2555 void CmpInst::swapOperands() {
2556   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2557     IC->swapOperands();
2558   else
2559     cast<FCmpInst>(this)->swapOperands();
2560 }
2561
2562 bool CmpInst::isCommutative() {
2563   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2564     return IC->isCommutative();
2565   return cast<FCmpInst>(this)->isCommutative();
2566 }
2567
2568 bool CmpInst::isEquality() {
2569   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2570     return IC->isEquality();
2571   return cast<FCmpInst>(this)->isEquality();
2572 }
2573
2574
2575 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2576   switch (pred) {
2577     default: assert(!"Unknown cmp predicate!");
2578     case ICMP_EQ: return ICMP_NE;
2579     case ICMP_NE: return ICMP_EQ;
2580     case ICMP_UGT: return ICMP_ULE;
2581     case ICMP_ULT: return ICMP_UGE;
2582     case ICMP_UGE: return ICMP_ULT;
2583     case ICMP_ULE: return ICMP_UGT;
2584     case ICMP_SGT: return ICMP_SLE;
2585     case ICMP_SLT: return ICMP_SGE;
2586     case ICMP_SGE: return ICMP_SLT;
2587     case ICMP_SLE: return ICMP_SGT;
2588
2589     case FCMP_OEQ: return FCMP_UNE;
2590     case FCMP_ONE: return FCMP_UEQ;
2591     case FCMP_OGT: return FCMP_ULE;
2592     case FCMP_OLT: return FCMP_UGE;
2593     case FCMP_OGE: return FCMP_ULT;
2594     case FCMP_OLE: return FCMP_UGT;
2595     case FCMP_UEQ: return FCMP_ONE;
2596     case FCMP_UNE: return FCMP_OEQ;
2597     case FCMP_UGT: return FCMP_OLE;
2598     case FCMP_ULT: return FCMP_OGE;
2599     case FCMP_UGE: return FCMP_OLT;
2600     case FCMP_ULE: return FCMP_OGT;
2601     case FCMP_ORD: return FCMP_UNO;
2602     case FCMP_UNO: return FCMP_ORD;
2603     case FCMP_TRUE: return FCMP_FALSE;
2604     case FCMP_FALSE: return FCMP_TRUE;
2605   }
2606 }
2607
2608 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2609   switch (pred) {
2610     default: assert(! "Unknown icmp predicate!");
2611     case ICMP_EQ: case ICMP_NE: 
2612     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2613        return pred;
2614     case ICMP_UGT: return ICMP_SGT;
2615     case ICMP_ULT: return ICMP_SLT;
2616     case ICMP_UGE: return ICMP_SGE;
2617     case ICMP_ULE: return ICMP_SLE;
2618   }
2619 }
2620
2621 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2622   switch (pred) {
2623     default: assert(! "Unknown icmp predicate!");
2624     case ICMP_EQ: case ICMP_NE: 
2625     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
2626        return pred;
2627     case ICMP_SGT: return ICMP_UGT;
2628     case ICMP_SLT: return ICMP_ULT;
2629     case ICMP_SGE: return ICMP_UGE;
2630     case ICMP_SLE: return ICMP_ULE;
2631   }
2632 }
2633
2634 bool ICmpInst::isSignedPredicate(Predicate pred) {
2635   switch (pred) {
2636     default: assert(! "Unknown icmp predicate!");
2637     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2638       return true;
2639     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
2640     case ICMP_UGE: case ICMP_ULE:
2641       return false;
2642   }
2643 }
2644
2645 /// Initialize a set of values that all satisfy the condition with C.
2646 ///
2647 ConstantRange 
2648 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2649   APInt Lower(C);
2650   APInt Upper(C);
2651   uint32_t BitWidth = C.getBitWidth();
2652   switch (pred) {
2653   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2654   case ICmpInst::ICMP_EQ: Upper++; break;
2655   case ICmpInst::ICMP_NE: Lower++; break;
2656   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2657   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2658   case ICmpInst::ICMP_UGT: 
2659     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2660     break;
2661   case ICmpInst::ICMP_SGT:
2662     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2663     break;
2664   case ICmpInst::ICMP_ULE: 
2665     Lower = APInt::getMinValue(BitWidth); Upper++; 
2666     break;
2667   case ICmpInst::ICMP_SLE: 
2668     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2669     break;
2670   case ICmpInst::ICMP_UGE:
2671     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2672     break;
2673   case ICmpInst::ICMP_SGE:
2674     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2675     break;
2676   }
2677   return ConstantRange(Lower, Upper);
2678 }
2679
2680 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2681   switch (pred) {
2682     default: assert(!"Unknown cmp predicate!");
2683     case ICMP_EQ: case ICMP_NE:
2684       return pred;
2685     case ICMP_SGT: return ICMP_SLT;
2686     case ICMP_SLT: return ICMP_SGT;
2687     case ICMP_SGE: return ICMP_SLE;
2688     case ICMP_SLE: return ICMP_SGE;
2689     case ICMP_UGT: return ICMP_ULT;
2690     case ICMP_ULT: return ICMP_UGT;
2691     case ICMP_UGE: return ICMP_ULE;
2692     case ICMP_ULE: return ICMP_UGE;
2693   
2694     case FCMP_FALSE: case FCMP_TRUE:
2695     case FCMP_OEQ: case FCMP_ONE:
2696     case FCMP_UEQ: case FCMP_UNE:
2697     case FCMP_ORD: case FCMP_UNO:
2698       return pred;
2699     case FCMP_OGT: return FCMP_OLT;
2700     case FCMP_OLT: return FCMP_OGT;
2701     case FCMP_OGE: return FCMP_OLE;
2702     case FCMP_OLE: return FCMP_OGE;
2703     case FCMP_UGT: return FCMP_ULT;
2704     case FCMP_ULT: return FCMP_UGT;
2705     case FCMP_UGE: return FCMP_ULE;
2706     case FCMP_ULE: return FCMP_UGE;
2707   }
2708 }
2709
2710 bool CmpInst::isUnsigned(unsigned short predicate) {
2711   switch (predicate) {
2712     default: return false;
2713     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
2714     case ICmpInst::ICMP_UGE: return true;
2715   }
2716 }
2717
2718 bool CmpInst::isSigned(unsigned short predicate){
2719   switch (predicate) {
2720     default: return false;
2721     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
2722     case ICmpInst::ICMP_SGE: return true;
2723   }
2724 }
2725
2726 bool CmpInst::isOrdered(unsigned short predicate) {
2727   switch (predicate) {
2728     default: return false;
2729     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
2730     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
2731     case FCmpInst::FCMP_ORD: return true;
2732   }
2733 }
2734       
2735 bool CmpInst::isUnordered(unsigned short predicate) {
2736   switch (predicate) {
2737     default: return false;
2738     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
2739     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
2740     case FCmpInst::FCMP_UNO: return true;
2741   }
2742 }
2743
2744 //===----------------------------------------------------------------------===//
2745 //                        SwitchInst Implementation
2746 //===----------------------------------------------------------------------===//
2747
2748 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2749   assert(Value && Default);
2750   ReservedSpace = 2+NumCases*2;
2751   NumOperands = 2;
2752   OperandList = allocHungoffUses(ReservedSpace);
2753
2754   OperandList[0] = Value;
2755   OperandList[1] = Default;
2756 }
2757
2758 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2759 /// switch on and a default destination.  The number of additional cases can
2760 /// be specified here to make memory allocation more efficient.  This
2761 /// constructor can also autoinsert before another instruction.
2762 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2763                        Instruction *InsertBefore)
2764   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2765                    0, 0, InsertBefore) {
2766   init(Value, Default, NumCases);
2767 }
2768
2769 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2770 /// switch on and a default destination.  The number of additional cases can
2771 /// be specified here to make memory allocation more efficient.  This
2772 /// constructor also autoinserts at the end of the specified BasicBlock.
2773 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2774                        BasicBlock *InsertAtEnd)
2775   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2776                    0, 0, InsertAtEnd) {
2777   init(Value, Default, NumCases);
2778 }
2779
2780 SwitchInst::SwitchInst(const SwitchInst &SI)
2781   : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
2782                    allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2783   Use *OL = OperandList, *InOL = SI.OperandList;
2784   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2785     OL[i] = InOL[i];
2786     OL[i+1] = InOL[i+1];
2787   }
2788   SubclassOptionalData = SI.SubclassOptionalData;
2789 }
2790
2791 SwitchInst::~SwitchInst() {
2792   dropHungoffUses(OperandList);
2793 }
2794
2795
2796 /// addCase - Add an entry to the switch instruction...
2797 ///
2798 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2799   unsigned OpNo = NumOperands;
2800   if (OpNo+2 > ReservedSpace)
2801     resizeOperands(0);  // Get more space!
2802   // Initialize some new operands.
2803   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2804   NumOperands = OpNo+2;
2805   OperandList[OpNo] = OnVal;
2806   OperandList[OpNo+1] = Dest;
2807 }
2808
2809 /// removeCase - This method removes the specified successor from the switch
2810 /// instruction.  Note that this cannot be used to remove the default
2811 /// destination (successor #0).
2812 ///
2813 void SwitchInst::removeCase(unsigned idx) {
2814   assert(idx != 0 && "Cannot remove the default case!");
2815   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2816
2817   unsigned NumOps = getNumOperands();
2818   Use *OL = OperandList;
2819
2820   // Move everything after this operand down.
2821   //
2822   // FIXME: we could just swap with the end of the list, then erase.  However,
2823   // client might not expect this to happen.  The code as it is thrashes the
2824   // use/def lists, which is kinda lame.
2825   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2826     OL[i-2] = OL[i];
2827     OL[i-2+1] = OL[i+1];
2828   }
2829
2830   // Nuke the last value.
2831   OL[NumOps-2].set(0);
2832   OL[NumOps-2+1].set(0);
2833   NumOperands = NumOps-2;
2834 }
2835
2836 /// resizeOperands - resize operands - This adjusts the length of the operands
2837 /// list according to the following behavior:
2838 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
2839 ///      of operation.  This grows the number of ops by 3 times.
2840 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
2841 ///   3. If NumOps == NumOperands, trim the reserved space.
2842 ///
2843 void SwitchInst::resizeOperands(unsigned NumOps) {
2844   unsigned e = getNumOperands();
2845   if (NumOps == 0) {
2846     NumOps = e*3;
2847   } else if (NumOps*2 > NumOperands) {
2848     // No resize needed.
2849     if (ReservedSpace >= NumOps) return;
2850   } else if (NumOps == NumOperands) {
2851     if (ReservedSpace == NumOps) return;
2852   } else {
2853     return;
2854   }
2855
2856   ReservedSpace = NumOps;
2857   Use *NewOps = allocHungoffUses(NumOps);
2858   Use *OldOps = OperandList;
2859   for (unsigned i = 0; i != e; ++i) {
2860       NewOps[i] = OldOps[i];
2861   }
2862   OperandList = NewOps;
2863   if (OldOps) Use::zap(OldOps, OldOps + e, true);
2864 }
2865
2866
2867 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2868   return getSuccessor(idx);
2869 }
2870 unsigned SwitchInst::getNumSuccessorsV() const {
2871   return getNumSuccessors();
2872 }
2873 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2874   setSuccessor(idx, B);
2875 }
2876
2877 // Define these methods here so vtables don't get emitted into every translation
2878 // unit that uses these classes.
2879
2880 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2881   GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this);
2882   New->SubclassOptionalData = SubclassOptionalData;
2883   return New;
2884 }
2885
2886 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2887   BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>());
2888   New->SubclassOptionalData = SubclassOptionalData;
2889   return New;
2890 }
2891
2892 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2893   FCmpInst *New = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2894   New->SubclassOptionalData = SubclassOptionalData;
2895   return New;
2896 }
2897 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2898   ICmpInst *New = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2899   New->SubclassOptionalData = SubclassOptionalData;
2900   return New;
2901 }
2902
2903 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2904   ExtractValueInst *New = new ExtractValueInst(*this);
2905   New->SubclassOptionalData = SubclassOptionalData;
2906   return New;
2907 }
2908 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2909   InsertValueInst *New = new InsertValueInst(*this);
2910   New->SubclassOptionalData = SubclassOptionalData;
2911   return New;
2912 }
2913
2914 MallocInst *MallocInst::clone(LLVMContext&) const {
2915   MallocInst *New = new MallocInst(getAllocatedType(),
2916                                    (Value*)getOperand(0),
2917                                    getAlignment());
2918   New->SubclassOptionalData = SubclassOptionalData;
2919   return New;
2920 }
2921
2922 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2923   AllocaInst *New = new AllocaInst(getAllocatedType(),
2924                                    (Value*)getOperand(0),
2925                                    getAlignment());
2926   New->SubclassOptionalData = SubclassOptionalData;
2927   return New;
2928 }
2929
2930 FreeInst *FreeInst::clone(LLVMContext&) const {
2931   FreeInst *New = new FreeInst(getOperand(0));
2932   New->SubclassOptionalData = SubclassOptionalData;
2933   return New;
2934 }
2935
2936 LoadInst *LoadInst::clone(LLVMContext&) const {
2937   LoadInst *New = new LoadInst(getOperand(0),
2938                                Twine(), isVolatile(),
2939                                getAlignment());
2940   New->SubclassOptionalData = SubclassOptionalData;
2941   return New;
2942 }
2943
2944 StoreInst *StoreInst::clone(LLVMContext&) const {
2945   StoreInst *New = new StoreInst(getOperand(0), getOperand(1),
2946                                  isVolatile(), getAlignment());
2947   New->SubclassOptionalData = SubclassOptionalData;
2948   return New;
2949 }
2950
2951 TruncInst *TruncInst::clone(LLVMContext&) const {
2952   TruncInst *New = new TruncInst(getOperand(0), getType());
2953   New->SubclassOptionalData = SubclassOptionalData;
2954   return New;
2955 }
2956
2957 ZExtInst *ZExtInst::clone(LLVMContext&) const {
2958   ZExtInst *New = new ZExtInst(getOperand(0), getType());
2959   New->SubclassOptionalData = SubclassOptionalData;
2960   return New;
2961 }
2962
2963 SExtInst *SExtInst::clone(LLVMContext&) const {
2964   SExtInst *New = new SExtInst(getOperand(0), getType());
2965   New->SubclassOptionalData = SubclassOptionalData;
2966   return New;
2967 }
2968
2969 FPTruncInst *FPTruncInst::clone(LLVMContext&) const {
2970   FPTruncInst *New = new FPTruncInst(getOperand(0), getType());
2971   New->SubclassOptionalData = SubclassOptionalData;
2972   return New;
2973 }
2974
2975 FPExtInst *FPExtInst::clone(LLVMContext&) const {
2976   FPExtInst *New = new FPExtInst(getOperand(0), getType());
2977   New->SubclassOptionalData = SubclassOptionalData;
2978   return New;
2979 }
2980
2981 UIToFPInst *UIToFPInst::clone(LLVMContext&) const {
2982   UIToFPInst *New = new UIToFPInst(getOperand(0), getType());
2983   New->SubclassOptionalData = SubclassOptionalData;
2984   return New;
2985 }
2986
2987 SIToFPInst *SIToFPInst::clone(LLVMContext&) const {
2988   SIToFPInst *New = new SIToFPInst(getOperand(0), getType());
2989   New->SubclassOptionalData = SubclassOptionalData;
2990   return New;
2991 }
2992
2993 FPToUIInst *FPToUIInst::clone(LLVMContext&) const {
2994   FPToUIInst *New = new FPToUIInst(getOperand(0), getType());
2995   New->SubclassOptionalData = SubclassOptionalData;
2996   return New;
2997 }
2998
2999 FPToSIInst *FPToSIInst::clone(LLVMContext&) const {
3000   FPToSIInst *New = new FPToSIInst(getOperand(0), getType());
3001   New->SubclassOptionalData = SubclassOptionalData;
3002   return New;
3003 }
3004
3005 PtrToIntInst *PtrToIntInst::clone(LLVMContext&) const {
3006   PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType());
3007   New->SubclassOptionalData = SubclassOptionalData;
3008   return New;
3009 }
3010
3011 IntToPtrInst *IntToPtrInst::clone(LLVMContext&) const {
3012   IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType());
3013   New->SubclassOptionalData = SubclassOptionalData;
3014   return New;
3015 }
3016
3017 BitCastInst *BitCastInst::clone(LLVMContext&) const {
3018   BitCastInst *New = new BitCastInst(getOperand(0), getType());
3019   New->SubclassOptionalData = SubclassOptionalData;
3020   return New;
3021 }
3022
3023 CallInst *CallInst::clone(LLVMContext&) const {
3024   CallInst *New = new(getNumOperands()) CallInst(*this);
3025   New->SubclassOptionalData = SubclassOptionalData;
3026   return New;
3027 }
3028
3029 SelectInst *SelectInst::clone(LLVMContext&) const {
3030   SelectInst *New = SelectInst::Create(getOperand(0),
3031                                        getOperand(1),
3032                                        getOperand(2));
3033   New->SubclassOptionalData = SubclassOptionalData;
3034   return New;
3035 }
3036
3037 VAArgInst *VAArgInst::clone(LLVMContext&) const {
3038   VAArgInst *New = new VAArgInst(getOperand(0), getType());
3039   New->SubclassOptionalData = SubclassOptionalData;
3040   return New;
3041 }
3042
3043 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
3044   ExtractElementInst *New = ExtractElementInst::Create(getOperand(0),
3045                                                        getOperand(1));
3046   New->SubclassOptionalData = SubclassOptionalData;
3047   return New;
3048 }
3049
3050 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
3051   InsertElementInst *New = InsertElementInst::Create(getOperand(0),
3052                                                      getOperand(1),
3053                                                      getOperand(2));
3054   New->SubclassOptionalData = SubclassOptionalData;
3055   return New;
3056 }
3057
3058 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
3059   ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0),
3060                                                  getOperand(1),
3061                                                  getOperand(2));
3062   New->SubclassOptionalData = SubclassOptionalData;
3063   return New;
3064 }
3065
3066 PHINode *PHINode::clone(LLVMContext&) const {
3067   PHINode *New = new PHINode(*this);
3068   New->SubclassOptionalData = SubclassOptionalData;
3069   return New;
3070 }
3071
3072 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3073   ReturnInst *New = new(getNumOperands()) ReturnInst(*this);
3074   New->SubclassOptionalData = SubclassOptionalData;
3075   return New;
3076 }
3077
3078 BranchInst *BranchInst::clone(LLVMContext&) const {
3079   unsigned Ops(getNumOperands());
3080   BranchInst *New = new(Ops, Ops == 1) BranchInst(*this);
3081   New->SubclassOptionalData = SubclassOptionalData;
3082   return New;
3083 }
3084
3085 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3086   SwitchInst *New = new SwitchInst(*this);
3087   New->SubclassOptionalData = SubclassOptionalData;
3088   return New;
3089 }
3090
3091 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3092   InvokeInst *New = new(getNumOperands()) InvokeInst(*this);
3093   New->SubclassOptionalData = SubclassOptionalData;
3094   return New;
3095 }
3096
3097 UnwindInst *UnwindInst::clone(LLVMContext &C) const {
3098   UnwindInst *New = new UnwindInst(C);
3099   New->SubclassOptionalData = SubclassOptionalData;
3100   return New;
3101 }
3102
3103 UnreachableInst *UnreachableInst::clone(LLVMContext &C) const {
3104   UnreachableInst *New = new UnreachableInst(C);
3105   New->SubclassOptionalData = SubclassOptionalData;
3106   return New;
3107 }