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