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