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