Add many more instruction combination simplifications
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -------------=//
2 //
3 // InstructionCombining - Combine instructions to form fewer, simple
4 //   instructions.  This pass does not modify the CFG, and has a tendancy to
5 //   make instructions dead, so a subsequent DIE pass is useful.  This pass is
6 //   where algebraic simplification happens.
7 //
8 // This pass combines things like:
9 //    %Y = add int 1, %X
10 //    %Z = add int 1, %Y
11 // into:
12 //    %Z = add int 2, %X
13 //
14 // This is a simple worklist driven algorithm.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Scalar/InstructionCombining.h"
19 #include "llvm/ConstantHandling.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iOther.h"
22 #include "llvm/iOperators.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "../TransformInternals.h"
27
28
29 namespace {
30   class InstCombiner : public FunctionPass,
31                        public InstVisitor<InstCombiner, Instruction*> {
32     // Worklist of all of the instructions that need to be simplified.
33     std::vector<Instruction*> WorkList;
34
35     void AddUsesToWorkList(Instruction *I) {
36       // The instruction was simplified, add all users of the instruction to
37       // the work lists because they might get more simplified now...
38       //
39       for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
40            UI != UE; ++UI)
41         WorkList.push_back(cast<Instruction>(*UI));
42     }
43
44   public:
45     const char *getPassName() const { return "Instruction Combining"; }
46
47     virtual bool runOnFunction(Function *F);
48
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.preservesCFG();
51     }
52
53     // Visitation implementation - Implement instruction combining for different
54     // instruction types.  The semantics are as follows:
55     // Return Value:
56     //    null        - No change was made
57     //     I          - Change was made, I is still valid
58     //   otherwise    - Change was made, replace I with returned instruction
59     //   
60
61     Instruction *visitAdd(BinaryOperator *I);
62     Instruction *visitSub(BinaryOperator *I);
63     Instruction *visitMul(BinaryOperator *I);
64     Instruction *visitDiv(BinaryOperator *I);
65     Instruction *visitRem(BinaryOperator *I);
66     Instruction *visitAnd(BinaryOperator *I);
67     Instruction *visitOr (BinaryOperator *I);
68     Instruction *visitXor(BinaryOperator *I);
69     Instruction *visitSetCondInst(BinaryOperator *I);
70     Instruction *visitShiftInst(Instruction *I);
71     Instruction *visitCastInst(CastInst *CI);
72     Instruction *visitGetElementPtrInst(GetElementPtrInst *GEP);
73     Instruction *visitMemAccessInst(MemAccessInst *MAI);
74
75     // visitInstruction - Specify what to return for unhandled instructions...
76     Instruction *visitInstruction(Instruction *I) { return 0; }
77   };
78 }
79
80
81
82 // Make sure that this instruction has a constant on the right hand side if it
83 // has any constant arguments.  If not, fix it an return true.
84 //
85 static bool SimplifyBinOp(BinaryOperator *I) {
86   if (isa<Constant>(I->getOperand(0)) && !isa<Constant>(I->getOperand(1)))
87     return !I->swapOperands();
88   return false;
89 }
90
91 Instruction *InstCombiner::visitAdd(BinaryOperator *I) {
92   if (I->use_empty()) return 0;       // Don't fix dead add instructions...
93   bool Changed = SimplifyBinOp(I);
94   Value *Op1 = I->getOperand(0);
95
96   // Simplify add instructions with a constant RHS...
97   if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
98     // Eliminate 'add int %X, 0'
99     if (I->getType()->isIntegral() && Op2->isNullValue()) {
100       AddUsesToWorkList(I);         // Add all modified instrs to worklist
101       I->replaceAllUsesWith(Op1);
102       return I;
103     }
104  
105     if (BinaryOperator *IOp1 = dyn_cast<BinaryOperator>(Op1)) {
106       Changed |= SimplifyBinOp(IOp1);
107       
108       if (IOp1->getOpcode() == Instruction::Add &&
109           isa<Constant>(IOp1->getOperand(1))) {
110         // Fold:
111         //    %Y = add int %X, 1
112         //    %Z = add int %Y, 1
113         // into:
114         //    %Z = add int %X, 2
115         //
116         if (Constant *Val = *Op2 + *cast<Constant>(IOp1->getOperand(1))) {
117           I->setOperand(0, IOp1->getOperand(0));
118           I->setOperand(1, Val);
119           return I;
120         }
121       }
122     }
123   }
124
125   return Changed ? I : 0;
126 }
127
128 Instruction *InstCombiner::visitSub(BinaryOperator *I) {
129   if (I->use_empty()) return 0;       // Don't fix dead add instructions...
130   Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
131
132   if (Op0 == Op1) {         // sub X, X  -> 0
133     AddUsesToWorkList(I);         // Add all modified instrs to worklist
134     I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
135     return I;
136   }
137
138   // If this is a subtract instruction with a constant RHS, convert it to an add
139   // instruction of a negative constant
140   //
141   if (Constant *Op2 = dyn_cast<Constant>(Op1))
142     if (Constant *RHS = *Constant::getNullValue(I->getType()) - *Op2) // 0 - RHS
143       return BinaryOperator::create(Instruction::Add, Op0, RHS, I->getName());
144
145   return 0;
146 }
147
148 Instruction *InstCombiner::visitMul(BinaryOperator *I) {
149   if (I->use_empty()) return 0;       // Don't fix dead instructions...
150   bool Changed = SimplifyBinOp(I);
151   Value *Op1 = I->getOperand(0);
152
153   // Simplify add instructions with a constant RHS...
154   if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
155     if (I->getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
156       // Eliminate 'mul int %X, 1'
157       AddUsesToWorkList(I);         // Add all modified instrs to worklist
158       I->replaceAllUsesWith(Op1);
159       return I;
160
161     } else if (I->getType()->isIntegral() &&
162                cast<ConstantInt>(Op2)->equalsInt(2)) {
163       // Convert 'mul int %X, 2' to 'add int %X, %X'
164       return BinaryOperator::create(Instruction::Add, Op1, Op1, I->getName());
165
166     } else if (Op2->isNullValue()) {
167       // Eliminate 'mul int %X, 0'
168       AddUsesToWorkList(I);         // Add all modified instrs to worklist
169       I->replaceAllUsesWith(Op2);   // Set this value to zero directly
170       return I;
171     }
172   }
173
174   return Changed ? I : 0;
175 }
176
177
178 Instruction *InstCombiner::visitDiv(BinaryOperator *I) {
179   if (I->use_empty()) return 0;       // Don't fix dead instructions...
180
181   // div X, 1 == X
182   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
183     if (RHS->equalsInt(1)) {
184       AddUsesToWorkList(I);         // Add all modified instrs to worklist
185       I->replaceAllUsesWith(I->getOperand(0));
186       return I;
187     }
188   return 0;
189 }
190
191
192 Instruction *InstCombiner::visitRem(BinaryOperator *I) {
193   if (I->use_empty()) return 0;       // Don't fix dead instructions...
194
195   // rem X, 1 == 0
196   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
197     if (RHS->equalsInt(1)) {
198       AddUsesToWorkList(I);         // Add all modified instrs to worklist
199       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
200       return I;
201     }
202   return 0;
203 }
204
205 static Constant *getMaxValue(const Type *Ty) {
206   assert(Ty == Type::BoolTy || Ty->isIntegral());
207   if (Ty == Type::BoolTy)
208     return ConstantBool::True;
209
210   // Calculate -1 casted to the right type...
211   unsigned TypeBits = Ty->getPrimitiveSize()*8;
212   uint64_t Val = (uint64_t)-1LL;       // All ones
213   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
214
215   if (Ty->isSigned())
216     return ConstantSInt::get(Ty, (int64_t)Val);
217   else if (Ty->isUnsigned())
218     return ConstantUInt::get(Ty, Val);
219
220   return 0;
221 }
222
223
224 Instruction *InstCombiner::visitAnd(BinaryOperator *I) {
225   if (I->use_empty()) return 0;       // Don't fix dead instructions...
226   bool Changed = SimplifyBinOp(I);
227   Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
228
229   // and X, X = X   and X, 0 == 0
230   if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
231     AddUsesToWorkList(I);         // Add all modified instrs to worklist
232     I->replaceAllUsesWith(Op1);
233     return I;
234   }
235
236   // and X, -1 == X
237   if (Constant *RHS = dyn_cast<Constant>(Op1))
238     if (RHS == getMaxValue(I->getType())) {
239       AddUsesToWorkList(I);         // Add all modified instrs to worklist
240       I->replaceAllUsesWith(Op0);
241       return I;
242     }
243
244   return Changed ? I : 0;
245 }
246
247
248
249 Instruction *InstCombiner::visitOr(BinaryOperator *I) {
250   if (I->use_empty()) return 0;       // Don't fix dead instructions...
251   bool Changed = SimplifyBinOp(I);
252   Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
253
254   // or X, X = X   or X, 0 == X
255   if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
256     AddUsesToWorkList(I);         // Add all modified instrs to worklist
257     I->replaceAllUsesWith(Op0);
258     return I;
259   }
260
261   // or X, -1 == -1
262   if (Constant *RHS = dyn_cast<Constant>(Op1))
263     if (RHS == getMaxValue(I->getType())) {
264       AddUsesToWorkList(I);         // Add all modified instrs to worklist
265       I->replaceAllUsesWith(Op1);
266       return I;
267     }
268
269   return Changed ? I : 0;
270 }
271
272
273
274 Instruction *InstCombiner::visitXor(BinaryOperator *I) {
275   if (I->use_empty()) return 0;       // Don't fix dead instructions...
276   bool Changed = SimplifyBinOp(I);
277   Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
278
279   // xor X, X = 0
280   if (Op0 == Op1) {
281     AddUsesToWorkList(I);         // Add all modified instrs to worklist
282     I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
283     return I;
284   }
285
286   // xor X, 0 == X
287   if (Op1 == Constant::getNullValue(I->getType())) {
288     AddUsesToWorkList(I);         // Add all modified instrs to worklist
289     I->replaceAllUsesWith(Op0);
290     return I;
291   }
292
293   return Changed ? I : 0;
294 }
295
296 Instruction *InstCombiner::visitSetCondInst(BinaryOperator *I) {
297   if (I->use_empty()) return 0;       // Don't fix dead instructions...
298   bool Changed = SimplifyBinOp(I);
299
300   // setcc X, X
301   if (I->getOperand(0) == I->getOperand(1)) {
302     bool NewVal = I->getOpcode() == Instruction::SetEQ ||
303                   I->getOpcode() == Instruction::SetGE ||
304                   I->getOpcode() == Instruction::SetLE;
305     AddUsesToWorkList(I);         // Add all modified instrs to worklist
306     I->replaceAllUsesWith(ConstantBool::get(NewVal));
307     return I;
308   }
309
310   return Changed ? I : 0;
311 }
312
313
314
315 Instruction *InstCombiner::visitShiftInst(Instruction *I) {
316   if (I->use_empty()) return 0;       // Don't fix dead instructions...
317   assert(I->getOperand(1)->getType() == Type::UByteTy);
318   Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
319
320   // shl X, 0 == X and shr X, 0 == X
321   // shl 0, X == 0 and shr 0, X == 0
322   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
323       Op0 == Constant::getNullValue(Op0->getType())) {
324     AddUsesToWorkList(I);         // Add all modified instrs to worklist
325     I->replaceAllUsesWith(Op0);
326     return I;
327   }
328
329   // shl int X, 32 = 0 and shr sbyte Y, 9 = 0, ... just don't eliminate shr of
330   // a signed value.
331   //
332   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
333     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
334     if (CUI->getValue() >= TypeBits &&
335         !(Op0->getType()->isSigned() && I->getOpcode() == Instruction::Shr)) {
336       AddUsesToWorkList(I);         // Add all modified instrs to worklist
337       I->replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
338       return I;
339     }
340   }
341   return 0;
342 }
343
344
345 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
346 // instruction.
347 //
348 static inline bool isEliminableCastOfCast(const CastInst *CI,
349                                           const CastInst *CSrc) {
350   assert(CI->getOperand(0) == CSrc);
351   const Type *SrcTy = CSrc->getOperand(0)->getType();
352   const Type *MidTy = CSrc->getType();
353   const Type *DstTy = CI->getType();
354
355   // It is legal to eliminate the instruction if casting A->B->A
356   if (SrcTy == DstTy) return true;
357
358   // Allow free casting and conversion of sizes as long as the sign doesn't
359   // change...
360   if (SrcTy->isSigned() == MidTy->isSigned() &&
361       MidTy->isSigned() == DstTy->isSigned())
362     return true;
363
364   // Otherwise, we cannot succeed.  Specifically we do not want to allow things
365   // like:  short -> ushort -> uint, because this can create wrong results if
366   // the input short is negative!
367   //
368   return false;
369 }
370
371
372 // CastInst simplification
373 //
374 Instruction *InstCombiner::visitCastInst(CastInst *CI) {
375   // If the user is casting a value to the same type, eliminate this cast
376   // instruction...
377   if (CI->getType() == CI->getOperand(0)->getType() && !CI->use_empty()) {
378     AddUsesToWorkList(CI);         // Add all modified instrs to worklist
379     CI->replaceAllUsesWith(CI->getOperand(0));
380     return CI;
381   }
382
383
384   // If casting the result of another cast instruction, try to eliminate this
385   // one!
386   //
387   if (CastInst *CSrc = dyn_cast<CastInst>(CI->getOperand(0)))
388     if (isEliminableCastOfCast(CI, CSrc)) {
389       // This instruction now refers directly to the cast's src operand.  This
390       // has a good chance of making CSrc dead.
391       CI->setOperand(0, CSrc->getOperand(0));
392       return CI;
393     }
394
395   return 0;
396 }
397
398
399
400 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst *GEP) {
401   // Is it getelementptr %P, uint 0
402   // If so, elminate the noop.
403   if (GEP->getNumOperands() == 2 && !GEP->use_empty() &&
404       GEP->getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
405     AddUsesToWorkList(GEP);         // Add all modified instrs to worklist
406     GEP->replaceAllUsesWith(GEP->getOperand(0));
407     return GEP;
408   }
409
410   return visitMemAccessInst(GEP);
411 }
412
413
414 // Combine Indices - If the source pointer to this mem access instruction is a
415 // getelementptr instruction, combine the indices of the GEP into this
416 // instruction
417 //
418 Instruction *InstCombiner::visitMemAccessInst(MemAccessInst *MAI) {
419   GetElementPtrInst *Src =
420     dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
421   if (!Src) return 0;
422
423   std::vector<Value *> Indices;
424   
425   // Only special case we have to watch out for is pointer arithmetic on the
426   // 0th index of MAI. 
427   unsigned FirstIdx = MAI->getFirstIndexOperandNumber();
428   if (FirstIdx == MAI->getNumOperands() || 
429       (FirstIdx == MAI->getNumOperands()-1 &&
430        MAI->getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) { 
431     // Replace the index list on this MAI with the index on the getelementptr
432     Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
433   } else if (*MAI->idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) { 
434     // Otherwise we can do the fold if the first index of the GEP is a zero
435     Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
436     Indices.insert(Indices.end(), MAI->idx_begin()+1, MAI->idx_end());
437   }
438
439   if (Indices.empty()) return 0;  // Can't do the fold?
440
441   switch (MAI->getOpcode()) {
442   case Instruction::GetElementPtr:
443     return new GetElementPtrInst(Src->getOperand(0), Indices, MAI->getName());
444   case Instruction::Load:
445     return new LoadInst(Src->getOperand(0), Indices, MAI->getName());
446   case Instruction::Store:
447     return new StoreInst(MAI->getOperand(0), Src->getOperand(0), Indices);
448   default:
449     assert(0 && "Unknown memaccessinst!");
450     break;
451   }
452   abort();
453   return 0;
454 }
455
456
457 bool InstCombiner::runOnFunction(Function *F) {
458   bool Changed = false;
459
460   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
461
462   while (!WorkList.empty()) {
463     Instruction *I = WorkList.back();  // Get an instruction from the worklist
464     WorkList.pop_back();
465
466     // Now that we have an instruction, try combining it to simplify it...
467     Instruction *Result = visit(I);
468     if (Result) {
469       // Should we replace the old instruction with a new one?
470       if (Result != I)
471         ReplaceInstWithInst(I, Result);
472
473       WorkList.push_back(Result);
474       AddUsesToWorkList(Result);
475       Changed = true;
476     }
477   }
478
479   return Changed;
480 }
481
482 Pass *createInstructionCombiningPass() {
483   return new InstCombiner();
484 }