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