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