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