blob: 733b4d689e9d80fd3125aaaccf406065d804131f [file] [log] [blame]
Eugene Zelenko9248fde2017-08-24 21:22:41 +00001//===- ForwardOpTree.h ------------------------------------------*- C++ -*-===//
Michael Krusea6b2de32017-07-22 14:02:47 +00002//
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// Move instructions between statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "polly/ForwardOpTree.h"
Michael Kruse70af4f52017-08-07 18:40:29 +000015#include "polly/Options.h"
Michael Kruse07e8c362017-07-24 12:43:27 +000016#include "polly/ScopBuilder.h"
Michael Krusea6b2de32017-07-22 14:02:47 +000017#include "polly/ScopInfo.h"
18#include "polly/ScopPass.h"
19#include "polly/Support/GICHelper.h"
Michael Kruse70af4f52017-08-07 18:40:29 +000020#include "polly/Support/ISLOStream.h"
21#include "polly/Support/ISLTools.h"
Michael Krusea6b2de32017-07-22 14:02:47 +000022#include "polly/Support/VirtualInstruction.h"
Michael Kruse70af4f52017-08-07 18:40:29 +000023#include "polly/ZoneAlgo.h"
Eugene Zelenko9248fde2017-08-24 21:22:41 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/LoopInfo.h"
Michael Krusea6b2de32017-07-22 14:02:47 +000028#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko9248fde2017-08-24 21:22:41 +000029#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Value.h"
32#include "llvm/Pass.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39#include "isl/ctx.h"
40#include "isl/isl-noexceptions.h"
41#include <cassert>
42#include <memory>
Michael Krusea6b2de32017-07-22 14:02:47 +000043
Michael Kruse36550ba2017-08-09 12:27:35 +000044#define DEBUG_TYPE "polly-optree"
Michael Krusea6b2de32017-07-22 14:02:47 +000045
Michael Krusea6b2de32017-07-22 14:02:47 +000046using namespace llvm;
Eugene Zelenko9248fde2017-08-24 21:22:41 +000047using namespace polly;
Michael Krusea6b2de32017-07-22 14:02:47 +000048
Michael Kruse70af4f52017-08-07 18:40:29 +000049static cl::opt<bool>
50 AnalyzeKnown("polly-optree-analyze-known",
51 cl::desc("Analyze array contents for load forwarding"),
52 cl::cat(PollyCategory), cl::init(true), cl::Hidden);
53
54static cl::opt<unsigned long>
55 MaxOps("polly-optree-max-ops",
56 cl::desc("Maximum number of ISL operations to invest for known "
57 "analysis; 0=no limit"),
58 cl::init(1000000), cl::cat(PollyCategory), cl::Hidden);
59
60STATISTIC(KnownAnalyzed, "Number of successfully analyzed SCoPs");
61STATISTIC(KnownOutOfQuota,
62 "Analyses aborted because max_operations was reached");
Michael Kruse70af4f52017-08-07 18:40:29 +000063
Michael Krusea6b2de32017-07-22 14:02:47 +000064STATISTIC(TotalInstructionsCopied, "Number of copied instructions");
Michael Kruse70af4f52017-08-07 18:40:29 +000065STATISTIC(TotalKnownLoadsForwarded,
66 "Number of forwarded loads because their value was known");
Michael Kruse07e8c362017-07-24 12:43:27 +000067STATISTIC(TotalReadOnlyCopied, "Number of copied read-only accesses");
Michael Krusea6b2de32017-07-22 14:02:47 +000068STATISTIC(TotalForwardedTrees, "Number of forwarded operand trees");
69STATISTIC(TotalModifiedStmts,
70 "Number of statements with at least one forwarded tree");
71
72STATISTIC(ScopsModified, "Number of SCoPs with at least one forwarded tree");
73
Michael Kruse06ed5292017-08-23 13:50:30 +000074STATISTIC(NumValueWrites, "Number of scalar value writes after OpTree");
75STATISTIC(NumValueWritesInLoops,
76 "Number of scalar value writes nested in affine loops after OpTree");
77STATISTIC(NumPHIWrites, "Number of scalar phi writes after OpTree");
78STATISTIC(NumPHIWritesInLoops,
79 "Number of scalar phi writes nested in affine loops after OpTree");
80STATISTIC(NumSingletonWrites, "Number of singleton writes after OpTree");
81STATISTIC(NumSingletonWritesInLoops,
82 "Number of singleton writes nested in affine loops after OpTree");
83
Michael Krusea6b2de32017-07-22 14:02:47 +000084namespace {
85
86/// The state of whether an operand tree was/can be forwarded.
Michael Krused85e3452017-07-24 15:33:53 +000087///
88/// The items apply to an instructions and its operand tree with the instruction
89/// as the root element. If the value in question is not an instruction in the
90/// SCoP, it can be a leaf of an instruction's operand tree.
Michael Krusea6b2de32017-07-22 14:02:47 +000091enum ForwardingDecision {
Michael Krused85e3452017-07-24 15:33:53 +000092 /// The root instruction or value cannot be forwarded at all.
Michael Krusea6b2de32017-07-22 14:02:47 +000093 FD_CannotForward,
Michael Krused85e3452017-07-24 15:33:53 +000094
95 /// The root instruction or value can be forwarded as a leaf of a larger
96 /// operand tree.
97 /// It does not make sense to move the value itself, it would just replace it
98 /// by a use of itself. For instance, a constant "5" used in a statement can
99 /// be forwarded, but it would just replace it by the same constant "5".
100 /// However, it makes sense to move as an operand of
101 ///
102 /// %add = add 5, 5
103 ///
104 /// where "5" is moved as part of a larger operand tree. "5" would be placed
105 /// (disregarding for a moment that literal constants don't have a location
106 /// and can be used anywhere) into the same statement as %add would.
Michael Kruse67752072017-07-24 15:33:58 +0000107 FD_CanForwardLeaf,
Michael Krused85e3452017-07-24 15:33:53 +0000108
109 /// The root instruction can be forwarded in a non-trivial way. This requires
110 /// the operand tree root to be an instruction in some statement.
Michael Kruse07e8c362017-07-24 12:43:27 +0000111 FD_CanForwardTree,
Michael Krused85e3452017-07-24 15:33:53 +0000112
113 /// Used to indicate that a forwarding has be carried out successfully.
Michael Krusea6b2de32017-07-22 14:02:47 +0000114 FD_DidForward,
Michael Krusea9a70862017-08-04 12:28:42 +0000115
116 /// A forwarding method cannot be applied to the operand tree.
117 /// The difference to FD_CannotForward is that there might be other methods
118 /// that can handle it.
119 /// The conditions that make an operand tree applicable must be checked even
120 /// with DoIt==true because a method following the one that returned
121 /// FD_NotApplicable might have returned FD_CanForwardTree.
122 FD_NotApplicable
Michael Krusea6b2de32017-07-22 14:02:47 +0000123};
124
125/// Implementation of operand tree forwarding for a specific SCoP.
126///
127/// For a statement that requires a scalar value (through a value read
128/// MemoryAccess), see if its operand can be moved into the statement. If so,
129/// the MemoryAccess is removed and the all the operand tree instructions are
130/// moved into the statement. All original instructions are left in the source
131/// statements. The simplification pass can clean these up.
Michael Kruse70af4f52017-08-07 18:40:29 +0000132class ForwardOpTreeImpl : ZoneAlgorithm {
Michael Krusea6b2de32017-07-22 14:02:47 +0000133private:
Michael Krusea6b2de32017-07-22 14:02:47 +0000134 /// How many instructions have been copied to other statements.
135 int NumInstructionsCopied = 0;
136
Michael Kruse70af4f52017-08-07 18:40:29 +0000137 /// Number of loads forwarded because their value was known.
138 int NumKnownLoadsForwarded = 0;
139
Michael Kruse07e8c362017-07-24 12:43:27 +0000140 /// How many read-only accesses have been copied.
141 int NumReadOnlyCopied = 0;
142
Michael Krusea6b2de32017-07-22 14:02:47 +0000143 /// How many operand trees have been forwarded.
144 int NumForwardedTrees = 0;
145
146 /// Number of statements with at least one forwarded operand tree.
147 int NumModifiedStmts = 0;
148
149 /// Whether we carried out at least one change to the SCoP.
150 bool Modified = false;
151
Michael Kruse70af4f52017-08-07 18:40:29 +0000152 /// Contains the zones where array elements are known to contain a specific
153 /// value.
154 /// { [Element[] -> Zone[]] -> ValInst[] }
155 /// @see computeKnown()
156 isl::union_map Known;
157
158 /// Translator for newly introduced ValInsts to already existing ValInsts such
159 /// that new introduced load instructions can reuse the Known analysis of its
160 /// original load. { ValInst[] -> ValInst[] }
161 isl::union_map Translator;
162
163 /// Get list of array elements that do contain the same ValInst[] at Domain[].
164 ///
165 /// @param ValInst { Domain[] -> ValInst[] }
166 /// The values for which we search for alternative locations,
167 /// per statement instance.
168 ///
169 /// @return { Domain[] -> Element[] }
170 /// For each statement instance, the array elements that contain the
171 /// same ValInst.
172 isl::union_map findSameContentElements(isl::union_map ValInst) {
173 assert(ValInst.is_single_valued().is_true());
174
175 // { Domain[] }
176 isl::union_set Domain = ValInst.domain();
177
178 // { Domain[] -> Scatter[] }
179 isl::union_map Schedule = getScatterFor(Domain);
180
181 // { Element[] -> [Scatter[] -> ValInst[]] }
182 isl::union_map MustKnownCurried =
183 convertZoneToTimepoints(Known, isl::dim::in, false, true).curry();
184
185 // { [Domain[] -> ValInst[]] -> Scatter[] }
186 isl::union_map DomValSched = ValInst.domain_map().apply_range(Schedule);
187
188 // { [Scatter[] -> ValInst[]] -> [Domain[] -> ValInst[]] }
189 isl::union_map SchedValDomVal =
190 DomValSched.range_product(ValInst.range_map()).reverse();
191
192 // { Element[] -> [Domain[] -> ValInst[]] }
193 isl::union_map MustKnownInst = MustKnownCurried.apply_range(SchedValDomVal);
194
195 // { Domain[] -> Element[] }
196 isl::union_map MustKnownMap =
197 MustKnownInst.uncurry().domain().unwrap().reverse();
198 simplify(MustKnownMap);
199
200 return MustKnownMap;
201 }
202
203 /// Find a single array element for each statement instance, within a single
204 /// array.
205 ///
206 /// @param MustKnown { Domain[] -> Element[] }
207 /// Set of candidate array elements.
208 /// @param Domain { Domain[] }
209 /// The statement instance for which we need elements for.
210 ///
211 /// @return { Domain[] -> Element[] }
212 /// For each statement instance, an array element out of @p MustKnown.
213 /// All array elements must be in the same array (Polly does not yet
214 /// support reading from different accesses using the same
215 /// MemoryAccess). If no mapping for all of @p Domain exists, returns
216 /// null.
217 isl::map singleLocation(isl::union_map MustKnown, isl::set Domain) {
218 // { Domain[] -> Element[] }
219 isl::map Result;
220
221 // MemoryAccesses can read only elements from a single array
222 // (i.e. not: { Dom[0] -> A[0]; Dom[1] -> B[1] }).
223 // Look through all spaces until we find one that contains at least the
224 // wanted statement instance.s
Reid Kleckner8d719a22017-08-10 21:46:22 +0000225 MustKnown.foreach_map([&](isl::map Map) -> isl::stat {
Michael Kruse70af4f52017-08-07 18:40:29 +0000226 // Get the array this is accessing.
227 isl::id ArrayId = Map.get_tuple_id(isl::dim::out);
228 ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(ArrayId.get_user());
229
230 // No support for generation of indirect array accesses.
231 if (SAI->getBasePtrOriginSAI())
232 return isl::stat::ok; // continue
233
234 // Determine whether this map contains all wanted values.
235 isl::set MapDom = Map.domain();
236 if (!Domain.is_subset(MapDom).is_true())
237 return isl::stat::ok; // continue
238
239 // There might be multiple array elements that contain the same value, but
240 // choose only one of them. lexmin is used because it returns a one-value
241 // mapping, we do not care about which one.
242 // TODO: Get the simplest access function.
243 Result = Map.lexmin();
244 return isl::stat::error; // break
245 });
246
247 return Result;
248 }
249
250public:
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000251 ForwardOpTreeImpl(Scop *S, LoopInfo *LI)
252 : ZoneAlgorithm("polly-optree", S, LI) {}
253
Michael Kruse70af4f52017-08-07 18:40:29 +0000254 /// Compute the zones of known array element contents.
255 ///
256 /// @return True if the computed #Known is usable.
257 bool computeKnownValues() {
258 isl::union_map MustKnown, KnownFromLoad, KnownFromInit;
259
260 // Check that nothing strange occurs.
Michael Kruse47281842017-08-28 20:39:07 +0000261 collectCompatibleElts();
Michael Kruse70af4f52017-08-07 18:40:29 +0000262
263 isl_ctx_reset_error(IslCtx.get());
264 {
265 IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), MaxOps);
266
267 computeCommon();
268 Known = computeKnown(true, true);
Michael Kruse70af4f52017-08-07 18:40:29 +0000269
270 // Preexisting ValInsts use the known content analysis of themselves.
271 Translator = makeIdentityMap(Known.range(), false);
272 }
273
274 if (!Known || !Translator) {
275 assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota);
276 KnownOutOfQuota++;
277 Known = nullptr;
278 Translator = nullptr;
279 DEBUG(dbgs() << "Known analysis exceeded max_operations\n");
280 return false;
281 }
282
283 KnownAnalyzed++;
284 DEBUG(dbgs() << "All known: " << Known << "\n");
285
286 return true;
287 }
288
Michael Krusea6b2de32017-07-22 14:02:47 +0000289 void printStatistics(raw_ostream &OS, int Indent = 0) {
290 OS.indent(Indent) << "Statistics {\n";
291 OS.indent(Indent + 4) << "Instructions copied: " << NumInstructionsCopied
292 << '\n';
Michael Kruse70af4f52017-08-07 18:40:29 +0000293 OS.indent(Indent + 4) << "Known loads forwarded: " << NumKnownLoadsForwarded
294 << '\n';
Michael Kruse07e8c362017-07-24 12:43:27 +0000295 OS.indent(Indent + 4) << "Read-only accesses copied: " << NumReadOnlyCopied
296 << '\n';
Michael Krusea6b2de32017-07-22 14:02:47 +0000297 OS.indent(Indent + 4) << "Operand trees forwarded: " << NumForwardedTrees
298 << '\n';
299 OS.indent(Indent + 4) << "Statements with forwarded operand trees: "
300 << NumModifiedStmts << '\n';
301 OS.indent(Indent) << "}\n";
302 }
303
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000304 void printStatements(raw_ostream &OS, int Indent = 0) const {
Michael Krusea6b2de32017-07-22 14:02:47 +0000305 OS.indent(Indent) << "After statements {\n";
306 for (auto &Stmt : *S) {
307 OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
308 for (auto *MA : Stmt)
309 MA->print(OS);
310
311 OS.indent(Indent + 12);
312 Stmt.printInstructions(OS);
313 }
314 OS.indent(Indent) << "}\n";
315 }
316
Michael Kruse70af4f52017-08-07 18:40:29 +0000317 /// Create a new MemoryAccess of type read and MemoryKind::Array.
318 ///
319 /// @param Stmt The statement in which the access occurs.
320 /// @param LI The instruction that does the access.
321 /// @param AccessRelation The array element that each statement instance
322 /// accesses.
323 ///
324 /// @param The newly created access.
325 MemoryAccess *makeReadArrayAccess(ScopStmt *Stmt, LoadInst *LI,
326 isl::map AccessRelation) {
327 isl::id ArrayId = AccessRelation.get_tuple_id(isl::dim::out);
328 ScopArrayInfo *SAI = reinterpret_cast<ScopArrayInfo *>(ArrayId.get_user());
329
330 // Create a dummy SCEV access, to be replaced anyway.
331 SmallVector<const SCEV *, 4> Sizes;
332 Sizes.reserve(SAI->getNumberOfDimensions());
333 SmallVector<const SCEV *, 4> Subscripts;
334 Subscripts.reserve(SAI->getNumberOfDimensions());
335 for (unsigned i = 0; i < SAI->getNumberOfDimensions(); i += 1) {
336 Sizes.push_back(SAI->getDimensionSize(i));
337 Subscripts.push_back(nullptr);
338 }
339
340 MemoryAccess *Access =
341 new MemoryAccess(Stmt, LI, MemoryAccess::READ, SAI->getBasePtr(),
342 LI->getType(), true, {}, Sizes, LI, MemoryKind::Array);
343 S->addAccessFunction(Access);
344 Stmt->addAccess(Access, true);
345
346 Access->setNewAccessRelation(AccessRelation);
347
348 return Access;
349 }
350
351 /// For an llvm::Value defined in @p DefStmt, compute the RAW dependency for a
352 /// use in every instance of @p UseStmt.
353 ///
354 /// @param UseStmt Statement a scalar is used in.
355 /// @param DefStmt Statement a scalar is defined in.
356 ///
357 /// @return { DomainUse[] -> DomainDef[] }
358 isl::map computeUseToDefFlowDependency(ScopStmt *UseStmt, ScopStmt *DefStmt) {
359 // { DomainUse[] -> Scatter[] }
360 isl::map UseScatter = getScatterFor(UseStmt);
361
362 // { Zone[] -> DomainDef[] }
363 isl::map ReachDefZone = getScalarReachingDefinition(DefStmt);
364
365 // { Scatter[] -> DomainDef[] }
366 isl::map ReachDefTimepoints =
367 convertZoneToTimepoints(ReachDefZone, isl::dim::in, false, true);
368
369 // { DomainUse[] -> DomainDef[] }
370 return UseScatter.apply_range(ReachDefTimepoints);
371 }
372
373 /// Forward a load by reading from an array element that contains the same
374 /// value. Typically the location it was loaded from.
375 ///
376 /// @param TargetStmt The statement the operand tree will be copied to.
377 /// @param Inst The (possibly speculatable) instruction to forward.
378 /// @param UseStmt The statement that uses @p Inst.
379 /// @param UseLoop The loop @p Inst is used in.
380 /// @param UseToTarget { DomainUse[] -> DomainTarget[] }
381 /// A mapping from the statement instance @p Inst is used
382 /// to the statement instance it is forwarded to.
383 /// @param DefStmt The statement @p Inst is defined in.
384 /// @param DefLoop The loop which contains @p Inst.
385 /// @param DefToTarget { DomainDef[] -> DomainTarget[] }
386 /// A mapping from the statement instance @p Inst is
387 /// defined to the statement instance it is forwarded to.
388 /// @param DoIt If false, only determine whether an operand tree can be
389 /// forwarded. If true, carry out the forwarding. Do not
390 /// use DoIt==true if an operand tree is not known to be
391 /// forwardable.
392 ///
393 /// @return FD_NotApplicable if @p Inst is not a LoadInst.
394 /// FD_CannotForward if no array element to load from was found.
395 /// FD_CanForwardLeaf if the load is already in the target statement
396 /// instance.
397 /// FD_CanForwardTree if @p Inst is forwardable.
398 /// FD_DidForward if @p DoIt was true.
399 ForwardingDecision forwardKnownLoad(ScopStmt *TargetStmt, Instruction *Inst,
400 ScopStmt *UseStmt, Loop *UseLoop,
401 isl::map UseToTarget, ScopStmt *DefStmt,
402 Loop *DefLoop, isl::map DefToTarget,
403 bool DoIt) {
404 // Cannot do anything without successful known analysis.
405 if (Known.is_null())
406 return FD_NotApplicable;
407
408 LoadInst *LI = dyn_cast<LoadInst>(Inst);
409 if (!LI)
410 return FD_NotApplicable;
411
Michael Kruse7954a222017-09-03 16:09:38 +0000412 // If the load is already in the statement, no forwarding is necessary.
Michael Kruse70af4f52017-08-07 18:40:29 +0000413 // However, it might happen that the LoadInst is already present in the
414 // statement's instruction list. In that case we do as follows:
415 // - For the evaluation (DoIt==false), we can trivially forward it as it is
416 // benefit of forwarding an already present instruction.
Michael Kruse7954a222017-09-03 16:09:38 +0000417 // - For the execution (DoIt==true), prepend the instruction (to make it
Michael Kruse70af4f52017-08-07 18:40:29 +0000418 // available to all instructions following in the instruction list), but
419 // do not add another MemoryAccess.
420 MemoryAccess *Access = TargetStmt->getArrayAccessOrNULLFor(LI);
421 if (Access && !DoIt)
Tobias Grosserd6e06792017-09-03 19:52:15 +0000422 return FD_CanForwardTree;
Michael Kruse70af4f52017-08-07 18:40:29 +0000423
424 if (DoIt)
425 TargetStmt->prependInstruction(LI);
426
427 ForwardingDecision OpDecision =
428 forwardTree(TargetStmt, LI->getPointerOperand(), DefStmt, DefLoop,
429 DefToTarget, DoIt);
430 switch (OpDecision) {
431 case FD_CannotForward:
432 assert(!DoIt);
433 return OpDecision;
434
435 case FD_CanForwardLeaf:
436 case FD_CanForwardTree:
437 assert(!DoIt);
438 break;
439
440 case FD_DidForward:
441 assert(DoIt);
442 break;
443
444 default:
445 llvm_unreachable("Shouldn't return this");
446 }
447
448 // { DomainDef[] -> ValInst[] }
449 isl::map ExpectedVal = makeValInst(Inst, UseStmt, UseLoop);
450
451 // { DomainTarget[] -> ValInst[] }
452 isl::map TargetExpectedVal = ExpectedVal.apply_domain(UseToTarget);
453 isl::union_map TranslatedExpectedVal =
454 isl::union_map(TargetExpectedVal).apply_range(Translator);
455
456 // { DomainTarget[] -> Element[] }
457 isl::union_map Candidates = findSameContentElements(TranslatedExpectedVal);
458
459 isl::map SameVal = singleLocation(Candidates, getDomainFor(TargetStmt));
460 if (!SameVal)
461 return FD_CannotForward;
462
463 if (!DoIt)
464 return FD_CanForwardTree;
465
466 if (Access) {
467 DEBUG(dbgs() << " forwarded known load with preexisting MemoryAccess"
468 << Access << "\n");
469 } else {
470 Access = makeReadArrayAccess(TargetStmt, LI, SameVal);
471 DEBUG(dbgs() << " forwarded known load with new MemoryAccess" << Access
472 << "\n");
473
474 // { ValInst[] }
475 isl::space ValInstSpace = ExpectedVal.get_space().range();
476
477 // After adding a new load to the SCoP, also update the Known content
478 // about it. The new load will have a known ValInst of
479 // { [DomainTarget[] -> Value[]] }
480 // but which -- because it is a copy of it -- has same value as the
481 // { [DomainDef[] -> Value[]] }
482 // that it replicates. Instead of cloning the known content of
483 // [DomainDef[] -> Value[]]
484 // for DomainTarget[], we add a 'translator' that maps
485 // [DomainTarget[] -> Value[]] to [DomainDef[] -> Value[]]
486 // before comparing to the known content.
487 // TODO: 'Translator' could also be used to map PHINodes to their incoming
488 // ValInsts.
489 if (ValInstSpace.is_wrapping()) {
490 // { DefDomain[] -> Value[] }
491 isl::map ValInsts = ExpectedVal.range().unwrap();
492
493 // { DefDomain[] }
494 isl::set DefDomain = ValInsts.domain();
495
496 // { Value[] }
497 isl::space ValSpace = ValInstSpace.unwrap().range();
498
499 // { Value[] -> Value[] }
500 isl::map ValToVal =
501 isl::map::identity(ValSpace.map_from_domain_and_range(ValSpace));
502
503 // { [TargetDomain[] -> Value[]] -> [DefDomain[] -> Value] }
504 isl::map LocalTranslator = DefToTarget.reverse().product(ValToVal);
505
506 Translator = Translator.add_map(LocalTranslator);
507 DEBUG(dbgs() << " local translator is " << LocalTranslator
508 << "\n");
509 }
510 }
511 DEBUG(dbgs() << " expected values where " << TargetExpectedVal
512 << "\n");
513 DEBUG(dbgs() << " candidate elements where " << Candidates << "\n");
514 assert(Access);
515
516 NumKnownLoadsForwarded++;
517 TotalKnownLoadsForwarded++;
518 return FD_DidForward;
519 }
520
Michael Krusea9a70862017-08-04 12:28:42 +0000521 /// Forwards a speculatively executable instruction.
522 ///
Michael Kruse70af4f52017-08-07 18:40:29 +0000523 /// @param TargetStmt The statement the operand tree will be copied to.
524 /// @param UseInst The (possibly speculatable) instruction to forward.
525 /// @param DefStmt The statement @p UseInst is defined in.
526 /// @param DefLoop The loop which contains @p UseInst.
527 /// @param DefToTarget { DomainDef[] -> DomainTarget[] }
528 /// A mapping from the statement instance @p UseInst is
529 /// defined to the statement instance it is forwarded to.
530 /// @param DoIt If false, only determine whether an operand tree can be
531 /// forwarded. If true, carry out the forwarding. Do not
532 /// use DoIt==true if an operand tree is not known to be
533 /// forwardable.
Michael Krusea9a70862017-08-04 12:28:42 +0000534 ///
Michael Kruse70af4f52017-08-07 18:40:29 +0000535 /// @return FD_NotApplicable if @p UseInst is not speculatable.
536 /// FD_CannotForward if one of @p UseInst's operands is not
537 /// forwardable.
538 /// FD_CanForwardTree if @p UseInst is forwardable.
539 /// FD_DidForward if @p DoIt was true.
Michael Krusea9a70862017-08-04 12:28:42 +0000540 ForwardingDecision forwardSpeculatable(ScopStmt *TargetStmt,
541 Instruction *UseInst,
Michael Kruse70af4f52017-08-07 18:40:29 +0000542 ScopStmt *DefStmt, Loop *DefLoop,
543 isl::map DefToTarget, bool DoIt) {
Michael Krusea9a70862017-08-04 12:28:42 +0000544 // PHIs, unless synthesizable, are not yet supported.
545 if (isa<PHINode>(UseInst))
546 return FD_NotApplicable;
547
548 // Compatible instructions must satisfy the following conditions:
549 // 1. Idempotent (instruction will be copied, not moved; although its
550 // original instance might be removed by simplification)
551 // 2. Not access memory (There might be memory writes between)
552 // 3. Not cause undefined behaviour (we might copy to a location when the
553 // original instruction was no executed; this is currently not possible
554 // because we do not forward PHINodes)
555 // 4. Not leak memory if executed multiple times (i.e. malloc)
556 //
557 // Instruction::mayHaveSideEffects is not sufficient because it considers
558 // malloc to not have side-effects. llvm::isSafeToSpeculativelyExecute is
559 // not sufficient because it allows memory accesses.
560 if (mayBeMemoryDependent(*UseInst))
561 return FD_NotApplicable;
562
Michael Krusea9a70862017-08-04 12:28:42 +0000563 if (DoIt) {
564 // To ensure the right order, prepend this instruction before its
565 // operands. This ensures that its operands are inserted before the
566 // instruction using them.
567 // TODO: The operand tree is not really a tree, but a DAG. We should be
568 // able to handle DAGs without duplication.
569 TargetStmt->prependInstruction(UseInst);
570 NumInstructionsCopied++;
571 TotalInstructionsCopied++;
572 }
573
574 for (Value *OpVal : UseInst->operand_values()) {
575 ForwardingDecision OpDecision =
Michael Kruse70af4f52017-08-07 18:40:29 +0000576 forwardTree(TargetStmt, OpVal, DefStmt, DefLoop, DefToTarget, DoIt);
Michael Krusea9a70862017-08-04 12:28:42 +0000577 switch (OpDecision) {
578 case FD_CannotForward:
579 assert(!DoIt);
580 return FD_CannotForward;
581
582 case FD_CanForwardLeaf:
583 case FD_CanForwardTree:
584 assert(!DoIt);
585 break;
586
587 case FD_DidForward:
588 assert(DoIt);
589 break;
590
591 case FD_NotApplicable:
592 llvm_unreachable("forwardTree should never return FD_NotApplicable");
593 }
594 }
595
596 if (DoIt)
597 return FD_DidForward;
598 return FD_CanForwardTree;
599 }
600
Michael Krusea6b2de32017-07-22 14:02:47 +0000601 /// Determines whether an operand tree can be forwarded or carries out a
602 /// forwarding, depending on the @p DoIt flag.
603 ///
Michael Kruse70af4f52017-08-07 18:40:29 +0000604 /// @param TargetStmt The statement the operand tree will be copied to.
605 /// @param UseVal The value (usually an instruction) which is root of an
606 /// operand tree.
607 /// @param UseStmt The statement that uses @p UseVal.
608 /// @param UseLoop The loop @p UseVal is used in.
609 /// @param UseToTarget { DomainUse[] -> DomainTarget[] }
610 /// A mapping from the statement instance @p UseVal is used
611 /// to the statement instance it is forwarded to.
612 /// @param DoIt If false, only determine whether an operand tree can be
613 /// forwarded. If true, carry out the forwarding. Do not
614 /// use DoIt==true if an operand tree is not known to be
615 /// forwardable.
Michael Krusea6b2de32017-07-22 14:02:47 +0000616 ///
Michael Kruse5b8a9092017-07-24 12:39:46 +0000617 /// @return If DoIt==false, return whether the operand tree can be forwarded.
618 /// If DoIt==true, return FD_DidForward.
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000619 ForwardingDecision forwardTree(ScopStmt *TargetStmt, Value *UseVal,
620 ScopStmt *UseStmt, Loop *UseLoop,
Michael Kruse70af4f52017-08-07 18:40:29 +0000621 isl::map UseToTarget, bool DoIt) {
622 ScopStmt *DefStmt = nullptr;
623 Loop *DefLoop = nullptr;
624
625 // { DefDomain[] -> TargetDomain[] }
626 isl::map DefToTarget;
627
Michael Krusea6b2de32017-07-22 14:02:47 +0000628 VirtualUse VUse = VirtualUse::create(UseStmt, UseLoop, UseVal, true);
629 switch (VUse.getKind()) {
630 case VirtualUse::Constant:
631 case VirtualUse::Block:
Michael Krusee5f47062017-07-22 14:30:02 +0000632 case VirtualUse::Hoisted:
Michael Krusea6b2de32017-07-22 14:02:47 +0000633 // These can be used anywhere without special considerations.
634 if (DoIt)
635 return FD_DidForward;
Michael Kruse67752072017-07-24 15:33:58 +0000636 return FD_CanForwardLeaf;
Michael Krusea6b2de32017-07-22 14:02:47 +0000637
Michael Kruse9f6e41c2017-07-31 19:46:21 +0000638 case VirtualUse::Synthesizable: {
639 // ScopExpander will take care for of generating the code at the new
640 // location.
641 if (DoIt)
642 return FD_DidForward;
643
644 // Check if the value is synthesizable at the new location as well. This
645 // might be possible when leaving a loop for which ScalarEvolution is
646 // unable to derive the exit value for.
647 // TODO: If there is a LCSSA PHI at the loop exit, use that one.
648 // If the SCEV contains a SCEVAddRecExpr, we currently depend on that we
649 // do not forward past its loop header. This would require us to use a
650 // previous loop induction variable instead the current one. We currently
651 // do not allow forwarding PHI nodes, thus this should never occur (the
652 // only exception where no phi is necessary being an unreachable loop
653 // without edge from the outside).
654 VirtualUse TargetUse = VirtualUse::create(
655 S, TargetStmt, TargetStmt->getSurroundingLoop(), UseVal, true);
656 if (TargetUse.getKind() == VirtualUse::Synthesizable)
657 return FD_CanForwardLeaf;
658
659 DEBUG(dbgs() << " Synthesizable would not be synthesizable anymore: "
660 << *UseVal << "\n");
Michael Krusea6b2de32017-07-22 14:02:47 +0000661 return FD_CannotForward;
Michael Kruse9f6e41c2017-07-31 19:46:21 +0000662 }
Michael Krusea6b2de32017-07-22 14:02:47 +0000663
Michael Krusea6b2de32017-07-22 14:02:47 +0000664 case VirtualUse::ReadOnly:
Michael Krused85e3452017-07-24 15:33:53 +0000665 // Note that we cannot return FD_CanForwardTree here. With a operand tree
666 // depth of 0, UseVal is the use in TargetStmt that we try to replace.
667 // With -polly-analyze-read-only-scalars=true we would ensure the
668 // existence of a MemoryAccess (which already exists for a leaf) and be
669 // removed again by tryForwardTree because it's goal is to remove this
670 // scalar MemoryAccess. It interprets FD_CanForwardTree as the permission
671 // to do so.
Michael Kruse07e8c362017-07-24 12:43:27 +0000672 if (!DoIt)
Michael Kruse67752072017-07-24 15:33:58 +0000673 return FD_CanForwardLeaf;
Michael Kruse07e8c362017-07-24 12:43:27 +0000674
675 // If we model read-only scalars, we need to create a MemoryAccess for it.
676 if (ModelReadOnlyScalars)
677 TargetStmt->ensureValueRead(UseVal);
678
679 NumReadOnlyCopied++;
680 TotalReadOnlyCopied++;
681 return FD_DidForward;
Michael Krusea6b2de32017-07-22 14:02:47 +0000682
683 case VirtualUse::Intra:
Michael Kruse70af4f52017-08-07 18:40:29 +0000684 // Knowing that UseStmt and DefStmt are the same statement instance, just
685 // reuse the information about UseStmt for DefStmt
686 DefStmt = UseStmt;
687 DefToTarget = UseToTarget;
Michael Krusea6b2de32017-07-22 14:02:47 +0000688
Michael Kruse70af4f52017-08-07 18:40:29 +0000689 LLVM_FALLTHROUGH;
690 case VirtualUse::Inter:
691 Instruction *Inst = cast<Instruction>(UseVal);
692
Michael Krusecd3b9fe2017-08-09 16:45:37 +0000693 if (!DefStmt) {
Michael Kruse70af4f52017-08-07 18:40:29 +0000694 DefStmt = S->getStmtFor(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +0000695 if (!DefStmt)
696 return FD_CannotForward;
697 }
698
Michael Kruse70af4f52017-08-07 18:40:29 +0000699 DefLoop = LI->getLoopFor(Inst->getParent());
700
701 if (DefToTarget.is_null() && !Known.is_null()) {
702 // { UseDomain[] -> DefDomain[] }
703 isl::map UseToDef = computeUseToDefFlowDependency(UseStmt, DefStmt);
704
705 // { DefDomain[] -> UseDomain[] -> TargetDomain[] } shortened to
706 // { DefDomain[] -> TargetDomain[] }
707 DefToTarget = UseToTarget.apply_domain(UseToDef);
708 simplify(DefToTarget);
709 }
710
711 ForwardingDecision SpeculativeResult = forwardSpeculatable(
712 TargetStmt, Inst, DefStmt, DefLoop, DefToTarget, DoIt);
Michael Krusea9a70862017-08-04 12:28:42 +0000713 if (SpeculativeResult != FD_NotApplicable)
714 return SpeculativeResult;
Michael Kruse9f6e41c2017-07-31 19:46:21 +0000715
Michael Kruse70af4f52017-08-07 18:40:29 +0000716 ForwardingDecision KnownResult =
717 forwardKnownLoad(TargetStmt, Inst, UseStmt, UseLoop, UseToTarget,
718 DefStmt, DefLoop, DefToTarget, DoIt);
719 if (KnownResult != FD_NotApplicable)
720 return KnownResult;
721
Michael Krusea9a70862017-08-04 12:28:42 +0000722 // When no method is found to forward the operand tree, we effectively
723 // cannot handle it.
724 DEBUG(dbgs() << " Cannot forward instruction: " << *Inst << "\n");
725 return FD_CannotForward;
Michael Krusea6b2de32017-07-22 14:02:47 +0000726 }
727
728 llvm_unreachable("Case unhandled");
729 }
730
731 /// Try to forward an operand tree rooted in @p RA.
732 bool tryForwardTree(MemoryAccess *RA) {
733 assert(RA->isLatestScalarKind());
734 DEBUG(dbgs() << "Trying to forward operand tree " << RA << "...\n");
735
736 ScopStmt *Stmt = RA->getStatement();
737 Loop *InLoop = Stmt->getSurroundingLoop();
738
Michael Kruse70af4f52017-08-07 18:40:29 +0000739 isl::map TargetToUse;
740 if (!Known.is_null()) {
741 isl::space DomSpace = Stmt->getDomainSpace();
742 TargetToUse =
743 isl::map::identity(DomSpace.map_from_domain_and_range(DomSpace));
744 }
745
746 ForwardingDecision Assessment = forwardTree(
747 Stmt, RA->getAccessValue(), Stmt, InLoop, TargetToUse, false);
Michael Krusea6b2de32017-07-22 14:02:47 +0000748 assert(Assessment != FD_DidForward);
Michael Kruse07e8c362017-07-24 12:43:27 +0000749 if (Assessment != FD_CanForwardTree)
Michael Krusea6b2de32017-07-22 14:02:47 +0000750 return false;
751
Michael Kruse70af4f52017-08-07 18:40:29 +0000752 ForwardingDecision Execution = forwardTree(Stmt, RA->getAccessValue(), Stmt,
753 InLoop, TargetToUse, true);
Michael Krusefd350892017-08-01 22:15:04 +0000754 assert(Execution == FD_DidForward &&
755 "A previous positive assessment must also be executable");
756 (void)Execution;
Michael Krusea6b2de32017-07-22 14:02:47 +0000757
758 Stmt->removeSingleMemoryAccess(RA);
759 return true;
760 }
761
Michael Krusea6b2de32017-07-22 14:02:47 +0000762 /// Return which SCoP this instance is processing.
763 Scop *getScop() const { return S; }
764
765 /// Run the algorithm: Use value read accesses as operand tree roots and try
766 /// to forward them into the statement.
767 bool forwardOperandTrees() {
768 for (ScopStmt &Stmt : *S) {
Michael Krusea6b2de32017-07-22 14:02:47 +0000769 bool StmtModified = false;
770
771 // Because we are modifying the MemoryAccess list, collect them first to
772 // avoid iterator invalidation.
773 SmallVector<MemoryAccess *, 16> Accs;
774 for (MemoryAccess *RA : Stmt) {
775 if (!RA->isRead())
776 continue;
777 if (!RA->isLatestScalarKind())
778 continue;
779
780 Accs.push_back(RA);
781 }
782
783 for (MemoryAccess *RA : Accs) {
784 if (tryForwardTree(RA)) {
785 Modified = true;
786 StmtModified = true;
787 NumForwardedTrees++;
788 TotalForwardedTrees++;
789 }
790 }
791
792 if (StmtModified) {
793 NumModifiedStmts++;
794 TotalModifiedStmts++;
795 }
796 }
797
798 if (Modified)
799 ScopsModified++;
800 return Modified;
801 }
802
803 /// Print the pass result, performed transformations and the SCoP after the
804 /// transformation.
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000805 void print(raw_ostream &OS, int Indent = 0) {
Michael Krusea6b2de32017-07-22 14:02:47 +0000806 printStatistics(OS, Indent);
807
808 if (!Modified) {
809 // This line can easily be checked in regression tests.
810 OS << "ForwardOpTree executed, but did not modify anything\n";
811 return;
812 }
813
814 printStatements(OS, Indent);
815 }
816};
817
818/// Pass that redirects scalar reads to array elements that are known to contain
819/// the same value.
820///
821/// This reduces the number of scalar accesses and therefore potentially
822/// increases the freedom of the scheduler. In the ideal case, all reads of a
823/// scalar definition are redirected (We currently do not care about removing
824/// the write in this case). This is also useful for the main DeLICM pass as
825/// there are less scalars to be mapped.
826class ForwardOpTree : public ScopPass {
827private:
Michael Krusea6b2de32017-07-22 14:02:47 +0000828 /// The pass implementation, also holding per-scop data.
829 std::unique_ptr<ForwardOpTreeImpl> Impl;
830
831public:
832 static char ID;
833
834 explicit ForwardOpTree() : ScopPass(ID) {}
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000835 ForwardOpTree(const ForwardOpTree &) = delete;
836 ForwardOpTree &operator=(const ForwardOpTree &) = delete;
Michael Krusea6b2de32017-07-22 14:02:47 +0000837
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000838 void getAnalysisUsage(AnalysisUsage &AU) const override {
Michael Krusea6b2de32017-07-22 14:02:47 +0000839 AU.addRequiredTransitive<ScopInfoRegionPass>();
840 AU.addRequired<LoopInfoWrapperPass>();
841 AU.setPreservesAll();
842 }
843
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000844 bool runOnScop(Scop &S) override {
Michael Krusea6b2de32017-07-22 14:02:47 +0000845 // Free resources for previous SCoP's computation, if not yet done.
846 releaseMemory();
847
848 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000849 Impl = llvm::make_unique<ForwardOpTreeImpl>(&S, &LI);
Michael Krusea6b2de32017-07-22 14:02:47 +0000850
Michael Kruse70af4f52017-08-07 18:40:29 +0000851 if (AnalyzeKnown) {
852 DEBUG(dbgs() << "Prepare forwarders...\n");
853 Impl->computeKnownValues();
854 }
855
Michael Krusea6b2de32017-07-22 14:02:47 +0000856 DEBUG(dbgs() << "Forwarding operand trees...\n");
857 Impl->forwardOperandTrees();
858
859 DEBUG(dbgs() << "\nFinal Scop:\n");
860 DEBUG(dbgs() << S);
861
Michael Kruse06ed5292017-08-23 13:50:30 +0000862 // Update statistics
863 auto ScopStats = S.getStatistics();
864 NumValueWrites += ScopStats.NumValueWrites;
865 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
866 NumPHIWrites += ScopStats.NumPHIWrites;
867 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
868 NumSingletonWrites += ScopStats.NumSingletonWrites;
869 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
870
Michael Krusea6b2de32017-07-22 14:02:47 +0000871 return false;
872 }
873
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000874 void printScop(raw_ostream &OS, Scop &S) const override {
Michael Krusea6b2de32017-07-22 14:02:47 +0000875 if (!Impl)
876 return;
877
878 assert(Impl->getScop() == &S);
879 Impl->print(OS);
880 }
881
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000882 void releaseMemory() override { Impl.reset(); }
Michael Krusea6b2de32017-07-22 14:02:47 +0000883}; // class ForwardOpTree
884
885char ForwardOpTree::ID;
Eugene Zelenko9248fde2017-08-24 21:22:41 +0000886
887} // namespace
Michael Krusea6b2de32017-07-22 14:02:47 +0000888
889ScopPass *polly::createForwardOpTreePass() { return new ForwardOpTree(); }
890
891INITIALIZE_PASS_BEGIN(ForwardOpTree, "polly-optree",
892 "Polly - Forward operand tree", false, false)
893INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
894INITIALIZE_PASS_END(ForwardOpTree, "polly-optree",
895 "Polly - Forward operand tree", false, false)