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