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