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