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