blob: 5af1e4d856f9e6f17e675c72be69a94efdc0a908 [file] [log] [blame]
Artem Serov7f4aff62017-06-21 17:02:18 +01001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_COMPILER_OPTIMIZING_SUPERBLOCK_CLONER_H_
18#define ART_COMPILER_OPTIMIZING_SUPERBLOCK_CLONER_H_
19
20#include "base/arena_bit_vector.h"
21#include "base/arena_containers.h"
22#include "base/bit_vector-inl.h"
23#include "nodes.h"
24
Vladimir Marko0a516052019-10-14 13:00:44 +000025namespace art {
Artem Serov7f4aff62017-06-21 17:02:18 +010026
Nicolas Geoffray256c94b2019-04-29 10:55:09 +010027class InductionVarRange;
28
Artem Serov7f4aff62017-06-21 17:02:18 +010029static const bool kSuperblockClonerLogging = false;
Artem Serovc8150b52019-07-31 18:28:00 +010030static const bool kSuperblockClonerVerify = false;
Artem Serov7f4aff62017-06-21 17:02:18 +010031
32// Represents an edge between two HBasicBlocks.
33//
34// Note: objects of this class are small - pass them by value.
35class HEdge : public ArenaObject<kArenaAllocSuperblockCloner> {
36 public:
37 HEdge(HBasicBlock* from, HBasicBlock* to) : from_(from->GetBlockId()), to_(to->GetBlockId()) {
38 DCHECK_NE(to_, kInvalidBlockId);
39 DCHECK_NE(from_, kInvalidBlockId);
40 }
41 HEdge(uint32_t from, uint32_t to) : from_(from), to_(to) {
42 DCHECK_NE(to_, kInvalidBlockId);
43 DCHECK_NE(from_, kInvalidBlockId);
44 }
45 HEdge() : from_(kInvalidBlockId), to_(kInvalidBlockId) {}
46
47 uint32_t GetFrom() const { return from_; }
48 uint32_t GetTo() const { return to_; }
49
50 bool operator==(const HEdge& other) const {
51 return this->from_ == other.from_ && this->to_ == other.to_;
52 }
53
54 bool operator!=(const HEdge& other) const { return !operator==(other); }
55 void Dump(std::ostream& stream) const;
56
57 // Returns whether an edge represents a valid edge in CF graph: whether the from_ block
58 // has to_ block as a successor.
59 bool IsValid() const { return from_ != kInvalidBlockId && to_ != kInvalidBlockId; }
60
61 private:
62 // Predecessor block id.
63 uint32_t from_;
64 // Successor block id.
65 uint32_t to_;
66};
67
68// Returns whether a HEdge edge corresponds to an existing edge in the graph.
69inline bool IsEdgeValid(HEdge edge, HGraph* graph) {
70 if (!edge.IsValid()) {
71 return false;
72 }
73 uint32_t from = edge.GetFrom();
74 uint32_t to = edge.GetTo();
75 if (from >= graph->GetBlocks().size() || to >= graph->GetBlocks().size()) {
76 return false;
77 }
78
79 HBasicBlock* block_from = graph->GetBlocks()[from];
80 HBasicBlock* block_to = graph->GetBlocks()[to];
81 if (block_from == nullptr || block_to == nullptr) {
82 return false;
83 }
84
85 return block_from->HasSuccessor(block_to, 0);
86}
87
88// SuperblockCloner provides a feature of cloning subgraphs in a smart, high level way without
89// fine grain manipulation with IR; data flow and graph properties are resolved/adjusted
90// automatically. The clone transformation is defined by specifying a set of basic blocks to copy
91// and a set of rules how to treat edges, remap their successors. By using this approach such
92// optimizations as Branch Target Expansion, Loop Peeling, Loop Unrolling can be implemented.
93//
94// The idea of the transformation is based on "Superblock cloning" technique described in the book
95// "Engineering a Compiler. Second Edition", Keith D. Cooper, Linda Torczon, Rice University
96// Houston, Texas. 2nd edition, Morgan Kaufmann. The original paper is "The Superblock: An Efective
97// Technique for VLIW and Superscalar Compilation" by Hwu, W.M.W., Mahlke, S.A., Chen, W.Y. et al.
98// J Supercomput (1993) 7: 229. doi:10.1007/BF01205185.
99//
100// There are two states of the IR graph: original graph (before the transformation) and
101// copy graph (after).
102//
103// Before the transformation:
104// Defining a set of basic block to copy (orig_bb_set) partitions all of the edges in the original
105// graph into 4 categories/sets (use the following notation for edges: "(pred, succ)",
106// where pred, succ - basic blocks):
107// - internal - pred, succ are members of ‘orig_bb_set’.
108// - outside - pred, succ are not members of ‘orig_bb_set’.
109// - incoming - pred is not a member of ‘orig_bb_set’, succ is.
110// - outgoing - pred is a member of ‘orig_bb_set’, succ is not.
111//
112// Transformation:
113//
114// 1. Initial cloning:
115// 1.1. For each ‘orig_block’ in orig_bb_set create a copy ‘copy_block’; these new blocks
116// form ‘copy_bb_set’.
117// 1.2. For each edge (X, Y) from internal set create an edge (X_1, Y_1) where X_1, Y_1 are the
118// copies of X, Y basic blocks correspondingly; these new edges form ‘copy_internal’ edge
119// set.
120// 1.3. For each edge (X, Y) from outgoing set create an edge (X_1, Y_1) where X_1, Y_1 are the
121// copies of X, Y basic blocks correspondingly; these new edges form ‘copy_outgoing’ edge
122// set.
123// 2. Successors remapping.
124// 2.1. 'remap_orig_internal’ - set of edges (X, Y) from ‘orig_bb_set’ whose successors should
125// be remapped to copy nodes: ((X, Y) will be transformed into (X, Y_1)).
126// 2.2. ‘remap_copy_internal’ - set of edges (X_1, Y_1) from ‘copy_bb_set’ whose successors
127// should be remapped to copy nodes: (X_1, Y_1) will be transformed into (X_1, Y)).
128// 2.3. 'remap_incoming’ - set of edges (X, Y) from the ‘incoming’ edge set in the original graph
129// whose successors should be remapped to copies nodes: ((X, Y) will be transformed into
130// (X, Y_1)).
131// 3. Adjust control flow structures and relations (dominance, reverse post order, loops, etc).
132// 4. Fix/resolve data flow.
133// 5. Do cleanups (DCE, critical edges splitting, etc).
134//
135class SuperblockCloner : public ValueObject {
136 public:
137 // TODO: Investigate optimal types for the containers.
138 using HBasicBlockMap = ArenaSafeMap<HBasicBlock*, HBasicBlock*>;
139 using HInstructionMap = ArenaSafeMap<HInstruction*, HInstruction*>;
140 using HBasicBlockSet = ArenaBitVector;
141 using HEdgeSet = ArenaHashSet<HEdge>;
142
143 SuperblockCloner(HGraph* graph,
144 const HBasicBlockSet* orig_bb_set,
145 HBasicBlockMap* bb_map,
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100146 HInstructionMap* hir_map,
147 InductionVarRange* induction_range);
Artem Serov7f4aff62017-06-21 17:02:18 +0100148
149 // Sets edge successor remapping info specified by corresponding edge sets.
150 void SetSuccessorRemappingInfo(const HEdgeSet* remap_orig_internal,
151 const HEdgeSet* remap_copy_internal,
152 const HEdgeSet* remap_incoming);
153
154 // Returns whether the specified subgraph is copyable.
155 // TODO: Start from small range of graph patterns then extend it.
156 bool IsSubgraphClonable() const;
157
Artem Serov02eebcf2017-12-13 19:48:31 +0000158 // Returns whether selected subgraph satisfies the criteria for fast data flow resolution
159 // when iterative DF algorithm is not required and dominators/instructions inputs can be
160 // trivially adjusted.
161 //
162 // TODO: formally describe the criteria.
163 //
164 // Loop peeling and unrolling satisfy the criteria.
165 bool IsFastCase() const;
166
Artem Serov7f4aff62017-06-21 17:02:18 +0100167 // Runs the copy algorithm according to the description.
168 void Run();
169
170 // Cleans up the graph after transformation: splits critical edges, recalculates control flow
171 // information (back-edges, dominators, loop info, etc), eliminates redundant phis.
172 void CleanUp();
173
174 // Returns a clone of a basic block (orig_block).
175 //
176 // - The copy block will have no successors/predecessors; they should be set up manually.
177 // - For each instruction in the orig_block a copy is created and inserted into the copy block;
178 // this correspondence is recorded in the map (old instruction, new instruction).
179 // - Graph HIR is not valid after this transformation: all of the HIRs have their inputs the
180 // same, as in the original block, PHIs do not reflect a correct correspondence between the
181 // value and predecessors (as the copy block has no predecessors by now), etc.
182 HBasicBlock* CloneBasicBlock(const HBasicBlock* orig_block);
183
184 // Creates a clone for each basic blocks in orig_bb_set adding corresponding entries into bb_map_
185 // and hir_map_.
186 void CloneBasicBlocks();
187
188 HInstruction* GetInstrCopy(HInstruction* orig_instr) const {
189 auto copy_input_iter = hir_map_->find(orig_instr);
190 DCHECK(copy_input_iter != hir_map_->end());
191 return copy_input_iter->second;
192 }
193
194 HBasicBlock* GetBlockCopy(HBasicBlock* orig_block) const {
195 HBasicBlock* block = bb_map_->Get(orig_block);
196 DCHECK(block != nullptr);
197 return block;
198 }
199
200 HInstruction* GetInstrOrig(HInstruction* copy_instr) const {
201 for (auto it : *hir_map_) {
202 if (it.second == copy_instr) {
203 return it.first;
204 }
205 }
206 return nullptr;
207 }
208
209 bool IsInOrigBBSet(uint32_t block_id) const {
210 return orig_bb_set_.IsBitSet(block_id);
211 }
212
213 bool IsInOrigBBSet(const HBasicBlock* block) const {
214 return IsInOrigBBSet(block->GetBlockId());
215 }
216
Artem Serov02eebcf2017-12-13 19:48:31 +0000217 // Returns the area (the most outer loop) in the graph for which control flow (back edges, loops,
218 // dominators) needs to be adjusted.
219 HLoopInformation* GetRegionToBeAdjusted() const {
220 return outer_loop_;
221 }
222
Artem Serov7f4aff62017-06-21 17:02:18 +0100223 private:
224 // Fills the 'exits' vector with the subgraph exits.
Artem Serovca210e32017-12-15 13:43:20 +0000225 void SearchForSubgraphExits(ArenaVector<HBasicBlock*>* exits) const;
Artem Serov7f4aff62017-06-21 17:02:18 +0100226
Artem Serov02eebcf2017-12-13 19:48:31 +0000227 // Finds and records information about the area in the graph for which control flow (back edges,
Artem Serov7f4aff62017-06-21 17:02:18 +0100228 // loops, dominators) needs to be adjusted.
229 void FindAndSetLocalAreaForAdjustments();
230
231 // Remaps edges' successors according to the info specified in the edges sets.
232 //
233 // Only edge successors/predecessors and phis' input records (to have a correspondence between
234 // a phi input record (not value) and a block's predecessor) are adjusted at this stage: neither
235 // phis' nor instructions' inputs values are resolved.
236 void RemapEdgesSuccessors();
237
Artem Serov02eebcf2017-12-13 19:48:31 +0000238 // Adjusts control flow (back edges, loops, dominators) for the local area defined by
Artem Serov7f4aff62017-06-21 17:02:18 +0100239 // FindAndSetLocalAreaForAdjustments.
240 void AdjustControlFlowInfo();
241
242 // Resolves Data Flow - adjusts phis' and instructions' inputs in order to have a valid graph in
243 // the SSA form.
244 void ResolveDataFlow();
245
246 //
Artem Serovca210e32017-12-15 13:43:20 +0000247 // Helpers for live-outs processing and Subgraph-closed SSA.
248 //
249 // - live-outs - values which are defined inside the subgraph and have uses outside.
250 // - Subgraph-closed SSA - SSA form for which all the values defined inside the subgraph
251 // have no outside uses except for the phi-nodes in the subgraph exits.
252 //
253 // Note: now if the subgraph has live-outs it is only clonable if it has a single exit; this
254 // makes the subgraph-closed SSA form construction much easier.
255 //
256 // TODO: Support subgraphs with live-outs and multiple exits.
257 //
258
259 // For each live-out value 'val' in the region puts a record <val, val> into the map.
260 // Returns whether all of the instructions in the subgraph are clonable.
261 bool CollectLiveOutsAndCheckClonable(HInstructionMap* live_outs_) const;
262
263 // Constructs Subgraph-closed SSA; precondition - a subgraph has a single exit.
264 //
265 // For each live-out 'val' in 'live_outs_' map inserts a HPhi 'phi' into the exit node, updates
266 // the record in the map to <val, phi> and replaces all outside uses with this phi.
267 void ConstructSubgraphClosedSSA();
268
269 // Fixes the data flow for the live-out 'val' by adding a 'copy_val' input to the corresponding
270 // (<val, phi>) phi after the cloning is done.
271 void FixSubgraphClosedSSAAfterCloning();
272
273 //
Artem Serov7f4aff62017-06-21 17:02:18 +0100274 // Helpers for CloneBasicBlock.
275 //
276
277 // Adjusts copy instruction's inputs: if the input of the original instruction is defined in the
278 // orig_bb_set, replaces it with a corresponding copy otherwise leaves it the same as original.
279 void ReplaceInputsWithCopies(HInstruction* copy_instr);
280
281 // Recursively clones the environment for the copy instruction. If the input of the original
282 // environment is defined in the orig_bb_set, replaces it with a corresponding copy otherwise
283 // leaves it the same as original.
284 void DeepCloneEnvironmentWithRemapping(HInstruction* copy_instr, const HEnvironment* orig_env);
285
286 //
287 // Helpers for RemapEdgesSuccessors.
288 //
289
290 // Remaps incoming or original internal edge to its copy, adjusts the phi inputs in orig_succ and
291 // copy_succ.
292 void RemapOrigInternalOrIncomingEdge(HBasicBlock* orig_block, HBasicBlock* orig_succ);
293
294 // Adds copy internal edge (from copy_block to copy_succ), updates phis in the copy_succ.
295 void AddCopyInternalEdge(HBasicBlock* orig_block, HBasicBlock* orig_succ);
296
297 // Remaps copy internal edge to its origin, adjusts the phi inputs in orig_succ.
298 void RemapCopyInternalEdge(HBasicBlock* orig_block, HBasicBlock* orig_succ);
299
300 //
301 // Local versions of control flow calculation/adjustment routines.
302 //
303
304 void FindBackEdgesLocal(HBasicBlock* entry_block, ArenaBitVector* local_set);
305 void RecalculateBackEdgesInfo(ArenaBitVector* outer_loop_bb_set);
306 GraphAnalysisResult AnalyzeLoopsLocally(ArenaBitVector* outer_loop_bb_set);
307 void CleanUpControlFlow();
308
309 //
310 // Helpers for ResolveDataFlow
311 //
312
313 // Resolves the inputs of the phi.
314 void ResolvePhi(HPhi* phi);
315
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100316 // Update induction range after when fixing SSA.
317 void UpdateInductionRangeInfoOf(
318 HInstruction* user, HInstruction* old_instruction, HInstruction* replacement);
319
Artem Serov7f4aff62017-06-21 17:02:18 +0100320 //
321 // Debug and logging methods.
322 //
323 void CheckInstructionInputsRemapping(HInstruction* orig_instr);
Artem Serov02eebcf2017-12-13 19:48:31 +0000324 bool CheckRemappingInfoIsValid();
325 void VerifyGraph();
326 void DumpInputSets();
Artem Serov7f4aff62017-06-21 17:02:18 +0100327
328 HBasicBlock* GetBlockById(uint32_t block_id) const {
329 DCHECK(block_id < graph_->GetBlocks().size());
330 HBasicBlock* block = graph_->GetBlocks()[block_id];
331 DCHECK(block != nullptr);
332 return block;
333 }
334
335 HGraph* const graph_;
336 ArenaAllocator* const arena_;
337
338 // Set of basic block in the original graph to be copied.
339 HBasicBlockSet orig_bb_set_;
340
341 // Sets of edges which require successors remapping.
342 const HEdgeSet* remap_orig_internal_;
343 const HEdgeSet* remap_copy_internal_;
344 const HEdgeSet* remap_incoming_;
345
346 // Correspondence map for blocks: (original block, copy block).
347 HBasicBlockMap* bb_map_;
348 // Correspondence map for instructions: (original HInstruction, copy HInstruction).
349 HInstructionMap* hir_map_;
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100350 // As a result of cloning, the induction range analysis information can be invalidated
351 // and must be updated. If not null, the cloner updates it for changed instructions.
352 InductionVarRange* induction_range_;
Artem Serov02eebcf2017-12-13 19:48:31 +0000353 // Area in the graph for which control flow (back edges, loops, dominators) needs to be adjusted.
Artem Serov7f4aff62017-06-21 17:02:18 +0100354 HLoopInformation* outer_loop_;
355 HBasicBlockSet outer_loop_bb_set_;
356
Artem Serovca210e32017-12-15 13:43:20 +0000357 HInstructionMap live_outs_;
358
Artem Serov7f4aff62017-06-21 17:02:18 +0100359 ART_FRIEND_TEST(SuperblockClonerTest, AdjustControlFlowInfo);
Artem Serov02eebcf2017-12-13 19:48:31 +0000360 ART_FRIEND_TEST(SuperblockClonerTest, IsGraphConnected);
Artem Serov7f4aff62017-06-21 17:02:18 +0100361
362 DISALLOW_COPY_AND_ASSIGN(SuperblockCloner);
363};
364
Artem Serov02eebcf2017-12-13 19:48:31 +0000365// Helper class to perform loop peeling/unrolling.
366//
367// This helper should be used when correspondence map between original and copied
368// basic blocks/instructions are demanded.
369class PeelUnrollHelper : public ValueObject {
370 public:
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100371 PeelUnrollHelper(HLoopInformation* info,
372 SuperblockCloner::HBasicBlockMap* bb_map,
373 SuperblockCloner::HInstructionMap* hir_map,
374 InductionVarRange* induction_range) :
Artem Serov02eebcf2017-12-13 19:48:31 +0000375 loop_info_(info),
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100376 cloner_(info->GetHeader()->GetGraph(), &info->GetBlocks(), bb_map, hir_map, induction_range) {
Artem Serov02eebcf2017-12-13 19:48:31 +0000377 // For now do peeling/unrolling only for natural loops.
378 DCHECK(!info->IsIrreducible());
379 }
380
381 // Returns whether the loop can be peeled/unrolled (static function).
382 static bool IsLoopClonable(HLoopInformation* loop_info);
383
384 // Returns whether the loop can be peeled/unrolled.
385 bool IsLoopClonable() const { return cloner_.IsSubgraphClonable(); }
386
Andreas Gampe3db70682018-12-26 15:12:03 -0800387 HBasicBlock* DoPeeling() { return DoPeelUnrollImpl(/* to_unroll= */ false); }
388 HBasicBlock* DoUnrolling() { return DoPeelUnrollImpl(/* to_unroll= */ true); }
Artem Serov02eebcf2017-12-13 19:48:31 +0000389 HLoopInformation* GetRegionToBeAdjusted() const { return cloner_.GetRegionToBeAdjusted(); }
390
391 protected:
392 // Applies loop peeling/unrolling for the loop specified by 'loop_info'.
393 //
394 // Depending on 'do_unroll' either unrolls loop by 2 or peels one iteration from it.
395 HBasicBlock* DoPeelUnrollImpl(bool to_unroll);
396
397 private:
398 HLoopInformation* loop_info_;
399 SuperblockCloner cloner_;
400
401 DISALLOW_COPY_AND_ASSIGN(PeelUnrollHelper);
402};
403
404// Helper class to perform loop peeling/unrolling.
405//
406// This helper should be used when there is no need to get correspondence information between
407// original and copied basic blocks/instructions.
408class PeelUnrollSimpleHelper : public ValueObject {
409 public:
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100410 PeelUnrollSimpleHelper(HLoopInformation* info, InductionVarRange* induction_range);
Artem Serov02eebcf2017-12-13 19:48:31 +0000411 bool IsLoopClonable() const { return helper_.IsLoopClonable(); }
412 HBasicBlock* DoPeeling() { return helper_.DoPeeling(); }
413 HBasicBlock* DoUnrolling() { return helper_.DoUnrolling(); }
414 HLoopInformation* GetRegionToBeAdjusted() const { return helper_.GetRegionToBeAdjusted(); }
415
Artem Serov72411e62017-10-19 16:18:07 +0100416 const SuperblockCloner::HBasicBlockMap* GetBasicBlockMap() const { return &bb_map_; }
417 const SuperblockCloner::HInstructionMap* GetInstructionMap() const { return &hir_map_; }
418
Artem Serov02eebcf2017-12-13 19:48:31 +0000419 private:
420 SuperblockCloner::HBasicBlockMap bb_map_;
421 SuperblockCloner::HInstructionMap hir_map_;
422 PeelUnrollHelper helper_;
423
424 DISALLOW_COPY_AND_ASSIGN(PeelUnrollSimpleHelper);
425};
426
427// Collects edge remapping info for loop peeling/unrolling for the loop specified by loop info.
428void CollectRemappingInfoForPeelUnroll(bool to_unroll,
429 HLoopInformation* loop_info,
430 SuperblockCloner::HEdgeSet* remap_orig_internal,
431 SuperblockCloner::HEdgeSet* remap_copy_internal,
432 SuperblockCloner::HEdgeSet* remap_incoming);
433
434// Returns whether blocks from 'work_set' are reachable from the rest of the graph.
435//
436// Returns whether such a set 'outer_entries' of basic blocks exists that:
437// - each block from 'outer_entries' is not from 'work_set'.
438// - each block from 'work_set' is reachable from at least one block from 'outer_entries'.
439//
440// After the function returns work_set contains only blocks from the original 'work_set'
441// which are unreachable from the rest of the graph.
442bool IsSubgraphConnected(SuperblockCloner::HBasicBlockSet* work_set, HGraph* graph);
443
444// Returns a common predecessor of loop1 and loop2 in the loop tree or nullptr if it is the whole
445// graph.
446HLoopInformation* FindCommonLoop(HLoopInformation* loop1, HLoopInformation* loop2);
Artem Serov7f4aff62017-06-21 17:02:18 +0100447} // namespace art
448
449namespace std {
450
451template <>
452struct hash<art::HEdge> {
453 size_t operator()(art::HEdge const& x) const noexcept {
454 // Use Cantor pairing function as the hash function.
Artem Serov02eebcf2017-12-13 19:48:31 +0000455 size_t a = x.GetFrom();
456 size_t b = x.GetTo();
Artem Serov7f4aff62017-06-21 17:02:18 +0100457 return (a + b) * (a + b + 1) / 2 + b;
458 }
459};
Artem Serov02eebcf2017-12-13 19:48:31 +0000460ostream& operator<<(ostream& os, const art::HEdge& e);
Artem Serov7f4aff62017-06-21 17:02:18 +0100461
462} // namespace std
463
464#endif // ART_COMPILER_OPTIMIZING_SUPERBLOCK_CLONER_H_