Invoke instructions do not dominate all successors
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
21 using namespace llvm;
22
23 unsigned CallSite::getCallingConv() const {
24   if (CallInst *CI = dyn_cast<CallInst>(I))
25     return CI->getCallingConv();
26   else
27     return cast<InvokeInst>(I)->getCallingConv();
28 }
29 void CallSite::setCallingConv(unsigned CC) {
30   if (CallInst *CI = dyn_cast<CallInst>(I))
31     CI->setCallingConv(CC);
32   else
33     cast<InvokeInst>(I)->setCallingConv(CC);
34 }
35
36
37 //===----------------------------------------------------------------------===//
38 //                            TerminatorInst Class
39 //===----------------------------------------------------------------------===//
40
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42                                Use *Ops, unsigned NumOps, Instruction *IB)
43   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
44 }
45
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47                                Use *Ops, unsigned NumOps, BasicBlock *IAE)
48   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
49 }
50
51
52
53 //===----------------------------------------------------------------------===//
54 //                               PHINode Class
55 //===----------------------------------------------------------------------===//
56
57 PHINode::PHINode(const PHINode &PN)
58   : Instruction(PN.getType(), Instruction::PHI,
59                 new Use[PN.getNumOperands()], PN.getNumOperands()),
60     ReservedSpace(PN.getNumOperands()) {
61   Use *OL = OperandList;
62   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
63     OL[i].init(PN.getOperand(i), this);
64     OL[i+1].init(PN.getOperand(i+1), this);
65   }
66 }
67
68 PHINode::~PHINode() {
69   delete [] OperandList;
70 }
71
72 // removeIncomingValue - Remove an incoming value.  This is useful if a
73 // predecessor basic block is deleted.
74 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
75   unsigned NumOps = getNumOperands();
76   Use *OL = OperandList;
77   assert(Idx*2 < NumOps && "BB not in PHI node!");
78   Value *Removed = OL[Idx*2];
79
80   // Move everything after this operand down.
81   //
82   // FIXME: we could just swap with the end of the list, then erase.  However,
83   // client might not expect this to happen.  The code as it is thrashes the
84   // use/def lists, which is kinda lame.
85   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
86     OL[i-2] = OL[i];
87     OL[i-2+1] = OL[i+1];
88   }
89
90   // Nuke the last value.
91   OL[NumOps-2].set(0);
92   OL[NumOps-2+1].set(0);
93   NumOperands = NumOps-2;
94
95   // If the PHI node is dead, because it has zero entries, nuke it now.
96   if (NumOps == 2 && DeletePHIIfEmpty) {
97     // If anyone is using this PHI, make them use a dummy value instead...
98     replaceAllUsesWith(UndefValue::get(getType()));
99     eraseFromParent();
100   }
101   return Removed;
102 }
103
104 /// resizeOperands - resize operands - This adjusts the length of the operands
105 /// list according to the following behavior:
106 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
107 ///      of operation.  This grows the number of ops by 1.5 times.
108 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
109 ///   3. If NumOps == NumOperands, trim the reserved space.
110 ///
111 void PHINode::resizeOperands(unsigned NumOps) {
112   if (NumOps == 0) {
113     NumOps = (getNumOperands())*3/2;
114     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
115   } else if (NumOps*2 > NumOperands) {
116     // No resize needed.
117     if (ReservedSpace >= NumOps) return;
118   } else if (NumOps == NumOperands) {
119     if (ReservedSpace == NumOps) return;
120   } else {
121     return;
122   }
123
124   ReservedSpace = NumOps;
125   Use *NewOps = new Use[NumOps];
126   Use *OldOps = OperandList;
127   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
128       NewOps[i].init(OldOps[i], this);
129       OldOps[i].set(0);
130   }
131   delete [] OldOps;
132   OperandList = NewOps;
133 }
134
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
137 ///
138 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
139   // If the PHI node only has one incoming value, eliminate the PHI node...
140   if (getNumIncomingValues() == 1)
141     return getIncomingValue(0);
142   
143   // Otherwise if all of the incoming values are the same for the PHI, replace
144   // the PHI node with the incoming value.
145   //
146   Value *InVal = 0;
147   bool HasUndefInput = false;
148   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
149     if (isa<UndefValue>(getIncomingValue(i)))
150       HasUndefInput = true;
151     else if (getIncomingValue(i) != this)  // Not the PHI node itself...
152       if (InVal && getIncomingValue(i) != InVal)
153         return 0;  // Not the same, bail out.
154       else
155         InVal = getIncomingValue(i);
156   
157   // The only case that could cause InVal to be null is if we have a PHI node
158   // that only has entries for itself.  In this case, there is no entry into the
159   // loop, so kill the PHI.
160   //
161   if (InVal == 0) InVal = UndefValue::get(getType());
162   
163   // If we have a PHI node like phi(X, undef, X), where X is defined by some
164   // instruction, we cannot always return X as the result of the PHI node.  Only
165   // do this if X is not an instruction (thus it must dominate the PHI block),
166   // or if the client is prepared to deal with this possibility.
167   if (HasUndefInput && !AllowNonDominatingInstruction)
168     if (Instruction *IV = dyn_cast<Instruction>(InVal))
169       // If it's in the entry block, it dominates everything.
170       if (IV->getParent() != &IV->getParent()->getParent()->front() ||
171           isa<InvokeInst>(IV))
172         return 0;   // Cannot guarantee that InVal dominates this PHINode.
173
174   // All of the incoming values are the same, return the value now.
175   return InVal;
176 }
177
178
179 //===----------------------------------------------------------------------===//
180 //                        CallInst Implementation
181 //===----------------------------------------------------------------------===//
182
183 CallInst::~CallInst() {
184   delete [] OperandList;
185 }
186
187 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
188   NumOperands = Params.size()+1;
189   Use *OL = OperandList = new Use[Params.size()+1];
190   OL[0].init(Func, this);
191
192   const FunctionType *FTy =
193     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
194
195   assert((Params.size() == FTy->getNumParams() ||
196           (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
197          "Calling a function with bad signature");
198   for (unsigned i = 0, e = Params.size(); i != e; ++i)
199     OL[i+1].init(Params[i], this);
200 }
201
202 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
203   NumOperands = 3;
204   Use *OL = OperandList = new Use[3];
205   OL[0].init(Func, this);
206   OL[1].init(Actual1, this);
207   OL[2].init(Actual2, this);
208
209   const FunctionType *FTy =
210     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
211
212   assert((FTy->getNumParams() == 2 ||
213           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
214          "Calling a function with bad signature");
215 }
216
217 void CallInst::init(Value *Func, Value *Actual) {
218   NumOperands = 2;
219   Use *OL = OperandList = new Use[2];
220   OL[0].init(Func, this);
221   OL[1].init(Actual, this);
222
223   const FunctionType *FTy =
224     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
225
226   assert((FTy->getNumParams() == 1 ||
227           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
228          "Calling a function with bad signature");
229 }
230
231 void CallInst::init(Value *Func) {
232   NumOperands = 1;
233   Use *OL = OperandList = new Use[1];
234   OL[0].init(Func, this);
235
236   const FunctionType *MTy =
237     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
238
239   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
240 }
241
242 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
243                    const std::string &Name, Instruction *InsertBefore)
244   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
245                                  ->getElementType())->getReturnType(),
246                 Instruction::Call, 0, 0, Name, InsertBefore) {
247   init(Func, Params);
248 }
249
250 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
251                    const std::string &Name, BasicBlock *InsertAtEnd)
252   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
253                                  ->getElementType())->getReturnType(),
254                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
255   init(Func, Params);
256 }
257
258 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
259                    const std::string &Name, Instruction  *InsertBefore)
260   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
261                                    ->getElementType())->getReturnType(),
262                 Instruction::Call, 0, 0, Name, InsertBefore) {
263   init(Func, Actual1, Actual2);
264 }
265
266 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
267                    const std::string &Name, BasicBlock  *InsertAtEnd)
268   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269                                    ->getElementType())->getReturnType(),
270                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
271   init(Func, Actual1, Actual2);
272 }
273
274 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
275                    Instruction  *InsertBefore)
276   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
277                                    ->getElementType())->getReturnType(),
278                 Instruction::Call, 0, 0, Name, InsertBefore) {
279   init(Func, Actual);
280 }
281
282 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
283                    BasicBlock  *InsertAtEnd)
284   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
285                                    ->getElementType())->getReturnType(),
286                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
287   init(Func, Actual);
288 }
289
290 CallInst::CallInst(Value *Func, const std::string &Name,
291                    Instruction *InsertBefore)
292   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
293                                    ->getElementType())->getReturnType(),
294                 Instruction::Call, 0, 0, Name, InsertBefore) {
295   init(Func);
296 }
297
298 CallInst::CallInst(Value *Func, const std::string &Name,
299                    BasicBlock *InsertAtEnd)
300   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
301                                    ->getElementType())->getReturnType(),
302                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
303   init(Func);
304 }
305
306 CallInst::CallInst(const CallInst &CI)
307   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
308                 CI.getNumOperands()) {
309   SubclassData = CI.SubclassData;
310   Use *OL = OperandList;
311   Use *InOL = CI.OperandList;
312   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
313     OL[i].init(InOL[i], this);
314 }
315
316
317 //===----------------------------------------------------------------------===//
318 //                        InvokeInst Implementation
319 //===----------------------------------------------------------------------===//
320
321 InvokeInst::~InvokeInst() {
322   delete [] OperandList;
323 }
324
325 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
326                       const std::vector<Value*> &Params) {
327   NumOperands = 3+Params.size();
328   Use *OL = OperandList = new Use[3+Params.size()];
329   OL[0].init(Fn, this);
330   OL[1].init(IfNormal, this);
331   OL[2].init(IfException, this);
332   const FunctionType *FTy =
333     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
334
335   assert((Params.size() == FTy->getNumParams()) ||
336          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
337          "Calling a function with bad signature");
338
339   for (unsigned i = 0, e = Params.size(); i != e; i++)
340     OL[i+3].init(Params[i], this);
341 }
342
343 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
344                        BasicBlock *IfException,
345                        const std::vector<Value*> &Params,
346                        const std::string &Name, Instruction *InsertBefore)
347   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
348                                     ->getElementType())->getReturnType(),
349                    Instruction::Invoke, 0, 0, Name, InsertBefore) {
350   init(Fn, IfNormal, IfException, Params);
351 }
352
353 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
354                        BasicBlock *IfException,
355                        const std::vector<Value*> &Params,
356                        const std::string &Name, BasicBlock *InsertAtEnd)
357   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
358                                     ->getElementType())->getReturnType(),
359                    Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
360   init(Fn, IfNormal, IfException, Params);
361 }
362
363 InvokeInst::InvokeInst(const InvokeInst &II)
364   : TerminatorInst(II.getType(), Instruction::Invoke,
365                    new Use[II.getNumOperands()], II.getNumOperands()) {
366   SubclassData = II.SubclassData;
367   Use *OL = OperandList, *InOL = II.OperandList;
368   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
369     OL[i].init(InOL[i], this);
370 }
371
372 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
373   return getSuccessor(idx);
374 }
375 unsigned InvokeInst::getNumSuccessorsV() const {
376   return getNumSuccessors();
377 }
378 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
379   return setSuccessor(idx, B);
380 }
381
382
383 //===----------------------------------------------------------------------===//
384 //                        ReturnInst Implementation
385 //===----------------------------------------------------------------------===//
386
387 void ReturnInst::init(Value *retVal) {
388   if (retVal && retVal->getType() != Type::VoidTy) {
389     assert(!isa<BasicBlock>(retVal) &&
390            "Cannot return basic block.  Probably using the incorrect ctor");
391     NumOperands = 1;
392     RetVal.init(retVal, this);
393   }
394 }
395
396 unsigned ReturnInst::getNumSuccessorsV() const {
397   return getNumSuccessors();
398 }
399
400 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
401 // emit the vtable for the class in this translation unit.
402 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
403   assert(0 && "ReturnInst has no successors!");
404 }
405
406 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
407   assert(0 && "ReturnInst has no successors!");
408   abort();
409   return 0;
410 }
411
412
413 //===----------------------------------------------------------------------===//
414 //                        UnwindInst Implementation
415 //===----------------------------------------------------------------------===//
416
417 unsigned UnwindInst::getNumSuccessorsV() const {
418   return getNumSuccessors();
419 }
420
421 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
422   assert(0 && "UnwindInst has no successors!");
423 }
424
425 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
426   assert(0 && "UnwindInst has no successors!");
427   abort();
428   return 0;
429 }
430
431 //===----------------------------------------------------------------------===//
432 //                      UnreachableInst Implementation
433 //===----------------------------------------------------------------------===//
434
435 unsigned UnreachableInst::getNumSuccessorsV() const {
436   return getNumSuccessors();
437 }
438
439 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
440   assert(0 && "UnwindInst has no successors!");
441 }
442
443 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
444   assert(0 && "UnwindInst has no successors!");
445   abort();
446   return 0;
447 }
448
449 //===----------------------------------------------------------------------===//
450 //                        BranchInst Implementation
451 //===----------------------------------------------------------------------===//
452
453 void BranchInst::AssertOK() {
454   if (isConditional())
455     assert(getCondition()->getType() == Type::BoolTy &&
456            "May only branch on boolean predicates!");
457 }
458
459 BranchInst::BranchInst(const BranchInst &BI) :
460   TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
461   OperandList[0].init(BI.getOperand(0), this);
462   if (BI.getNumOperands() != 1) {
463     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
464     OperandList[1].init(BI.getOperand(1), this);
465     OperandList[2].init(BI.getOperand(2), this);
466   }
467 }
468
469 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
470   return getSuccessor(idx);
471 }
472 unsigned BranchInst::getNumSuccessorsV() const {
473   return getNumSuccessors();
474 }
475 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
476   setSuccessor(idx, B);
477 }
478
479
480 //===----------------------------------------------------------------------===//
481 //                        AllocationInst Implementation
482 //===----------------------------------------------------------------------===//
483
484 static Value *getAISize(Value *Amt) {
485   if (!Amt)
486     Amt = ConstantUInt::get(Type::UIntTy, 1);
487   else
488     assert(Amt->getType() == Type::UIntTy &&
489            "Malloc/Allocation array size != UIntTy!");
490   return Amt;
491 }
492
493 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
494                                const std::string &Name,
495                                Instruction *InsertBefore)
496   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
497                      Name, InsertBefore) {
498   assert(Ty != Type::VoidTy && "Cannot allocate void!");
499 }
500
501 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
502                                const std::string &Name,
503                                BasicBlock *InsertAtEnd)
504   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
505                      Name, InsertAtEnd) {
506   assert(Ty != Type::VoidTy && "Cannot allocate void!");
507 }
508
509 bool AllocationInst::isArrayAllocation() const {
510   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
511     return CUI->getValue() != 1;
512   return true;
513 }
514
515 const Type *AllocationInst::getAllocatedType() const {
516   return getType()->getElementType();
517 }
518
519 AllocaInst::AllocaInst(const AllocaInst &AI)
520   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
521                    Instruction::Alloca) {
522 }
523
524 MallocInst::MallocInst(const MallocInst &MI)
525   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
526                    Instruction::Malloc) {
527 }
528
529 //===----------------------------------------------------------------------===//
530 //                             FreeInst Implementation
531 //===----------------------------------------------------------------------===//
532
533 void FreeInst::AssertOK() {
534   assert(isa<PointerType>(getOperand(0)->getType()) &&
535          "Can not free something of nonpointer type!");
536 }
537
538 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
539   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
540   AssertOK();
541 }
542
543 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
544   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
545   AssertOK();
546 }
547
548
549 //===----------------------------------------------------------------------===//
550 //                           LoadInst Implementation
551 //===----------------------------------------------------------------------===//
552
553 void LoadInst::AssertOK() {
554   assert(isa<PointerType>(getOperand(0)->getType()) &&
555          "Ptr must have pointer type.");
556 }
557
558 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
559   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
560                      Load, Ptr, Name, InsertBef) {
561   setVolatile(false);
562   AssertOK();
563 }
564
565 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
566   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
567                      Load, Ptr, Name, InsertAE) {
568   setVolatile(false);
569   AssertOK();
570 }
571
572 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
573                    Instruction *InsertBef)
574   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
575                      Load, Ptr, Name, InsertBef) {
576   setVolatile(isVolatile);
577   AssertOK();
578 }
579
580 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
581                    BasicBlock *InsertAE)
582   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
583                      Load, Ptr, Name, InsertAE) {
584   setVolatile(isVolatile);
585   AssertOK();
586 }
587
588
589 //===----------------------------------------------------------------------===//
590 //                           StoreInst Implementation
591 //===----------------------------------------------------------------------===//
592
593 void StoreInst::AssertOK() {
594   assert(isa<PointerType>(getOperand(1)->getType()) &&
595          "Ptr must have pointer type!");
596   assert(getOperand(0)->getType() ==
597                  cast<PointerType>(getOperand(1)->getType())->getElementType()
598          && "Ptr must be a pointer to Val type!");
599 }
600
601
602 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
603   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
604   Ops[0].init(val, this);
605   Ops[1].init(addr, this);
606   setVolatile(false);
607   AssertOK();
608 }
609
610 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
611   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
612   Ops[0].init(val, this);
613   Ops[1].init(addr, this);
614   setVolatile(false);
615   AssertOK();
616 }
617
618 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
619                      Instruction *InsertBefore)
620   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
621   Ops[0].init(val, this);
622   Ops[1].init(addr, this);
623   setVolatile(isVolatile);
624   AssertOK();
625 }
626
627 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
628                      BasicBlock *InsertAtEnd)
629   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
630   Ops[0].init(val, this);
631   Ops[1].init(addr, this);
632   setVolatile(isVolatile);
633   AssertOK();
634 }
635
636 //===----------------------------------------------------------------------===//
637 //                       GetElementPtrInst Implementation
638 //===----------------------------------------------------------------------===//
639
640 // checkType - Simple wrapper function to give a better assertion failure
641 // message on bad indexes for a gep instruction.
642 //
643 static inline const Type *checkType(const Type *Ty) {
644   assert(Ty && "Invalid indices for type!");
645   return Ty;
646 }
647
648 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
649   NumOperands = 1+Idx.size();
650   Use *OL = OperandList = new Use[NumOperands];
651   OL[0].init(Ptr, this);
652
653   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
654     OL[i+1].init(Idx[i], this);
655 }
656
657 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
658   NumOperands = 3;
659   Use *OL = OperandList = new Use[3];
660   OL[0].init(Ptr, this);
661   OL[1].init(Idx0, this);
662   OL[2].init(Idx1, this);
663 }
664
665 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
666   NumOperands = 2;
667   Use *OL = OperandList = new Use[2];
668   OL[0].init(Ptr, this);
669   OL[1].init(Idx, this);
670 }
671
672 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
673                                      const std::string &Name, Instruction *InBe)
674   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
675                                                           Idx, true))),
676                 GetElementPtr, 0, 0, Name, InBe) {
677   init(Ptr, Idx);
678 }
679
680 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
681                                      const std::string &Name, BasicBlock *IAE)
682   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
683                                                           Idx, true))),
684                 GetElementPtr, 0, 0, Name, IAE) {
685   init(Ptr, Idx);
686 }
687
688 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
689                                      const std::string &Name, Instruction *InBe)
690   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
691                 GetElementPtr, 0, 0, Name, InBe) {
692   init(Ptr, Idx);
693 }
694
695 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
696                                      const std::string &Name, BasicBlock *IAE)
697   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
698                 GetElementPtr, 0, 0, Name, IAE) {
699   init(Ptr, Idx);
700 }
701
702 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
703                                      const std::string &Name, Instruction *InBe)
704   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
705                                                           Idx0, Idx1, true))),
706                 GetElementPtr, 0, 0, Name, InBe) {
707   init(Ptr, Idx0, Idx1);
708 }
709
710 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
711                                      const std::string &Name, BasicBlock *IAE)
712   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
713                                                           Idx0, Idx1, true))),
714                 GetElementPtr, 0, 0, Name, IAE) {
715   init(Ptr, Idx0, Idx1);
716 }
717
718 GetElementPtrInst::~GetElementPtrInst() {
719   delete[] OperandList;
720 }
721
722 // getIndexedType - Returns the type of the element that would be loaded with
723 // a load instruction with the specified parameters.
724 //
725 // A null type is returned if the indices are invalid for the specified
726 // pointer type.
727 //
728 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
729                                               const std::vector<Value*> &Idx,
730                                               bool AllowCompositeLeaf) {
731   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
732
733   // Handle the special case of the empty set index set...
734   if (Idx.empty())
735     if (AllowCompositeLeaf ||
736         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
737       return cast<PointerType>(Ptr)->getElementType();
738     else
739       return 0;
740
741   unsigned CurIdx = 0;
742   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
743     if (Idx.size() == CurIdx) {
744       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
745       return 0;   // Can't load a whole structure or array!?!?
746     }
747
748     Value *Index = Idx[CurIdx++];
749     if (isa<PointerType>(CT) && CurIdx != 1)
750       return 0;  // Can only index into pointer types at the first index!
751     if (!CT->indexValid(Index)) return 0;
752     Ptr = CT->getTypeAtIndex(Index);
753
754     // If the new type forwards to another type, then it is in the middle
755     // of being refined to another type (and hence, may have dropped all
756     // references to what it was using before).  So, use the new forwarded
757     // type.
758     if (const Type * Ty = Ptr->getForwardedType()) {
759       Ptr = Ty;
760     }
761   }
762   return CurIdx == Idx.size() ? Ptr : 0;
763 }
764
765 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
766                                               Value *Idx0, Value *Idx1,
767                                               bool AllowCompositeLeaf) {
768   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
769   if (!PTy) return 0;   // Type isn't a pointer type!
770
771   // Check the pointer index.
772   if (!PTy->indexValid(Idx0)) return 0;
773
774   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
775   if (!CT || !CT->indexValid(Idx1)) return 0;
776
777   const Type *ElTy = CT->getTypeAtIndex(Idx1);
778   if (AllowCompositeLeaf || ElTy->isFirstClassType())
779     return ElTy;
780   return 0;
781 }
782
783 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
784   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
785   if (!PTy) return 0;   // Type isn't a pointer type!
786
787   // Check the pointer index.
788   if (!PTy->indexValid(Idx)) return 0;
789
790   return PTy->getElementType();
791 }
792
793 //===----------------------------------------------------------------------===//
794 //                             BinaryOperator Class
795 //===----------------------------------------------------------------------===//
796
797 void BinaryOperator::init(BinaryOps iType)
798 {
799   Value *LHS = getOperand(0), *RHS = getOperand(1);
800   assert(LHS->getType() == RHS->getType() &&
801          "Binary operator operand types must match!");
802 #ifndef NDEBUG
803   switch (iType) {
804   case Add: case Sub:
805   case Mul: case Div:
806   case Rem:
807     assert(getType() == LHS->getType() &&
808            "Arithmetic operation should return same type as operands!");
809     assert((getType()->isInteger() ||
810             getType()->isFloatingPoint() ||
811             isa<PackedType>(getType()) ) &&
812           "Tried to create an arithmetic operation on a non-arithmetic type!");
813     break;
814   case And: case Or:
815   case Xor:
816     assert(getType() == LHS->getType() &&
817            "Logical operation should return same type as operands!");
818     assert(getType()->isIntegral() &&
819            "Tried to create a logical operation on a non-integral type!");
820     break;
821   case SetLT: case SetGT: case SetLE:
822   case SetGE: case SetEQ: case SetNE:
823     assert(getType() == Type::BoolTy && "Setcc must return bool!");
824   default:
825     break;
826   }
827 #endif
828 }
829
830 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
831                                        const std::string &Name,
832                                        Instruction *InsertBefore) {
833   assert(S1->getType() == S2->getType() &&
834          "Cannot create binary operator with two operands of differing type!");
835   switch (Op) {
836   // Binary comparison operators...
837   case SetLT: case SetGT: case SetLE:
838   case SetGE: case SetEQ: case SetNE:
839     return new SetCondInst(Op, S1, S2, Name, InsertBefore);
840
841   default:
842     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
843   }
844 }
845
846 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
847                                        const std::string &Name,
848                                        BasicBlock *InsertAtEnd) {
849   BinaryOperator *Res = create(Op, S1, S2, Name);
850   InsertAtEnd->getInstList().push_back(Res);
851   return Res;
852 }
853
854 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
855                                           Instruction *InsertBefore) {
856   if (!Op->getType()->isFloatingPoint())
857     return new BinaryOperator(Instruction::Sub,
858                               Constant::getNullValue(Op->getType()), Op,
859                               Op->getType(), Name, InsertBefore);
860   else
861     return new BinaryOperator(Instruction::Sub,
862                               ConstantFP::get(Op->getType(), -0.0), Op,
863                               Op->getType(), Name, InsertBefore);
864 }
865
866 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
867                                           BasicBlock *InsertAtEnd) {
868   if (!Op->getType()->isFloatingPoint())
869     return new BinaryOperator(Instruction::Sub,
870                               Constant::getNullValue(Op->getType()), Op,
871                               Op->getType(), Name, InsertAtEnd);
872   else
873     return new BinaryOperator(Instruction::Sub,
874                               ConstantFP::get(Op->getType(), -0.0), Op,
875                               Op->getType(), Name, InsertAtEnd);
876 }
877
878 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
879                                           Instruction *InsertBefore) {
880   return new BinaryOperator(Instruction::Xor, Op,
881                             ConstantIntegral::getAllOnesValue(Op->getType()),
882                             Op->getType(), Name, InsertBefore);
883 }
884
885 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
886                                           BasicBlock *InsertAtEnd) {
887   return new BinaryOperator(Instruction::Xor, Op,
888                             ConstantIntegral::getAllOnesValue(Op->getType()),
889                             Op->getType(), Name, InsertAtEnd);
890 }
891
892
893 // isConstantAllOnes - Helper function for several functions below
894 static inline bool isConstantAllOnes(const Value *V) {
895   return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
896 }
897
898 bool BinaryOperator::isNeg(const Value *V) {
899   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
900     if (Bop->getOpcode() == Instruction::Sub)
901       if (!V->getType()->isFloatingPoint())
902         return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
903       else
904         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
905   return false;
906 }
907
908 bool BinaryOperator::isNot(const Value *V) {
909   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
910     return (Bop->getOpcode() == Instruction::Xor &&
911             (isConstantAllOnes(Bop->getOperand(1)) ||
912              isConstantAllOnes(Bop->getOperand(0))));
913   return false;
914 }
915
916 Value *BinaryOperator::getNegArgument(Value *BinOp) {
917   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
918   return cast<BinaryOperator>(BinOp)->getOperand(1);
919 }
920
921 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
922   return getNegArgument(const_cast<Value*>(BinOp));
923 }
924
925 Value *BinaryOperator::getNotArgument(Value *BinOp) {
926   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
927   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
928   Value *Op0 = BO->getOperand(0);
929   Value *Op1 = BO->getOperand(1);
930   if (isConstantAllOnes(Op0)) return Op1;
931
932   assert(isConstantAllOnes(Op1));
933   return Op0;
934 }
935
936 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
937   return getNotArgument(const_cast<Value*>(BinOp));
938 }
939
940
941 // swapOperands - Exchange the two operands to this instruction.  This
942 // instruction is safe to use on any binary instruction and does not
943 // modify the semantics of the instruction.  If the instruction is
944 // order dependent (SetLT f.e.) the opcode is changed.
945 //
946 bool BinaryOperator::swapOperands() {
947   if (isCommutative())
948     ;  // If the instruction is commutative, it is safe to swap the operands
949   else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
950     /// FIXME: SetCC instructions shouldn't all have different opcodes.
951     setOpcode(SCI->getSwappedCondition());
952   else
953     return true;   // Can't commute operands
954
955   std::swap(Ops[0], Ops[1]);
956   return false;
957 }
958
959
960 //===----------------------------------------------------------------------===//
961 //                             SetCondInst Class
962 //===----------------------------------------------------------------------===//
963
964 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
965                          const std::string &Name, Instruction *InsertBefore)
966   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
967
968   // Make sure it's a valid type... getInverseCondition will assert out if not.
969   assert(getInverseCondition(Opcode));
970 }
971
972 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
973                          const std::string &Name, BasicBlock *InsertAtEnd)
974   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
975
976   // Make sure it's a valid type... getInverseCondition will assert out if not.
977   assert(getInverseCondition(Opcode));
978 }
979
980 // getInverseCondition - Return the inverse of the current condition opcode.
981 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
982 //
983 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
984   switch (Opcode) {
985   default:
986     assert(0 && "Unknown setcc opcode!");
987   case SetEQ: return SetNE;
988   case SetNE: return SetEQ;
989   case SetGT: return SetLE;
990   case SetLT: return SetGE;
991   case SetGE: return SetLT;
992   case SetLE: return SetGT;
993   }
994 }
995
996 // getSwappedCondition - Return the condition opcode that would be the result
997 // of exchanging the two operands of the setcc instruction without changing
998 // the result produced.  Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
999 //
1000 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1001   switch (Opcode) {
1002   default: assert(0 && "Unknown setcc instruction!");
1003   case SetEQ: case SetNE: return Opcode;
1004   case SetGT: return SetLT;
1005   case SetLT: return SetGT;
1006   case SetGE: return SetLE;
1007   case SetLE: return SetGE;
1008   }
1009 }
1010
1011 //===----------------------------------------------------------------------===//
1012 //                        SwitchInst Implementation
1013 //===----------------------------------------------------------------------===//
1014
1015 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1016   assert(Value && Default);
1017   ReservedSpace = 2+NumCases*2;
1018   NumOperands = 2;
1019   OperandList = new Use[ReservedSpace];
1020
1021   OperandList[0].init(Value, this);
1022   OperandList[1].init(Default, this);
1023 }
1024
1025 SwitchInst::SwitchInst(const SwitchInst &SI)
1026   : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1027                    SI.getNumOperands()) {
1028   Use *OL = OperandList, *InOL = SI.OperandList;
1029   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1030     OL[i].init(InOL[i], this);
1031     OL[i+1].init(InOL[i+1], this);
1032   }
1033 }
1034
1035 SwitchInst::~SwitchInst() {
1036   delete [] OperandList;
1037 }
1038
1039
1040 /// addCase - Add an entry to the switch instruction...
1041 ///
1042 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1043   unsigned OpNo = NumOperands;
1044   if (OpNo+2 > ReservedSpace)
1045     resizeOperands(0);  // Get more space!
1046   // Initialize some new operands.
1047   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1048   NumOperands = OpNo+2;
1049   OperandList[OpNo].init(OnVal, this);
1050   OperandList[OpNo+1].init(Dest, this);
1051 }
1052
1053 /// removeCase - This method removes the specified successor from the switch
1054 /// instruction.  Note that this cannot be used to remove the default
1055 /// destination (successor #0).
1056 ///
1057 void SwitchInst::removeCase(unsigned idx) {
1058   assert(idx != 0 && "Cannot remove the default case!");
1059   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1060
1061   unsigned NumOps = getNumOperands();
1062   Use *OL = OperandList;
1063
1064   // Move everything after this operand down.
1065   //
1066   // FIXME: we could just swap with the end of the list, then erase.  However,
1067   // client might not expect this to happen.  The code as it is thrashes the
1068   // use/def lists, which is kinda lame.
1069   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1070     OL[i-2] = OL[i];
1071     OL[i-2+1] = OL[i+1];
1072   }
1073
1074   // Nuke the last value.
1075   OL[NumOps-2].set(0);
1076   OL[NumOps-2+1].set(0);
1077   NumOperands = NumOps-2;
1078 }
1079
1080 /// resizeOperands - resize operands - This adjusts the length of the operands
1081 /// list according to the following behavior:
1082 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
1083 ///      of operation.  This grows the number of ops by 1.5 times.
1084 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
1085 ///   3. If NumOps == NumOperands, trim the reserved space.
1086 ///
1087 void SwitchInst::resizeOperands(unsigned NumOps) {
1088   if (NumOps == 0) {
1089     NumOps = getNumOperands()/2*6;
1090   } else if (NumOps*2 > NumOperands) {
1091     // No resize needed.
1092     if (ReservedSpace >= NumOps) return;
1093   } else if (NumOps == NumOperands) {
1094     if (ReservedSpace == NumOps) return;
1095   } else {
1096     return;
1097   }
1098
1099   ReservedSpace = NumOps;
1100   Use *NewOps = new Use[NumOps];
1101   Use *OldOps = OperandList;
1102   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1103       NewOps[i].init(OldOps[i], this);
1104       OldOps[i].set(0);
1105   }
1106   delete [] OldOps;
1107   OperandList = NewOps;
1108 }
1109
1110
1111 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1112   return getSuccessor(idx);
1113 }
1114 unsigned SwitchInst::getNumSuccessorsV() const {
1115   return getNumSuccessors();
1116 }
1117 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1118   setSuccessor(idx, B);
1119 }
1120
1121
1122 // Define these methods here so vtables don't get emitted into every translation
1123 // unit that uses these classes.
1124
1125 GetElementPtrInst *GetElementPtrInst::clone() const {
1126   return new GetElementPtrInst(*this);
1127 }
1128
1129 BinaryOperator *BinaryOperator::clone() const {
1130   return create(getOpcode(), Ops[0], Ops[1]);
1131 }
1132
1133 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1134 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1135 FreeInst   *FreeInst::clone()   const { return new FreeInst(getOperand(0)); }
1136 LoadInst   *LoadInst::clone()   const { return new LoadInst(*this); }
1137 StoreInst  *StoreInst::clone()  const { return new StoreInst(*this); }
1138 CastInst   *CastInst::clone()   const { return new CastInst(*this); }
1139 CallInst   *CallInst::clone()   const { return new CallInst(*this); }
1140 ShiftInst  *ShiftInst::clone()  const { return new ShiftInst(*this); }
1141 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1142 VAArgInst  *VAArgInst::clone()  const { return new VAArgInst(*this); }
1143 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
1144 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1145 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1146 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1147 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1148 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1149 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}