blob: 2dbdb1981a0097f8a7ef687d79a3e17a3069798b [file] [log] [blame]
Chris Lattner210e45a2009-12-04 02:10:16 +00001//===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
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 the PHITransAddr class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/PHITransAddr.h"
15#include "llvm/Analysis/Dominators.h"
Chris Lattner9a864122009-12-07 18:36:53 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7dedbf42009-12-09 00:01:00 +000017#include "llvm/Support/raw_ostream.h"
Chris Lattner210e45a2009-12-04 02:10:16 +000018using namespace llvm;
19
Chris Lattner6fcca1c2009-12-07 19:04:49 +000020static bool CanPHITrans(Instruction *Inst) {
21 if (isa<PHINode>(Inst) ||
22 isa<BitCastInst>(Inst) ||
23 isa<GetElementPtrInst>(Inst))
24 return true;
25
Chris Lattner34f84902009-12-08 06:06:26 +000026 if (Inst->getOpcode() == Instruction::Add &&
Chris Lattner6fcca1c2009-12-07 19:04:49 +000027 isa<ConstantInt>(Inst->getOperand(1)))
28 return true;
29
30 // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
31 // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
32 // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
33 return false;
34}
35
Chris Lattner7dedbf42009-12-09 00:01:00 +000036void PHITransAddr::dump() const {
37 if (Addr == 0) {
38 errs() << "PHITransAddr: null\n";
39 return;
40 }
41 errs() << "PHITransAddr: " << *Addr << "\n";
42 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
43 errs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
44}
45
46
47static bool VerifySubExpr(Value *Expr,
48 SmallVectorImpl<Instruction*> &InstInputs) {
49 // If this is a non-instruction value, there is nothing to do.
50 Instruction *I = dyn_cast<Instruction>(Expr);
51 if (I == 0) return true;
52
53 // If it's an instruction, it is either in Tmp or its operands recursively
54 // are.
55 SmallVectorImpl<Instruction*>::iterator Entry =
56 std::find(InstInputs.begin(), InstInputs.end(), I);
57 if (Entry != InstInputs.end()) {
58 InstInputs.erase(Entry);
59 return true;
60 }
61
62 // If it isn't in the InstInputs list it is a subexpr incorporated into the
63 // address. Sanity check that it is phi translatable.
64 if (!CanPHITrans(I)) {
65 errs() << "Non phi translatable instruction found in PHITransAddr, either "
66 "something is missing from InstInputs or CanPHITrans is wrong:\n";
67 errs() << *I << '\n';
68 return false;
69 }
70
71 // Validate the operands of the instruction.
72 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
73 if (!VerifySubExpr(I->getOperand(i), InstInputs))
74 return false;
75
76 return true;
77}
78
79/// Verify - Check internal consistency of this data structure. If the
80/// structure is valid, it returns true. If invalid, it prints errors and
81/// returns false.
82bool PHITransAddr::Verify() const {
83 if (Addr == 0) return true;
84
85 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
86
87 if (!VerifySubExpr(Addr, Tmp))
88 return false;
89
90 if (!Tmp.empty()) {
91 errs() << "PHITransAddr inconsistent, contains extra instructions:\n";
92 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
93 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
94 return false;
95 }
96
97 // a-ok.
98 return true;
99}
100
101
Chris Lattner9a864122009-12-07 18:36:53 +0000102/// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
103/// if we have some hope of doing it. This should be used as a filter to
104/// avoid calling PHITranslateValue in hopeless situations.
105bool PHITransAddr::IsPotentiallyPHITranslatable() const {
106 // If the input value is not an instruction, or if it is not defined in CurBB,
107 // then we don't need to phi translate it.
108 Instruction *Inst = dyn_cast<Instruction>(Addr);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000109 return Inst == 0 || CanPHITrans(Inst);
Chris Lattner210e45a2009-12-04 02:10:16 +0000110}
111
Chris Lattner9a864122009-12-07 18:36:53 +0000112
Chris Lattner43678f42009-12-08 23:42:51 +0000113static void RemoveInstInputs(Instruction *I,
114 SmallVectorImpl<Instruction*> &InstInputs) {
115 // If the instruction is in the InstInputs list, remove it.
116 SmallVectorImpl<Instruction*>::iterator Entry =
117 std::find(InstInputs.begin(), InstInputs.end(), I);
118 if (Entry != InstInputs.end()) {
119 InstInputs.erase(Entry);
120 return;
121 }
122
123 // Otherwise, it must have instruction inputs itself. Zap them recursively.
124 bool HadInstInputs = false;
125 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
126 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i))) {
127 RemoveInstInputs(Op, InstInputs);
128 HadInstInputs = true;
129 }
130 }
131
132 // This instruction had to have operands in the instinputs list or it should
133 // have been in the list itself. If not, the list is broken.
134 assert(HadInstInputs && "InstInputs list inconsistent!");
135}
136
137/// ReplaceInstWithValue - Remove any instruction inputs in the InstInputs
138/// array that are due to the specified instruction that is about to be
139/// removed from the address, and add any corresponding to V. This returns V.
140Value *PHITransAddr::ReplaceInstWithValue(Instruction *I, Value *V) {
141 // Remove the old instruction from InstInputs.
142 RemoveInstInputs(I, InstInputs);
143
144 // If V is an instruction, it is now an input.
145 if (Instruction *VI = dyn_cast<Instruction>(V))
146 InstInputs.push_back(VI);
147 return V;
148}
149
150
Chris Lattner9a864122009-12-07 18:36:53 +0000151Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
152 BasicBlock *PredBB) {
153 // If this is a non-instruction value, it can't require PHI translation.
154 Instruction *Inst = dyn_cast<Instruction>(V);
155 if (Inst == 0) return V;
156
Chris Lattneraf503152009-12-09 00:10:55 +0000157 // Determine whether 'Inst' is an input to our PHI translatable expression.
158 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
159
160 // Handle inputs instructions if needed.
161 if (isInput) {
162 if (Inst->getParent() != CurBB) {
163 // If it is an input defined in a different block, then it remains an
164 // input.
165 return Inst;
166 }
167
168 // If 'Inst' is defined in this block, it must be an input that needs to be
169 // phi translated or an intermediate expression that needs to be incorporated
170 // into the expression.
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000171
172 // If this is a PHI, go ahead and translate it.
173 if (PHINode *PN = dyn_cast<PHINode>(Inst))
174 return PN->getIncomingValueForBlock(PredBB);
175
176
177 // If this is a non-phi value, and it is analyzable, we can incorporate it
178 // into the expression by making all instruction operands be inputs.
179 if (!CanPHITrans(Inst))
180 return 0;
181
182 // Okay, we can incorporate it, this instruction is no longer an input.
183 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
184
185 // All instruction operands are now inputs (and of course, they may also be
186 // defined in this block, so they may need to be phi translated themselves.
187 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
188 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
189 InstInputs.push_back(Op);
Chris Lattner9a864122009-12-07 18:36:53 +0000190 }
191
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000192 // Ok, it must be an intermediate result (either because it started that way
193 // or because we just incorporated it into the expression). See if its
194 // operands need to be phi translated, and if so, reconstruct it.
Chris Lattner9a864122009-12-07 18:36:53 +0000195
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000196 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
197 Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB);
198 if (PHIIn == 0) return 0;
199 if (PHIIn == BC->getOperand(0))
200 return BC;
201
202 // Find an available version of this cast.
203
204 // Constants are trivial to find.
205 if (Constant *C = dyn_cast<Constant>(PHIIn))
Chris Lattner43678f42009-12-08 23:42:51 +0000206 return ReplaceInstWithValue(BC, ConstantExpr::getBitCast(C,
207 BC->getType()));
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000208
209 // Otherwise we have to see if a bitcasted version of the incoming pointer
210 // is available. If so, we can use it, otherwise we have to fail.
211 for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
212 UI != E; ++UI) {
213 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI))
214 if (BCI->getType() == BC->getType())
215 return BCI;
216 }
217 return 0;
218 }
Chris Lattner9a864122009-12-07 18:36:53 +0000219
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000220 // Handle getelementptr with at least one PHI translatable operand.
221 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
222 SmallVector<Value*, 8> GEPOps;
223 BasicBlock *CurBB = GEP->getParent();
224 bool AnyChanged = false;
225 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
226 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB);
227 if (GEPOp == 0) return 0;
228
Chris Lattner60454172009-12-07 19:52:57 +0000229 AnyChanged |= GEPOp != GEP->getOperand(i);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000230 GEPOps.push_back(GEPOp);
231 }
232
233 if (!AnyChanged)
234 return GEP;
235
236 // Simplify the GEP to handle 'gep x, 0' -> x etc.
237 if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD))
Chris Lattner43678f42009-12-08 23:42:51 +0000238 return ReplaceInstWithValue(GEP, V);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000239
240 // Scan to see if we have this GEP available.
241 Value *APHIOp = GEPOps[0];
242 for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
243 UI != E; ++UI) {
244 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
245 if (GEPI->getType() == GEP->getType() &&
246 GEPI->getNumOperands() == GEPOps.size() &&
247 GEPI->getParent()->getParent() == CurBB->getParent()) {
248 bool Mismatch = false;
249 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
250 if (GEPI->getOperand(i) != GEPOps[i]) {
251 Mismatch = true;
252 break;
253 }
254 if (!Mismatch)
255 return GEPI;
256 }
257 }
258 return 0;
259 }
260
261 // Handle add with a constant RHS.
262 if (Inst->getOpcode() == Instruction::Add &&
263 isa<ConstantInt>(Inst->getOperand(1))) {
264 // PHI translate the LHS.
265 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
266 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
267 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
268
269 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB);
270 if (LHS == 0) return 0;
271
272 // If the PHI translated LHS is an add of a constant, fold the immediates.
273 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
274 if (BOp->getOpcode() == Instruction::Add)
275 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
276 LHS = BOp->getOperand(0);
277 RHS = ConstantExpr::getAdd(RHS, CI);
278 isNSW = isNUW = false;
279 }
280
281 // See if the add simplifies away.
282 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD))
Chris Lattner43678f42009-12-08 23:42:51 +0000283 return ReplaceInstWithValue(Inst, Res);
Chris Lattner6fcca1c2009-12-07 19:04:49 +0000284
285 // Otherwise, see if we have this add available somewhere.
286 for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
287 UI != E; ++UI) {
288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
289 if (BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
290 BO->getParent()->getParent() == CurBB->getParent())
291 return BO;
292 }
293
294 return 0;
295 }
296
297 // Otherwise, we failed.
298 return 0;
Chris Lattner210e45a2009-12-04 02:10:16 +0000299}
300
Chris Lattner9a864122009-12-07 18:36:53 +0000301
302/// PHITranslateValue - PHI translate the current address up the CFG from
303/// CurBB to Pred, updating our state the reflect any needed changes. This
Chris Lattnere05a1882009-12-07 19:45:30 +0000304/// returns true on failure and sets Addr to null.
Chris Lattner9a864122009-12-07 18:36:53 +0000305bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) {
Chris Lattner7dedbf42009-12-09 00:01:00 +0000306 assert(Verify() && "Invalid PHITransAddr!");
Chris Lattner9a864122009-12-07 18:36:53 +0000307 Addr = PHITranslateSubExpr(Addr, CurBB, PredBB);
Chris Lattner7dedbf42009-12-09 00:01:00 +0000308 assert(Verify() && "Invalid PHITransAddr!");
Chris Lattner9a864122009-12-07 18:36:53 +0000309 return Addr == 0;
310}
311
312/// GetAvailablePHITranslatedSubExpr - Return the value computed by
313/// PHITranslateSubExpr if it dominates PredBB, otherwise return null.
Chris Lattner210e45a2009-12-04 02:10:16 +0000314Value *PHITransAddr::
Chris Lattner9a864122009-12-07 18:36:53 +0000315GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB,
Chris Lattner34f84902009-12-08 06:06:26 +0000316 const DominatorTree &DT) const {
317 PHITransAddr Tmp(V, TD);
318 Tmp.PHITranslateValue(CurBB, PredBB);
319
Chris Lattner210e45a2009-12-04 02:10:16 +0000320 // See if PHI translation succeeds.
Chris Lattner34f84902009-12-08 06:06:26 +0000321 V = Tmp.getAddr();
Chris Lattner210e45a2009-12-04 02:10:16 +0000322
323 // Make sure the value is live in the predecessor.
324 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
325 if (!DT.dominates(Inst->getParent(), PredBB))
326 return 0;
327 return V;
328}
329
Chris Lattner9a864122009-12-07 18:36:53 +0000330
331/// PHITranslateWithInsertion - PHI translate this value into the specified
332/// predecessor block, inserting a computation of the value if it is
333/// unavailable.
334///
335/// All newly created instructions are added to the NewInsts list. This
336/// returns null on failure.
337///
338Value *PHITransAddr::
339PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
340 const DominatorTree &DT,
341 SmallVectorImpl<Instruction*> &NewInsts) {
342 unsigned NISize = NewInsts.size();
343
344 // Attempt to PHI translate with insertion.
345 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
346
347 // If successful, return the new value.
348 if (Addr) return Addr;
349
350 // If not, destroy any intermediate instructions inserted.
351 while (NewInsts.size() != NISize)
352 NewInsts.pop_back_val()->eraseFromParent();
353 return 0;
354}
355
356
Chris Lattner210e45a2009-12-04 02:10:16 +0000357/// InsertPHITranslatedPointer - Insert a computation of the PHI translated
358/// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
359/// block. All newly created instructions are added to the NewInsts list.
360/// This returns null on failure.
361///
362Value *PHITransAddr::
Chris Lattner9a864122009-12-07 18:36:53 +0000363InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
364 BasicBlock *PredBB, const DominatorTree &DT,
365 SmallVectorImpl<Instruction*> &NewInsts) {
Chris Lattner210e45a2009-12-04 02:10:16 +0000366 // See if we have a version of this value already available and dominating
Chris Lattner9a864122009-12-07 18:36:53 +0000367 // PredBB. If so, there is no need to insert a new instance of it.
368 if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT))
Chris Lattner210e45a2009-12-04 02:10:16 +0000369 return Res;
370
Chris Lattner9a864122009-12-07 18:36:53 +0000371 // If we don't have an available version of this value, it must be an
372 // instruction.
373 Instruction *Inst = cast<Instruction>(InVal);
374
375 // Handle bitcast of PHI translatable value.
376 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
377 Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0),
378 CurBB, PredBB, DT, NewInsts);
379 if (OpVal == 0) return 0;
380
381 // Otherwise insert a bitcast at the end of PredBB.
382 BitCastInst *New = new BitCastInst(OpVal, InVal->getType(),
383 InVal->getName()+".phi.trans.insert",
384 PredBB->getTerminator());
385 NewInsts.push_back(New);
386 return New;
387 }
388
389 // Handle getelementptr with at least one PHI operand.
390 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
391 SmallVector<Value*, 8> GEPOps;
392 BasicBlock *CurBB = GEP->getParent();
393 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
394 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
395 CurBB, PredBB, DT, NewInsts);
396 if (OpVal == 0) return 0;
397 GEPOps.push_back(OpVal);
398 }
399
400 GetElementPtrInst *Result =
401 GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
402 InVal->getName()+".phi.trans.insert",
403 PredBB->getTerminator());
404 Result->setIsInBounds(GEP->isInBounds());
405 NewInsts.push_back(Result);
406 return Result;
407 }
408
409#if 0
410 // FIXME: This code works, but it is unclear that we actually want to insert
411 // a big chain of computation in order to make a value available in a block.
412 // This needs to be evaluated carefully to consider its cost trade offs.
413
414 // Handle add with a constant RHS.
415 if (Inst->getOpcode() == Instruction::Add &&
416 isa<ConstantInt>(Inst->getOperand(1))) {
417 // PHI translate the LHS.
418 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
419 CurBB, PredBB, DT, NewInsts);
420 if (OpVal == 0) return 0;
421
422 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
423 InVal->getName()+".phi.trans.insert",
424 PredBB->getTerminator());
425 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
426 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
427 NewInsts.push_back(Res);
428 return Res;
429 }
430#endif
431
Chris Lattner210e45a2009-12-04 02:10:16 +0000432 return 0;
433}