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