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