1 //===------ VirtualInstruction.cpp ------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Tools for determining which instructions are within a statement and the
11 // nature of their operands.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/Support/VirtualInstruction.h"
16 #include "polly/Support/SCEVValidator.h"
17 
18 using namespace polly;
19 using namespace llvm;
20 
21 VirtualUse VirtualUse ::create(Scop *S, const Use &U, LoopInfo *LI,
22                                bool Virtual) {
23   auto *UserBB = getUseBlock(U);
24   auto *UserStmt = S->getStmtFor(UserBB);
25   auto *UserScope = LI->getLoopFor(UserBB);
26   return create(S, UserStmt, UserScope, U.get(), Virtual);
27 }
28 
29 VirtualUse VirtualUse::create(Scop *S, ScopStmt *UserStmt, Loop *UserScope,
30                               Value *Val, bool Virtual) {
31   assert(!isa<StoreInst>(Val) && "a StoreInst cannot be used");
32 
33   if (isa<BasicBlock>(Val))
34     return VirtualUse(UserStmt, Val, Block, nullptr, nullptr);
35 
36   if (isa<llvm::Constant>(Val))
37     return VirtualUse(UserStmt, Val, Constant, nullptr, nullptr);
38 
39   // Is the value synthesizable? If the user has been pruned
40   // (UserStmt == nullptr), it is either not used anywhere or is synthesizable.
41   // We assume synthesizable which practically should have the same effect.
42   auto *SE = S->getSE();
43   if (SE->isSCEVable(Val->getType())) {
44     auto *ScevExpr = SE->getSCEVAtScope(Val, UserScope);
45     if (!UserStmt || canSynthesize(Val, *UserStmt->getParent(), SE, UserScope))
46       return VirtualUse(UserStmt, Val, Synthesizable, ScevExpr, nullptr);
47   }
48 
49   // FIXME: Inconsistency between lookupInvariantEquivClass and
50   // getRequiredInvariantLoads. Querying one of them should be enough.
51   auto &RIL = S->getRequiredInvariantLoads();
52   if (S->lookupInvariantEquivClass(Val) || RIL.count(dyn_cast<LoadInst>(Val)))
53     return VirtualUse(UserStmt, Val, Hoisted, nullptr, nullptr);
54 
55   // ReadOnly uses may have MemoryAccesses that we want to associate with the
56   // use. This is why we look for a MemoryAccess here already.
57   MemoryAccess *InputMA = nullptr;
58   if (UserStmt && Virtual)
59     InputMA = UserStmt->lookupValueReadOf(Val);
60 
61   // Uses are read-only if they have been defined before the SCoP, i.e., they
62   // cannot be written to inside the SCoP. Arguments are defined before any
63   // instructions, hence also before the SCoP. If the user has been pruned
64   // (UserStmt == nullptr) and is not SCEVable, assume it is read-only as it is
65   // neither an intra- nor an inter-use.
66   if (!UserStmt || isa<Argument>(Val))
67     return VirtualUse(UserStmt, Val, ReadOnly, nullptr, InputMA);
68 
69   auto Inst = cast<Instruction>(Val);
70   if (!S->contains(Inst))
71     return VirtualUse(UserStmt, Val, ReadOnly, nullptr, InputMA);
72 
73   // A use is inter-statement if either it is defined in another statement, or
74   // there is a MemoryAccess that reads its value that has been written by
75   // another statement.
76   if (InputMA || (!Virtual && !UserStmt->represents(Inst->getParent())))
77     return VirtualUse(UserStmt, Val, Inter, nullptr, InputMA);
78 
79   return VirtualUse(UserStmt, Val, Intra, nullptr, nullptr);
80 }
81 
82 void VirtualUse::print(raw_ostream &OS, bool Reproducible) const {
83   OS << "User: [" << User->getBaseName() << "] ";
84   switch (Kind) {
85   case VirtualUse::Constant:
86     OS << "Constant Op:";
87     break;
88   case VirtualUse::Block:
89     OS << "BasicBlock Op:";
90     break;
91   case VirtualUse::Synthesizable:
92     OS << "Synthesizable Op:";
93     break;
94   case VirtualUse::Hoisted:
95     OS << "Hoisted load Op:";
96     break;
97   case VirtualUse::ReadOnly:
98     OS << "Read-Only Op:";
99     break;
100   case VirtualUse::Intra:
101     OS << "Intra Op:";
102     break;
103   case VirtualUse::Inter:
104     OS << "Inter Op:";
105     break;
106   }
107 
108   if (Val) {
109     OS << ' ';
110     if (Reproducible)
111       OS << '"' << Val->getName() << '"';
112     else
113       Val->print(OS, true);
114   }
115   if (ScevExpr) {
116     OS << ' ';
117     ScevExpr->print(OS);
118   }
119   if (InputMA && !Reproducible)
120     OS << ' ' << InputMA;
121 }
122 
123 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
124 LLVM_DUMP_METHOD void VirtualUse::dump() const {
125   print(errs(), false);
126   errs() << '\n';
127 }
128 #endif
129 
130 void VirtualInstruction::print(raw_ostream &OS, bool Reproducible) const {
131   if (!Stmt || !Inst) {
132     OS << "[null VirtualInstruction]";
133     return;
134   }
135 
136   OS << "[" << Stmt->getBaseName() << "]";
137   Inst->print(OS, !Reproducible);
138 }
139 
140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
141 LLVM_DUMP_METHOD void VirtualInstruction::dump() const {
142   print(errs(), false);
143   errs() << '\n';
144 }
145 #endif
146 
147 /// Return true if @p Inst cannot be removed, even if it is nowhere referenced.
148 static bool isRoot(const Instruction *Inst) {
149   // The store is handled by its MemoryAccess. The load must be reached from the
150   // roots in order to be marked as used.
151   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
152     return false;
153 
154   // Terminator instructions (in region statements) are required for control
155   // flow.
156   if (isa<TerminatorInst>(Inst))
157     return true;
158 
159   // Writes to memory must be honored.
160   if (Inst->mayWriteToMemory())
161     return true;
162 
163   return false;
164 }
165 
166 /// Return true for MemoryAccesses that cannot be removed because it represents
167 /// an llvm::Value that is used after the SCoP.
168 static bool isEscaping(MemoryAccess *MA) {
169   assert(MA->isOriginalValueKind());
170   Scop *S = MA->getStatement()->getParent();
171   return S->isEscaping(cast<Instruction>(MA->getAccessValue()));
172 }
173 
174 /// Add non-removable virtual instructions in @p Stmt to @p RootInsts.
175 static void
176 addInstructionRoots(ScopStmt *Stmt,
177                     SmallVectorImpl<VirtualInstruction> &RootInsts) {
178   // For region statements we must keep all instructions because we do not
179   // support removing instructions from region statements.
180   if (!Stmt->isBlockStmt()) {
181     for (auto *BB : Stmt->getRegion()->blocks())
182       for (Instruction &Inst : *BB)
183         RootInsts.emplace_back(Stmt, &Inst);
184   }
185 
186   for (Instruction *Inst : Stmt->getInstructions())
187     if (isRoot(Inst))
188       RootInsts.emplace_back(Stmt, Inst);
189 }
190 
191 /// Add non-removable memory accesses in @p Stmt to @p RootInsts.
192 ///
193 /// @param Local If true, all writes are assumed to escape. markAndSweep
194 /// algorithms can use this to be applicable to a single ScopStmt only without
195 /// the risk of removing definitions required by other statements.
196 ///              If false, only writes for SCoP-escaping values are roots.  This
197 ///              is global mode, where such writes must be marked by theirs uses
198 ///              in order to be reachable.
199 static void addAccessRoots(ScopStmt *Stmt,
200                            SmallVectorImpl<MemoryAccess *> &RootAccs,
201                            bool Local) {
202   for (auto *MA : *Stmt) {
203     if (!MA->isWrite())
204       continue;
205 
206     // Writes to arrays are always used.
207     if (MA->isLatestArrayKind())
208       RootAccs.push_back(MA);
209 
210     // Values are roots if they are escaping.
211     else if (MA->isLatestValueKind()) {
212       if (Local || isEscaping(MA))
213         RootAccs.push_back(MA);
214     }
215 
216     // Exit phis are, by definition, escaping.
217     else if (MA->isLatestExitPHIKind())
218       RootAccs.push_back(MA);
219 
220     // phi writes are only roots if we are not visiting the statement
221     // containing the PHINode.
222     else if (Local && MA->isLatestPHIKind())
223       RootAccs.push_back(MA);
224   }
225 }
226 
227 /// Determine all instruction and access roots.
228 static void addRoots(ScopStmt *Stmt,
229                      SmallVectorImpl<VirtualInstruction> &RootInsts,
230                      SmallVectorImpl<MemoryAccess *> &RootAccs, bool Local) {
231   addInstructionRoots(Stmt, RootInsts);
232   addAccessRoots(Stmt, RootAccs, Local);
233 }
234 
235 /// Mark accesses and instructions as used if they are reachable from a root,
236 /// walking the operand trees.
237 ///
238 /// @param S              The SCoP to walk.
239 /// @param LI             The LoopInfo Analysis.
240 /// @param RootInsts      List of root instructions.
241 /// @param RootAccs       List of root accesses.
242 /// @param UsesInsts[out] Receives all reachable instructions, including the
243 /// roots.
244 /// @param UsedAccs[out]  Receives all reachable accesses, including the roots.
245 /// @param OnlyLocal      If non-nullptr, restricts walking to a single
246 /// statement.
247 static void walkReachable(Scop *S, LoopInfo *LI,
248                           ArrayRef<VirtualInstruction> RootInsts,
249                           ArrayRef<MemoryAccess *> RootAccs,
250                           DenseSet<VirtualInstruction> &UsedInsts,
251                           DenseSet<MemoryAccess *> &UsedAccs,
252                           ScopStmt *OnlyLocal = nullptr) {
253   UsedInsts.clear();
254   UsedAccs.clear();
255 
256   SmallVector<VirtualInstruction, 32> WorklistInsts;
257   SmallVector<MemoryAccess *, 32> WorklistAccs;
258 
259   WorklistInsts.append(RootInsts.begin(), RootInsts.end());
260   WorklistAccs.append(RootAccs.begin(), RootAccs.end());
261 
262   auto AddToWorklist = [&](VirtualUse VUse) {
263     switch (VUse.getKind()) {
264     case VirtualUse::Block:
265     case VirtualUse::Constant:
266     case VirtualUse::Synthesizable:
267     case VirtualUse::Hoisted:
268       break;
269     case VirtualUse::ReadOnly:
270       // Read-only scalars only have MemoryAccesses if ModelReadOnlyScalars is
271       // enabled.
272       if (!VUse.getMemoryAccess())
273         break;
274       LLVM_FALLTHROUGH;
275     case VirtualUse::Inter:
276       assert(VUse.getMemoryAccess());
277       WorklistAccs.push_back(VUse.getMemoryAccess());
278       break;
279     case VirtualUse::Intra:
280       WorklistInsts.emplace_back(VUse.getUser(),
281                                  cast<Instruction>(VUse.getValue()));
282       break;
283     }
284   };
285 
286   while (true) {
287     // We have two worklists to process: Only when the MemoryAccess worklist is
288     // empty, we process the instruction worklist.
289 
290     while (!WorklistAccs.empty()) {
291       auto *Acc = WorklistAccs.pop_back_val();
292 
293       ScopStmt *Stmt = Acc->getStatement();
294       if (OnlyLocal && Stmt != OnlyLocal)
295         continue;
296 
297       auto Inserted = UsedAccs.insert(Acc);
298       if (!Inserted.second)
299         continue;
300 
301       if (Acc->isRead()) {
302         const ScopArrayInfo *SAI = Acc->getScopArrayInfo();
303 
304         if (Acc->isOriginalValueKind()) {
305           MemoryAccess *DefAcc = S->getValueDef(SAI);
306 
307           // Accesses to read-only values do not have a definition.
308           if (DefAcc)
309             WorklistAccs.push_back(S->getValueDef(SAI));
310         }
311 
312         if (Acc->isOriginalAnyPHIKind()) {
313           auto IncomingMAs = S->getPHIIncomings(SAI);
314           WorklistAccs.append(IncomingMAs.begin(), IncomingMAs.end());
315         }
316       }
317 
318       if (Acc->isWrite()) {
319         if (Acc->isOriginalValueKind() ||
320             (Acc->isOriginalArrayKind() && Acc->getAccessValue())) {
321           Loop *Scope = Stmt->getSurroundingLoop();
322           VirtualUse VUse =
323               VirtualUse::create(S, Stmt, Scope, Acc->getAccessValue(), true);
324           AddToWorklist(VUse);
325         }
326 
327         if (Acc->isOriginalAnyPHIKind()) {
328           for (auto Incoming : Acc->getIncoming()) {
329             VirtualUse VUse = VirtualUse::create(
330                 S, Stmt, LI->getLoopFor(Incoming.first), Incoming.second, true);
331             AddToWorklist(VUse);
332           }
333         }
334 
335         if (Acc->isOriginalArrayKind())
336           WorklistInsts.emplace_back(Stmt, Acc->getAccessInstruction());
337       }
338     }
339 
340     // If both worklists are empty, stop walking.
341     if (WorklistInsts.empty())
342       break;
343 
344     VirtualInstruction VInst = WorklistInsts.pop_back_val();
345     ScopStmt *Stmt = VInst.getStmt();
346     Instruction *Inst = VInst.getInstruction();
347 
348     // Do not process statements other than the local.
349     if (OnlyLocal && Stmt != OnlyLocal)
350       continue;
351 
352     auto InsertResult = UsedInsts.insert(VInst);
353     if (!InsertResult.second)
354       continue;
355 
356     // Add all operands to the worklists.
357     if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
358       if (MemoryAccess *PHIRead = Stmt->lookupPHIReadOf(PHI))
359         WorklistAccs.push_back(PHIRead);
360     } else {
361       for (VirtualUse VUse : VInst.operands())
362         AddToWorklist(VUse);
363     }
364 
365     // If there is an array access, also add its MemoryAccesses to the worklist.
366     const MemoryAccessList *Accs = Stmt->lookupArrayAccessesFor(Inst);
367     if (!Accs)
368       continue;
369 
370     for (MemoryAccess *Acc : *Accs)
371       WorklistAccs.push_back(Acc);
372   }
373 }
374 
375 void polly::markReachable(Scop *S, LoopInfo *LI,
376                           DenseSet<VirtualInstruction> &UsedInsts,
377                           DenseSet<MemoryAccess *> &UsedAccs,
378                           ScopStmt *OnlyLocal) {
379   SmallVector<VirtualInstruction, 32> RootInsts;
380   SmallVector<MemoryAccess *, 32> RootAccs;
381 
382   if (OnlyLocal) {
383     addRoots(OnlyLocal, RootInsts, RootAccs, true);
384   } else {
385     for (auto &Stmt : *S)
386       addRoots(&Stmt, RootInsts, RootAccs, false);
387   }
388 
389   walkReachable(S, LI, RootInsts, RootAccs, UsedInsts, UsedAccs, OnlyLocal);
390 }
391