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