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