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