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