LLVM 23.0.0git
SSAUpdaterImpl.h
Go to the documentation of this file.
1//===- SSAUpdaterImpl.h - SSA Updater Implementation ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides a template that implements the core algorithm for the
10// SSAUpdater and MachineSSAUpdater.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
15#define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/ScopeExit.h"
22#include "llvm/Support/Debug.h"
24
25#define DEBUG_TYPE "ssaupdater"
26
27namespace llvm {
28
30
31template<typename T> class SSAUpdaterTraits;
32
33template<typename UpdaterT>
35private:
36 UpdaterT *Updater;
37
38 using Traits = SSAUpdaterTraits<UpdaterT>;
39 using BlkT = typename Traits::BlkT;
40 using ValT = typename Traits::ValT;
41 using PhiT = typename Traits::PhiT;
42
43 /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl.
44 /// The predecessors of each block are cached here since pred_iterator is
45 /// slow and we need to iterate over the blocks at least a few times.
46 class BBInfo {
47 public:
48 // Back-pointer to the corresponding block.
49 BlkT *BB;
50
51 // Value to use in this block.
52 ValT AvailableVal;
53
54 // Block that defines the available value.
55 BBInfo *DefBB;
56
57 // Postorder number.
58 int BlkNum = 0;
59
60 // Immediate dominator.
61 BBInfo *IDom = nullptr;
62
63 // Number of predecessor blocks.
64 unsigned NumPreds = 0;
65
66 // Array[NumPreds] of predecessor blocks.
67 BBInfo **Preds = nullptr;
68
69 // Marker for existing PHIs that match.
70 PhiT *PHITag = nullptr;
71
72 BBInfo(BlkT *ThisBB, ValT V)
73 : BB(ThisBB), AvailableVal(V), DefBB(V ? this : nullptr) {}
74 };
75
76 using AvailableValsTy = DenseMap<BlkT *, ValT>;
77
78 AvailableValsTy *AvailableVals;
79
80 SmallVectorImpl<PhiT *> *InsertedPHIs;
81
82 using BlockListTy = SmallVectorImpl<BBInfo *>;
83 using BBMapTy = DenseMap<BlkT *, BBInfo *>;
84
85 BBMapTy BBMap;
86 BumpPtrAllocator Allocator;
87
88public:
89 explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
91 Updater(U), AvailableVals(A), InsertedPHIs(Ins) {}
92
93 /// GetValue - Check to see if AvailableVals has an entry for the specified
94 /// BB and if so, return it. If not, construct SSA form by first
95 /// calculating the required placement of PHIs and then inserting new PHIs
96 /// where needed.
97 ValT GetValue(BlkT *BB) {
99 BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
100
101 // Special case: bail out if BB is unreachable.
102 if (BlockList.size() == 0) {
103 ValT V = Traits::GetPoisonVal(BB, Updater);
104 (*AvailableVals)[BB] = V;
105 return V;
106 }
107
108 FindDominators(&BlockList, PseudoEntry);
109 FindPHIPlacement(&BlockList);
110 FindAvailableVals(&BlockList);
111
112 return BBMap[BB]->DefBB->AvailableVal;
113 }
114
115 /// BuildBlockList - Starting from the specified basic block, traverse back
116 /// through its predecessors until reaching blocks with known values.
117 /// Create BBInfo structures for the blocks and append them to the block
118 /// list.
119 BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
122
123 BBInfo *Info = new (Allocator) BBInfo(BB, 0);
124 BBMap[BB] = Info;
125 WorkList.push_back(Info);
126
127 // Search backward from BB, creating BBInfos along the way and stopping
128 // when reaching blocks that define the value. Record those defining
129 // blocks on the RootList.
131 while (!WorkList.empty()) {
132 Info = WorkList.pop_back_val();
133 Preds.clear();
134 Traits::FindPredecessorBlocks(Info->BB, &Preds);
135 Info->NumPreds = Preds.size();
136 if (Info->NumPreds == 0)
137 Info->Preds = nullptr;
138 else
139 Info->Preds = static_cast<BBInfo **>(Allocator.Allocate(
140 Info->NumPreds * sizeof(BBInfo *), alignof(BBInfo *)));
141
142 for (unsigned p = 0; p != Info->NumPreds; ++p) {
143 BlkT *Pred = Preds[p];
144 // Check if BBMap already has a BBInfo for the predecessor block.
145 BBInfo *&BBMapBucket = BBMap[Pred];
146 if (BBMapBucket) {
147 Info->Preds[p] = BBMapBucket;
148 continue;
149 }
150
151 // Create a new BBInfo for the predecessor.
152 ValT PredVal = AvailableVals->lookup(Pred);
153 BBInfo *PredInfo = new (Allocator) BBInfo(Pred, PredVal);
154 BBMapBucket = PredInfo;
155 Info->Preds[p] = PredInfo;
156
157 if (PredInfo->AvailableVal) {
158 RootList.push_back(PredInfo);
159 continue;
160 }
161 WorkList.push_back(PredInfo);
162 }
163 }
164
165 // Now that we know what blocks are backwards-reachable from the starting
166 // block, do a forward depth-first traversal to assign postorder numbers
167 // to those blocks.
168 BBInfo *PseudoEntry = new (Allocator) BBInfo(nullptr, 0);
169 unsigned BlkNum = 1;
170
171 // Initialize the worklist with the roots from the backward traversal.
172 while (!RootList.empty()) {
173 Info = RootList.pop_back_val();
174 Info->IDom = PseudoEntry;
175 Info->BlkNum = -1;
176 WorkList.push_back(Info);
177 }
178
179 while (!WorkList.empty()) {
180 Info = WorkList.back();
181
182 if (Info->BlkNum == -2) {
183 // All the successors have been handled; assign the postorder number.
184 Info->BlkNum = BlkNum++;
185 // If not a root, put it on the BlockList.
186 if (!Info->AvailableVal)
187 BlockList->push_back(Info);
188 WorkList.pop_back();
189 continue;
190 }
191
192 // Leave this entry on the worklist, but set its BlkNum to mark that its
193 // successors have been put on the worklist. When it returns to the top
194 // the list, after handling its successors, it will be assigned a
195 // number.
196 Info->BlkNum = -2;
197
198 // Add unvisited successors to the work list.
199 for (typename Traits::BlkSucc_iterator SI =
200 Traits::BlkSucc_begin(Info->BB),
201 E = Traits::BlkSucc_end(Info->BB); SI != E; ++SI) {
202 BBInfo *SuccInfo = BBMap[*SI];
203 if (!SuccInfo || SuccInfo->BlkNum)
204 continue;
205 SuccInfo->BlkNum = -1;
206 WorkList.push_back(SuccInfo);
207 }
208 }
209 PseudoEntry->BlkNum = BlkNum;
210 return PseudoEntry;
211 }
212
213 /// IntersectDominators - This is the dataflow lattice "meet" operation for
214 /// finding dominators. Given two basic blocks, it walks up the dominator
215 /// tree until it finds a common dominator of both. It uses the postorder
216 /// number of the blocks to determine how to do that.
217 BBInfo *IntersectDominators(BBInfo *Blk1, BBInfo *Blk2) {
218 while (Blk1 != Blk2) {
219 while (Blk1->BlkNum < Blk2->BlkNum) {
220 Blk1 = Blk1->IDom;
221 if (!Blk1)
222 return Blk2;
223 }
224 while (Blk2->BlkNum < Blk1->BlkNum) {
225 Blk2 = Blk2->IDom;
226 if (!Blk2)
227 return Blk1;
228 }
229 }
230 return Blk1;
231 }
232
233 /// FindDominators - Calculate the dominator tree for the subset of the CFG
234 /// corresponding to the basic blocks on the BlockList. This uses the
235 /// algorithm from: "A Simple, Fast Dominance Algorithm" by Cooper, Harvey
236 /// and Kennedy, published in Software--Practice and Experience, 2001,
237 /// 4:1-10. Because the CFG subset does not include any edges leading into
238 /// blocks that define the value, the results are not the usual dominator
239 /// tree. The CFG subset has a single pseudo-entry node with edges to a set
240 /// of root nodes for blocks that define the value. The dominators for this
241 /// subset CFG are not the standard dominators but they are adequate for
242 /// placing PHIs within the subset CFG.
243 void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry) {
244 bool Changed;
245 do {
246 Changed = false;
247 // Iterate over the list in reverse order, i.e., forward on CFG edges.
248 for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
249 E = BlockList->rend(); I != E; ++I) {
250 BBInfo *Info = *I;
251 BBInfo *NewIDom = nullptr;
252
253 // Iterate through the block's predecessors.
254 for (unsigned p = 0; p != Info->NumPreds; ++p) {
255 BBInfo *Pred = Info->Preds[p];
256
257 // Treat an unreachable predecessor as a definition with 'poison'.
258 if (Pred->BlkNum == 0) {
259 Pred->AvailableVal = Traits::GetPoisonVal(Pred->BB, Updater);
260 (*AvailableVals)[Pred->BB] = Pred->AvailableVal;
261 Pred->DefBB = Pred;
262 Pred->BlkNum = PseudoEntry->BlkNum;
263 PseudoEntry->BlkNum++;
264 }
265
266 if (!NewIDom)
267 NewIDom = Pred;
268 else
269 NewIDom = IntersectDominators(NewIDom, Pred);
270 }
271
272 // Check if the IDom value has changed.
273 if (NewIDom && NewIDom != Info->IDom) {
274 Info->IDom = NewIDom;
275 Changed = true;
276 }
277 }
278 } while (Changed);
279 }
280
281 /// IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for
282 /// any blocks containing definitions of the value. If one is found, then
283 /// the successor of Pred is in the dominance frontier for the definition,
284 /// and this function returns true.
285 bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom) {
286 for (; Pred != IDom; Pred = Pred->IDom) {
287 if (Pred->DefBB == Pred)
288 return true;
289 }
290 return false;
291 }
292
293 /// FindPHIPlacement - PHIs are needed in the iterated dominance frontiers
294 /// of the known definitions. Iteratively add PHIs in the dom frontiers
295 /// until nothing changes. Along the way, keep track of the nearest
296 /// dominating definitions for non-PHI blocks.
297 void FindPHIPlacement(BlockListTy *BlockList) {
298 bool Changed;
299 do {
300 Changed = false;
301 // Iterate over the list in reverse order, i.e., forward on CFG edges.
302 for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
303 E = BlockList->rend(); I != E; ++I) {
304 BBInfo *Info = *I;
305
306 // If this block already needs a PHI, there is nothing to do here.
307 if (Info->DefBB == Info)
308 continue;
309
310 // Default to use the same def as the immediate dominator.
311 BBInfo *NewDefBB = Info->IDom->DefBB;
312 for (unsigned p = 0; p != Info->NumPreds; ++p) {
313 if (IsDefInDomFrontier(Info->Preds[p], Info->IDom)) {
314 // Need a PHI here.
315 NewDefBB = Info;
316 break;
317 }
318 }
319
320 // Check if anything changed.
321 if (NewDefBB != Info->DefBB) {
322 Info->DefBB = NewDefBB;
323 Changed = true;
324 }
325 }
326 } while (Changed);
327 }
328
329 /// Check all predecessors and if all of them have the same AvailableVal use
330 /// it as value for block represented by Info. Return true if singluar value
331 /// is found.
332 bool FindSingularVal(BBInfo *Info) {
333 if (!Info->NumPreds)
334 return false;
335 ValT Singular = Info->Preds[0]->DefBB->AvailableVal;
336 if (!Singular)
337 return false;
338 for (unsigned Idx = 1; Idx < Info->NumPreds; ++Idx) {
339 ValT PredVal = Info->Preds[Idx]->DefBB->AvailableVal;
340 if (!PredVal || Singular != PredVal)
341 return false;
342 }
343 // Record Singular value.
344 (*AvailableVals)[Info->BB] = Singular;
345 assert(BBMap[Info->BB] == Info && "Info missed in BBMap?");
346 Info->AvailableVal = Singular;
347 Info->DefBB = Info->Preds[0]->DefBB;
348 return true;
349 }
350
351 /// FindAvailableVal - If this block requires a PHI, first check if an
352 /// existing PHI matches the PHI placement and reaching definitions computed
353 /// earlier, and if not, create a new PHI. Visit all the block's
354 /// predecessors to calculate the available value for each one and fill in
355 /// the incoming values for a new PHI.
356 void FindAvailableVals(BlockListTy *BlockList) {
357 // Go through the worklist in forward order (i.e., backward through the CFG)
358 // and check if existing PHIs can be used. If not, create empty PHIs where
359 // they are needed.
360 for (typename BlockListTy::iterator I = BlockList->begin(),
361 E = BlockList->end(); I != E; ++I) {
362 BBInfo *Info = *I;
363 // Check if there needs to be a PHI in BB.
364 if (Info->DefBB != Info)
365 continue;
366
367 // Look for singular value.
368 if (FindSingularVal(Info))
369 continue;
370
371 // Look for an existing PHI.
372 FindExistingPHI(Info->BB);
373 if (Info->AvailableVal)
374 continue;
375
376 ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
377 Info->AvailableVal = PHI;
378 (*AvailableVals)[Info->BB] = PHI;
379 }
380
381 // Now go back through the worklist in reverse order to fill in the
382 // arguments for any new PHIs added in the forward traversal.
383 for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
384 E = BlockList->rend(); I != E; ++I) {
385 BBInfo *Info = *I;
386
387 if (Info->DefBB != Info) {
388 // Record the available value to speed up subsequent uses of this
389 // SSAUpdater for the same value.
390 (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
391 continue;
392 }
393
394 // Check if this block contains a newly added PHI.
395 PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
396 if (!PHI)
397 continue;
398
399 // Iterate through the block's predecessors.
400 for (unsigned p = 0; p != Info->NumPreds; ++p) {
401 BBInfo *PredInfo = Info->Preds[p];
402 BlkT *Pred = PredInfo->BB;
403 // Skip to the nearest preceding definition.
404 if (PredInfo->DefBB != PredInfo)
405 PredInfo = PredInfo->DefBB;
406 Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
407 }
408
409 LLVM_DEBUG(dbgs() << " Inserted PHI: " << *PHI << "\n");
410
411 // If the client wants to know about all new instructions, tell it.
412 if (InsertedPHIs) InsertedPHIs->push_back(PHI);
413 }
414 }
415
416 /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
417 /// them match what is needed.
418 void FindExistingPHI(BlkT *BB) {
419 SmallVector<BBInfo *, 20> TaggedBlocks;
420 // SSAUpdaterPhiSearchLimit is needed to guard against pathological cases
421 // (e.g. AMDGPU/large-phi-search.ll) where a large number of searches are
422 // done which all fail. Each search adds another PHI node to be searched.
423 // In a 3-stage build of LLVM the maximum search length was 53.
424 unsigned Count = 0;
425
426 for (auto &SomePHI : BB->phis()) {
427 // Abandon search for match. FindAvailableVals will create a new
428 // phi-node.
430 break;
431 if (CheckIfPHIMatches(&SomePHI, TaggedBlocks)) {
432 RecordMatchingPHIs(TaggedBlocks);
433 break;
434 }
435 }
436 }
437
438 /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
439 /// in the BBMap.
440 bool CheckIfPHIMatches(PhiT *PHI, BlockListTy &TaggedBlocks) {
441 // Match failed: clear all the PHITag values. Only need to clear visited
442 // blocks.
443 scope_exit Cleanup([&]() {
444 for (BBInfo *TaggedBlock : TaggedBlocks)
445 TaggedBlock->PHITag = nullptr;
446 TaggedBlocks.clear();
447 });
448
450 WorkList.push_back(PHI);
451
452 // Mark that the block containing this PHI has been visited.
453 BBInfo *PHIBlock = BBMap[PHI->getParent()];
454 PHIBlock->PHITag = PHI;
455 TaggedBlocks.push_back(PHIBlock);
456
457 while (!WorkList.empty()) {
458 PHI = WorkList.pop_back_val();
459
460 // Iterate through the PHI's incoming values.
461 for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
462 E = Traits::PHI_end(PHI); I != E; ++I) {
463 ValT IncomingVal = I.getIncomingValue();
464 BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
465 // Skip to the nearest preceding definition.
466 if (PredInfo->DefBB != PredInfo)
467 PredInfo = PredInfo->DefBB;
468
469 // Check if it matches the expected value.
470 if (PredInfo->AvailableVal) {
471 if (IncomingVal == PredInfo->AvailableVal)
472 continue;
473 return false;
474 }
475
476 // Check if the value is a PHI in the correct block.
477 PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
478 if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
479 return false;
480
481 // If this block has already been visited, check if this PHI matches.
482 if (PredInfo->PHITag) {
483 if (IncomingPHIVal == PredInfo->PHITag)
484 continue;
485 return false;
486 }
487 PredInfo->PHITag = IncomingPHIVal;
488 TaggedBlocks.push_back(PredInfo);
489
490 WorkList.push_back(IncomingPHIVal);
491 }
492 }
493 // Match found, keep PHITags.
494 Cleanup.release();
495 return true;
496 }
497
498 /// RecordMatchingPHIs - For each PHI node that matches, record it in both
499 /// the BBMap and the AvailableVals mapping.
500 void RecordMatchingPHIs(BlockListTy &TaggedBlocks) {
501 for (BBInfo *Block : TaggedBlocks) {
502 PhiT *PHI = Block->PHITag;
503 assert(PHI && "PHITag didn't set?");
504 BlkT *BB = PHI->getParent();
505 ValT PHIVal = Traits::GetPHIValue(PHI);
506 (*AvailableVals)[BB] = PHIVal;
507 BBMap[BB]->AvailableVal = PHIVal;
508 }
509 }
510};
511
512} // end namespace llvm
513
514#undef DEBUG_TYPE // "ssaupdater"
515
516#endif // LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
ManagedStatic< HTTPClientCleanup > Cleanup
#define I(x, y, z)
Definition MD5.cpp:57
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry)
FindDominators - Calculate the dominator tree for the subset of the CFG corresponding to the basic bl...
void FindAvailableVals(BlockListTy *BlockList)
FindAvailableVal - If this block requires a PHI, first check if an existing PHI matches the PHI place...
bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom)
IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for any blocks containing definit...
ValT GetValue(BlkT *BB)
GetValue - Check to see if AvailableVals has an entry for the specified BB and if so,...
SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A, SmallVectorImpl< PhiT * > *Ins)
BBInfo * BuildBlockList(BlkT *BB, BlockListTy *BlockList)
BuildBlockList - Starting from the specified basic block, traverse back through its predecessors unti...
bool FindSingularVal(BBInfo *Info)
Check all predecessors and if all of them have the same AvailableVal use it as value for block repres...
void FindPHIPlacement(BlockListTy *BlockList)
FindPHIPlacement - PHIs are needed in the iterated dominance frontiers of the known definitions.
void FindExistingPHI(BlkT *BB)
FindExistingPHI - Look through the PHI nodes in a block to see if any of them match what is needed.
BBInfo * IntersectDominators(BBInfo *Blk1, BBInfo *Blk2)
IntersectDominators - This is the dataflow lattice "meet" operation for finding dominators.
void RecordMatchingPHIs(BlockListTy &TaggedBlocks)
RecordMatchingPHIs - For each PHI node that matches, record it in both the BBMap and the AvailableVal...
bool CheckIfPHIMatches(PhiT *PHI, BlockListTy &TaggedBlocks)
CheckIfPHIMatches - Check if a PHI node matches the placement and values in the BBMap.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::iterator iterator
void push_back(const T &Elt)
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Changed
template class LLVM_TEMPLATE_ABI opt< unsigned >
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< unsigned > SSAUpdaterPhiSearchLimit
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383