blob: 59881fd97446d084fa9ce6c3b412b2c89f6cedbf [file] [log] [blame]
Evan Cheng20e9d032009-12-02 22:02:52 +00001//===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
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//
Evan Cheng71453822009-12-03 02:31:43 +000010// This file implements the MachineSSAUpdater class. It's based on SSAUpdater
11// class in lib/Transforms/Utils.
Evan Cheng20e9d032009-12-02 22:02:52 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/MachineSSAUpdater.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/SmallVector.h"
Evan Cheng20e9d032009-12-02 22:02:52 +000018#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng71453822009-12-03 02:31:43 +000019#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
Bob Wilsond561daf2010-04-26 17:40:49 +000021#include "llvm/Support/AlignOf.h"
22#include "llvm/Support/Allocator.h"
Evan Cheng71453822009-12-03 02:31:43 +000023#include "llvm/Support/Debug.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000029#include "llvm/Target/TargetSubtargetInfo.h"
Bob Wilsond1b38e32010-05-04 23:18:19 +000030#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Evan Cheng20e9d032009-12-02 22:02:52 +000031using namespace llvm;
32
Chandler Carruthe96dd892014-04-21 22:55:11 +000033#define DEBUG_TYPE "machine-ssaupdater"
34
Bob Wilsond561daf2010-04-26 17:40:49 +000035typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
Evan Cheng20e9d032009-12-02 22:02:52 +000036static AvailableValsTy &getAvailableVals(void *AV) {
37 return *static_cast<AvailableValsTy*>(AV);
38}
39
Evan Cheng71453822009-12-03 02:31:43 +000040MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
41 SmallVectorImpl<MachineInstr*> *NewPHI)
Craig Topperc0196b12014-04-14 00:51:57 +000042 : AV(nullptr), InsertedPHIs(NewPHI) {
Eric Christopherd9134482014-08-04 21:25:23 +000043 TII = MF.getTarget().getSubtargetImpl()->getInstrInfo();
Evan Cheng71453822009-12-03 02:31:43 +000044 MRI = &MF.getRegInfo();
45}
Evan Cheng20e9d032009-12-02 22:02:52 +000046
47MachineSSAUpdater::~MachineSSAUpdater() {
Richard Smith0ff8f0e2012-08-14 05:31:26 +000048 delete static_cast<AvailableValsTy*>(AV);
Evan Cheng20e9d032009-12-02 22:02:52 +000049}
50
51/// Initialize - Reset this object to get ready for a new set of SSA
52/// updates. ProtoValue is the value used to name PHI nodes.
Evan Cheng71453822009-12-03 02:31:43 +000053void MachineSSAUpdater::Initialize(unsigned V) {
Craig Topperc0196b12014-04-14 00:51:57 +000054 if (!AV)
Evan Cheng20e9d032009-12-02 22:02:52 +000055 AV = new AvailableValsTy();
56 else
57 getAvailableVals(AV).clear();
58
Evan Cheng71453822009-12-03 02:31:43 +000059 VR = V;
60 VRC = MRI->getRegClass(VR);
Evan Cheng20e9d032009-12-02 22:02:52 +000061}
62
63/// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
64/// the specified block.
65bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
66 return getAvailableVals(AV).count(BB);
67}
68
69/// AddAvailableValue - Indicate that a rewritten value is available in the
70/// specified block with the specified value.
71void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
72 getAvailableVals(AV)[BB] = V;
73}
74
75/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
76/// live at the end of the specified block.
77unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
78 return GetValueAtEndOfBlockInternal(BB);
79}
80
Evan Chengfb1654d2009-12-07 23:11:03 +000081static
82unsigned LookForIdenticalPHI(MachineBasicBlock *BB,
Craig Topperb94011f2013-07-14 04:42:23 +000083 SmallVectorImpl<std::pair<MachineBasicBlock*, unsigned> > &PredValues) {
Evan Chengfb1654d2009-12-07 23:11:03 +000084 if (BB->empty())
85 return 0;
86
Evan Chengc1610be2011-12-06 02:49:06 +000087 MachineBasicBlock::iterator I = BB->begin();
Chris Lattnerb06015a2010-02-09 19:54:29 +000088 if (!I->isPHI())
Evan Chengfb1654d2009-12-07 23:11:03 +000089 return 0;
90
91 AvailableValsTy AVals;
92 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
93 AVals[PredValues[i].first] = PredValues[i].second;
Chris Lattnerb06015a2010-02-09 19:54:29 +000094 while (I != BB->end() && I->isPHI()) {
Evan Chengfb1654d2009-12-07 23:11:03 +000095 bool Same = true;
96 for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
97 unsigned SrcReg = I->getOperand(i).getReg();
98 MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
99 if (AVals[SrcBB] != SrcReg) {
100 Same = false;
101 break;
102 }
103 }
104 if (Same)
105 return I->getOperand(0).getReg();
106 ++I;
107 }
108 return 0;
109}
110
Evan Chengb2c15292009-12-03 21:51:55 +0000111/// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
112/// a value of the given register class at the start of the specified basic
113/// block. It returns the virtual register defined by the instruction.
Evan Cheng71453822009-12-03 02:31:43 +0000114static
Jakob Stoklund Olesenb159b5f2012-12-19 21:31:56 +0000115MachineInstrBuilder InsertNewDef(unsigned Opcode,
Evan Chengb2c15292009-12-03 21:51:55 +0000116 MachineBasicBlock *BB, MachineBasicBlock::iterator I,
117 const TargetRegisterClass *RC,
Bob Wilsond1b38e32010-05-04 23:18:19 +0000118 MachineRegisterInfo *MRI,
119 const TargetInstrInfo *TII) {
Evan Cheng71453822009-12-03 02:31:43 +0000120 unsigned NewVR = MRI->createVirtualRegister(RC);
Chris Lattnerbd009d62010-04-02 20:17:23 +0000121 return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
Evan Cheng71453822009-12-03 02:31:43 +0000122}
Bob Wilsond561daf2010-04-26 17:40:49 +0000123
Evan Cheng20e9d032009-12-02 22:02:52 +0000124/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
125/// is live in the middle of the specified block.
126///
127/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
128/// important case: if there is a definition of the rewritten value after the
129/// 'use' in BB. Consider code like this:
130///
131/// X1 = ...
132/// SomeBB:
133/// use(X)
134/// X2 = ...
135/// br Cond, SomeBB, OutBB
136///
137/// In this case, there are two values (X1 and X2) added to the AvailableVals
138/// set by the client of the rewriter, and those values are both live out of
139/// their respective blocks. However, the use of X happens in the *middle* of
140/// a block. Because of this, we need to insert a new PHI node in SomeBB to
141/// merge the appropriate values, and this value isn't live out of the block.
142///
143unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
Evan Cheng71453822009-12-03 02:31:43 +0000144 // If there is no definition of the renamed variable in this block, just use
145 // GetValueAtEndOfBlock to do our work.
Bob Wilsond561daf2010-04-26 17:40:49 +0000146 if (!HasValueForBlock(BB))
Evan Chengfb1654d2009-12-07 23:11:03 +0000147 return GetValueAtEndOfBlockInternal(BB);
Evan Cheng71453822009-12-03 02:31:43 +0000148
Evan Chengb2c15292009-12-03 21:51:55 +0000149 // If there are no predecessors, just return undef.
Evan Cheng0f1cc352009-12-04 09:23:37 +0000150 if (BB->pred_empty()) {
151 // Insert an implicit_def to represent an undef value.
Chris Lattnerb06015a2010-02-09 19:54:29 +0000152 MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
Evan Cheng0f1cc352009-12-04 09:23:37 +0000153 BB, BB->getFirstTerminator(),
154 VRC, MRI, TII);
155 return NewDef->getOperand(0).getReg();
156 }
Evan Cheng71453822009-12-03 02:31:43 +0000157
158 // Otherwise, we have the hard case. Get the live-in values for each
159 // predecessor.
160 SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
161 unsigned SingularValue = 0;
162
163 bool isFirstPred = true;
164 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
165 E = BB->pred_end(); PI != E; ++PI) {
166 MachineBasicBlock *PredBB = *PI;
167 unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
168 PredValues.push_back(std::make_pair(PredBB, PredVal));
169
170 // Compute SingularValue.
171 if (isFirstPred) {
172 SingularValue = PredVal;
173 isFirstPred = false;
174 } else if (PredVal != SingularValue)
175 SingularValue = 0;
176 }
177
178 // Otherwise, if all the merged values are the same, just use it.
179 if (SingularValue != 0)
180 return SingularValue;
181
Evan Chengfb1654d2009-12-07 23:11:03 +0000182 // If an identical PHI is already in BB, just reuse it.
183 unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
184 if (DupPHI)
185 return DupPHI;
186
Evan Cheng71453822009-12-03 02:31:43 +0000187 // Otherwise, we do need a PHI: insert one now.
Evan Chengc1610be2011-12-06 02:49:06 +0000188 MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
Jakob Stoklund Olesenb159b5f2012-12-19 21:31:56 +0000189 MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
190 Loc, VRC, MRI, TII);
Evan Cheng71453822009-12-03 02:31:43 +0000191
192 // Fill in all the predecessors of the PHI.
Evan Cheng71453822009-12-03 02:31:43 +0000193 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
Jakob Stoklund Olesenb159b5f2012-12-19 21:31:56 +0000194 InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
Evan Cheng71453822009-12-03 02:31:43 +0000195
196 // See if the PHI node can be merged to a single value. This can happen in
197 // loop cases when we get a PHI of itself and one other value.
198 if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
199 InsertedPHI->eraseFromParent();
200 return ConstVal;
201 }
202
203 // If the client wants to know about all new instructions, tell it.
204 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
205
David Greene646aacb2010-01-05 00:10:05 +0000206 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Evan Cheng71453822009-12-03 02:31:43 +0000207 return InsertedPHI->getOperand(0).getReg();
208}
209
210static
211MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
212 MachineOperand *U) {
213 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
214 if (&MI->getOperand(i) == U)
215 return MI->getOperand(i+1).getMBB();
216 }
217
218 llvm_unreachable("MachineOperand::getParent() failure?");
Evan Cheng20e9d032009-12-02 22:02:52 +0000219}
220
221/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
222/// which use their value in the corresponding predecessor.
Evan Cheng71453822009-12-03 02:31:43 +0000223void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
224 MachineInstr *UseMI = U.getParent();
225 unsigned NewVR = 0;
Chris Lattnerb06015a2010-02-09 19:54:29 +0000226 if (UseMI->isPHI()) {
Evan Cheng71453822009-12-03 02:31:43 +0000227 MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
Evan Chengfb1654d2009-12-07 23:11:03 +0000228 NewVR = GetValueAtEndOfBlockInternal(SourceBB);
Evan Chenge156f612009-12-04 00:09:05 +0000229 } else {
230 NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
Evan Chengb2c15292009-12-03 21:51:55 +0000231 }
Evan Chenge156f612009-12-04 00:09:05 +0000232
Evan Cheng71453822009-12-03 02:31:43 +0000233 U.setReg(NewVR);
234}
Evan Cheng20e9d032009-12-02 22:02:52 +0000235
Bob Wilsond1b38e32010-05-04 23:18:19 +0000236/// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
237/// template, specialized for MachineSSAUpdater.
238namespace llvm {
239template<>
240class SSAUpdaterTraits<MachineSSAUpdater> {
241public:
242 typedef MachineBasicBlock BlkT;
243 typedef unsigned ValT;
244 typedef MachineInstr PhiT;
245
246 typedef MachineBasicBlock::succ_iterator BlkSucc_iterator;
247 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
248 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
249
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000250 /// Iterator for PHI operands.
251 class PHI_iterator {
252 private:
253 MachineInstr *PHI;
254 unsigned idx;
255
256 public:
257 explicit PHI_iterator(MachineInstr *P) // begin iterator
258 : PHI(P), idx(1) {}
259 PHI_iterator(MachineInstr *P, bool) // end iterator
260 : PHI(P), idx(PHI->getNumOperands()) {}
261
262 PHI_iterator &operator++() { idx += 2; return *this; }
263 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
264 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
265 unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
266 MachineBasicBlock *getIncomingBlock() {
267 return PHI->getOperand(idx+1).getMBB();
268 }
269 };
Bob Wilsond1b38e32010-05-04 23:18:19 +0000270 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
271 static inline PHI_iterator PHI_end(PhiT *PHI) {
272 return PHI_iterator(PHI, true);
273 }
274
275 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
276 /// vector.
277 static void FindPredecessorBlocks(MachineBasicBlock *BB,
278 SmallVectorImpl<MachineBasicBlock*> *Preds){
279 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
280 E = BB->pred_end(); PI != E; ++PI)
281 Preds->push_back(*PI);
282 }
283
284 /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
285 /// Add it into the specified block and return the register.
286 static unsigned GetUndefVal(MachineBasicBlock *BB,
287 MachineSSAUpdater *Updater) {
288 // Insert an implicit_def to represent an undef value.
289 MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
290 BB, BB->getFirstTerminator(),
291 Updater->VRC, Updater->MRI,
292 Updater->TII);
293 return NewDef->getOperand(0).getReg();
294 }
295
296 /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
297 /// Add it into the specified block and return the register.
298 static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
299 MachineSSAUpdater *Updater) {
Evan Chengc1610be2011-12-06 02:49:06 +0000300 MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
Bob Wilsond1b38e32010-05-04 23:18:19 +0000301 MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
302 Updater->VRC, Updater->MRI,
303 Updater->TII);
304 return PHI->getOperand(0).getReg();
305 }
306
307 /// AddPHIOperand - Add the specified value as an operand of the PHI for
308 /// the specified predecessor block.
309 static void AddPHIOperand(MachineInstr *PHI, unsigned Val,
310 MachineBasicBlock *Pred) {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000311 MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000312 }
313
314 /// InstrIsPHI - Check if an instruction is a PHI.
315 ///
316 static MachineInstr *InstrIsPHI(MachineInstr *I) {
Bob Wilson01fcdaa2010-05-10 17:14:26 +0000317 if (I && I->isPHI())
Bob Wilsond1b38e32010-05-04 23:18:19 +0000318 return I;
Craig Topperc0196b12014-04-14 00:51:57 +0000319 return nullptr;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000320 }
321
322 /// ValueIsPHI - Check if the instruction that defines the specified register
323 /// is a PHI instruction.
324 static MachineInstr *ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater) {
325 return InstrIsPHI(Updater->MRI->getVRegDef(Val));
326 }
327
328 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
329 /// operands, i.e., it was just added.
330 static MachineInstr *ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater) {
331 MachineInstr *PHI = ValueIsPHI(Val, Updater);
332 if (PHI && PHI->getNumOperands() <= 1)
333 return PHI;
Craig Topperc0196b12014-04-14 00:51:57 +0000334 return nullptr;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000335 }
336
337 /// GetPHIValue - For the specified PHI instruction, return the register
338 /// that it defines.
339 static unsigned GetPHIValue(MachineInstr *PHI) {
340 return PHI->getOperand(0).getReg();
341 }
342};
343
344} // End llvm namespace
345
Evan Cheng20e9d032009-12-02 22:02:52 +0000346/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
347/// for the specified BB and if so, return it. If not, construct SSA form by
Bob Wilsond561daf2010-04-26 17:40:49 +0000348/// first calculating the required placement of PHIs and then inserting new
349/// PHIs where needed.
Evan Cheng20e9d032009-12-02 22:02:52 +0000350unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
Evan Cheng71453822009-12-03 02:31:43 +0000351 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilsond561daf2010-04-26 17:40:49 +0000352 if (unsigned V = AvailableVals[BB])
353 return V;
Evan Cheng71453822009-12-03 02:31:43 +0000354
Bob Wilsond1b38e32010-05-04 23:18:19 +0000355 SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
356 return Impl.GetValue(BB);
Evan Cheng20e9d032009-12-02 22:02:52 +0000357}