ScopBuilder.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //===- polly/ScopBuilder.h --------------------------------------*- 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. // Create a polyhedral description for a static control flow region.
  10. //
  11. // The pass creates a polyhedral description of the Scops detected by the SCoP
  12. // detection derived from their LLVM-IR code.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef POLLY_SCOPBUILDER_H
  16. #define POLLY_SCOPBUILDER_H
  17. #include "polly/ScopInfo.h"
  18. #include "polly/Support/ScopHelper.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/SetVector.h"
  21. namespace polly {
  22. using llvm::SmallSetVector;
  23. class ScopDetection;
  24. /// Command line switch whether to model read-only accesses.
  25. extern bool ModelReadOnlyScalars;
  26. /// Build the Polly IR (Scop and ScopStmt) on a Region.
  27. class ScopBuilder {
  28. /// The AAResults to build AliasSetTracker.
  29. AAResults &AA;
  30. /// Target data for element size computing.
  31. const DataLayout &DL;
  32. /// DominatorTree to reason about guaranteed execution.
  33. DominatorTree &DT;
  34. /// LoopInfo for information about loops.
  35. LoopInfo &LI;
  36. /// Valid Regions for Scop
  37. ScopDetection &SD;
  38. /// The ScalarEvolution to help building Scop.
  39. ScalarEvolution &SE;
  40. /// An optimization diagnostic interface to add optimization remarks.
  41. OptimizationRemarkEmitter &ORE;
  42. /// Set of instructions that might read any memory location.
  43. SmallVector<std::pair<ScopStmt *, Instruction *>, 16> GlobalReads;
  44. /// Set of all accessed array base pointers.
  45. SmallSetVector<Value *, 16> ArrayBasePointers;
  46. // The Scop
  47. std::unique_ptr<Scop> scop;
  48. /// Collection to hold taken assumptions.
  49. ///
  50. /// There are two reasons why we want to record assumptions first before we
  51. /// add them to the assumed/invalid context:
  52. /// 1) If the SCoP is not profitable or otherwise invalid without the
  53. /// assumed/invalid context we do not have to compute it.
  54. /// 2) Information about the context are gathered rather late in the SCoP
  55. /// construction (basically after we know all parameters), thus the user
  56. /// might see overly complicated assumptions to be taken while they will
  57. /// only be simplified later on.
  58. RecordedAssumptionsTy RecordedAssumptions;
  59. // Methods for pattern matching against Fortran code generated by dragonegg.
  60. // @{
  61. /// Try to match for the descriptor of a Fortran array whose allocation
  62. /// is not visible. That is, we can see the load/store into the memory, but
  63. /// we don't actually know where the memory is allocated. If ALLOCATE had been
  64. /// called on the Fortran array, then we will see the lowered malloc() call.
  65. /// If not, this is dubbed as an "invisible allocation".
  66. ///
  67. /// "<descriptor>" is the descriptor of the Fortran array.
  68. ///
  69. /// Pattern match for "@descriptor":
  70. /// 1. %mem = load double*, double** bitcast (%"struct.array1_real(kind=8)"*
  71. /// <descriptor> to double**), align 32
  72. ///
  73. /// 2. [%slot = getelementptr inbounds i8, i8* %mem, i64 <index>]
  74. /// 2 is optional because if you are writing to the 0th index, you don't
  75. /// need a GEP.
  76. ///
  77. /// 3.1 store/load <memtype> <val>, <memtype>* %slot
  78. /// 3.2 store/load <memtype> <val>, <memtype>* %mem
  79. ///
  80. /// @see polly::MemoryAccess, polly::ScopArrayInfo
  81. ///
  82. /// @note assumes -polly-canonicalize has been run.
  83. ///
  84. /// @param Inst The LoadInst/StoreInst that accesses the memory.
  85. ///
  86. /// @returns Reference to <descriptor> on success, nullptr on failure.
  87. Value *findFADAllocationInvisible(MemAccInst Inst);
  88. /// Try to match for the descriptor of a Fortran array whose allocation
  89. /// call is visible. When we have a Fortran array, we try to look for a
  90. /// Fortran array where we can see the lowered ALLOCATE call. ALLOCATE
  91. /// is materialized as a malloc(...) which we pattern match for.
  92. ///
  93. /// Pattern match for "%untypedmem":
  94. /// 1. %untypedmem = i8* @malloc(...)
  95. ///
  96. /// 2. %typedmem = bitcast i8* %untypedmem to <memtype>
  97. ///
  98. /// 3. [%slot = getelementptr inbounds i8, i8* %typedmem, i64 <index>]
  99. /// 3 is optional because if you are writing to the 0th index, you don't
  100. /// need a GEP.
  101. ///
  102. /// 4.1 store/load <memtype> <val>, <memtype>* %slot, align 8
  103. /// 4.2 store/load <memtype> <val>, <memtype>* %mem, align 8
  104. ///
  105. /// @see polly::MemoryAccess, polly::ScopArrayInfo
  106. ///
  107. /// @note assumes -polly-canonicalize has been run.
  108. ///
  109. /// @param Inst The LoadInst/StoreInst that accesses the memory.
  110. ///
  111. /// @returns Reference to %untypedmem on success, nullptr on failure.
  112. Value *findFADAllocationVisible(MemAccInst Inst);
  113. // @}
  114. // Build the SCoP for Region @p R.
  115. void buildScop(Region &R, AssumptionCache &AC);
  116. /// Adjust the dimensions of @p Dom that was constructed for @p OldL
  117. /// to be compatible to domains constructed for loop @p NewL.
  118. ///
  119. /// This function assumes @p NewL and @p OldL are equal or there is a CFG
  120. /// edge from @p OldL to @p NewL.
  121. isl::set adjustDomainDimensions(isl::set Dom, Loop *OldL, Loop *NewL);
  122. /// Compute the domain for each basic block in @p R.
  123. ///
  124. /// @param R The region we currently traverse.
  125. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  126. /// region.
  127. ///
  128. /// @returns True if there was no problem and false otherwise.
  129. bool buildDomains(Region *R,
  130. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  131. /// Compute the branching constraints for each basic block in @p R.
  132. ///
  133. /// @param R The region we currently build branching conditions
  134. /// for.
  135. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  136. /// region.
  137. ///
  138. /// @returns True if there was no problem and false otherwise.
  139. bool buildDomainsWithBranchConstraints(
  140. Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  141. /// Build the conditions sets for the terminator @p TI in the @p Domain.
  142. ///
  143. /// This will fill @p ConditionSets with the conditions under which control
  144. /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
  145. /// have as many elements as @p TI has successors.
  146. bool buildConditionSets(BasicBlock *BB, Instruction *TI, Loop *L,
  147. __isl_keep isl_set *Domain,
  148. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  149. SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
  150. /// Build the conditions sets for the branch condition @p Condition in
  151. /// the @p Domain.
  152. ///
  153. /// This will fill @p ConditionSets with the conditions under which control
  154. /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
  155. /// have as many elements as @p TI has successors. If @p TI is nullptr the
  156. /// context under which @p Condition is true/false will be returned as the
  157. /// new elements of @p ConditionSets.
  158. bool buildConditionSets(BasicBlock *BB, Value *Condition, Instruction *TI,
  159. Loop *L, __isl_keep isl_set *Domain,
  160. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  161. SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
  162. /// Build the conditions sets for the switch @p SI in the @p Domain.
  163. ///
  164. /// This will fill @p ConditionSets with the conditions under which control
  165. /// will be moved from @p SI to its successors. Hence, @p ConditionSets will
  166. /// have as many elements as @p SI has successors.
  167. bool buildConditionSets(BasicBlock *BB, SwitchInst *SI, Loop *L,
  168. __isl_keep isl_set *Domain,
  169. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  170. SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
  171. /// Build condition sets for unsigned ICmpInst(s).
  172. /// Special handling is required for unsigned operands to ensure that if
  173. /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
  174. /// it should wrap around.
  175. ///
  176. /// @param IsStrictUpperBound holds information on the predicate relation
  177. /// between TestVal and UpperBound, i.e,
  178. /// TestVal < UpperBound OR TestVal <= UpperBound
  179. __isl_give isl_set *buildUnsignedConditionSets(
  180. BasicBlock *BB, Value *Condition, __isl_keep isl_set *Domain,
  181. const SCEV *SCEV_TestVal, const SCEV *SCEV_UpperBound,
  182. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  183. bool IsStrictUpperBound);
  184. /// Propagate the domain constraints through the region @p R.
  185. ///
  186. /// @param R The region we currently build branching
  187. /// conditions for.
  188. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  189. /// region.
  190. ///
  191. /// @returns True if there was no problem and false otherwise.
  192. bool propagateDomainConstraints(
  193. Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  194. /// Propagate domains that are known due to graph properties.
  195. ///
  196. /// As a CFG is mostly structured we use the graph properties to propagate
  197. /// domains without the need to compute all path conditions. In particular,
  198. /// if a block A dominates a block B and B post-dominates A we know that the
  199. /// domain of B is a superset of the domain of A. As we do not have
  200. /// post-dominator information available here we use the less precise region
  201. /// information. Given a region R, we know that the exit is always executed
  202. /// if the entry was executed, thus the domain of the exit is a superset of
  203. /// the domain of the entry. In case the exit can only be reached from
  204. /// within the region the domains are in fact equal. This function will use
  205. /// this property to avoid the generation of condition constraints that
  206. /// determine when a branch is taken. If @p BB is a region entry block we
  207. /// will propagate its domain to the region exit block. Additionally, we put
  208. /// the region exit block in the @p FinishedExitBlocks set so we can later
  209. /// skip edges from within the region to that block.
  210. ///
  211. /// @param BB The block for which the domain is currently
  212. /// propagated.
  213. /// @param BBLoop The innermost affine loop surrounding @p BB.
  214. /// @param FinishedExitBlocks Set of region exits the domain was set for.
  215. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  216. /// region.
  217. void propagateDomainConstraintsToRegionExit(
  218. BasicBlock *BB, Loop *BBLoop,
  219. SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks,
  220. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  221. /// Propagate invalid domains of statements through @p R.
  222. ///
  223. /// This method will propagate invalid statement domains through @p R and at
  224. /// the same time add error block domains to them. Additionally, the domains
  225. /// of error statements and those only reachable via error statements will
  226. /// be replaced by an empty set. Later those will be removed completely.
  227. ///
  228. /// @param R The currently traversed region.
  229. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  230. /// region.
  231. //
  232. /// @returns True if there was no problem and false otherwise.
  233. bool propagateInvalidStmtDomains(
  234. Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  235. /// Compute the union of predecessor domains for @p BB.
  236. ///
  237. /// To compute the union of all domains of predecessors of @p BB this
  238. /// function applies similar reasoning on the CFG structure as described for
  239. /// @see propagateDomainConstraintsToRegionExit
  240. ///
  241. /// @param BB The block for which the predecessor domains are collected.
  242. /// @param Domain The domain under which BB is executed.
  243. ///
  244. /// @returns The domain under which @p BB is executed.
  245. isl::set getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain);
  246. /// Add loop carried constraints to the header block of the loop @p L.
  247. ///
  248. /// @param L The loop to process.
  249. /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
  250. /// region.
  251. ///
  252. /// @returns True if there was no problem and false otherwise.
  253. bool addLoopBoundsToHeaderDomain(
  254. Loop *L, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  255. /// Compute the isl representation for the SCEV @p E in this BB.
  256. ///
  257. /// @param BB The BB for which isl representation is to be
  258. /// computed.
  259. /// @param InvalidDomainMap A map of BB to their invalid domains.
  260. /// @param E The SCEV that should be translated.
  261. /// @param NonNegative Flag to indicate the @p E has to be
  262. /// non-negative.
  263. ///
  264. /// Note that this function will also adjust the invalid context
  265. /// accordingly.
  266. __isl_give isl_pw_aff *
  267. getPwAff(BasicBlock *BB, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
  268. const SCEV *E, bool NonNegative = false);
  269. /// Create equivalence classes for required invariant accesses.
  270. ///
  271. /// These classes will consolidate multiple required invariant loads from the
  272. /// same address in order to keep the number of dimensions in the SCoP
  273. /// description small. For each such class equivalence class only one
  274. /// representing element, hence one required invariant load, will be chosen
  275. /// and modeled as parameter. The method
  276. /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
  277. /// equivalence class with the representing element that is modeled. As a
  278. /// consequence Scop::getIdForParam() will only return an id for the
  279. /// representing element of each equivalence class, thus for each required
  280. /// invariant location.
  281. void buildInvariantEquivalenceClasses();
  282. /// Try to build a multi-dimensional fixed sized MemoryAccess from the
  283. /// Load/Store instruction.
  284. ///
  285. /// @param Inst The Load/Store instruction that access the memory
  286. /// @param Stmt The parent statement of the instruction
  287. ///
  288. /// @returns True if the access could be built, False otherwise.
  289. bool buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt);
  290. /// Try to build a multi-dimensional parametric sized MemoryAccess.
  291. /// from the Load/Store instruction.
  292. ///
  293. /// @param Inst The Load/Store instruction that access the memory
  294. /// @param Stmt The parent statement of the instruction
  295. ///
  296. /// @returns True if the access could be built, False otherwise.
  297. bool buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt);
  298. /// Try to build a MemoryAccess for a memory intrinsic.
  299. ///
  300. /// @param Inst The instruction that access the memory
  301. /// @param Stmt The parent statement of the instruction
  302. ///
  303. /// @returns True if the access could be built, False otherwise.
  304. bool buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt);
  305. /// Try to build a MemoryAccess for a call instruction.
  306. ///
  307. /// @param Inst The call instruction that access the memory
  308. /// @param Stmt The parent statement of the instruction
  309. ///
  310. /// @returns True if the access could be built, False otherwise.
  311. bool buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt);
  312. /// Build a single-dimensional parametric sized MemoryAccess
  313. /// from the Load/Store instruction.
  314. ///
  315. /// @param Inst The Load/Store instruction that access the memory
  316. /// @param Stmt The parent statement of the instruction
  317. void buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt);
  318. /// Finalize all access relations.
  319. ///
  320. /// When building up access relations, temporary access relations that
  321. /// correctly represent each individual access are constructed. However, these
  322. /// access relations can be inconsistent or non-optimal when looking at the
  323. /// set of accesses as a whole. This function finalizes the memory accesses
  324. /// and constructs a globally consistent state.
  325. void finalizeAccesses();
  326. /// Update access dimensionalities.
  327. ///
  328. /// When detecting memory accesses different accesses to the same array may
  329. /// have built with different dimensionality, as outer zero-values dimensions
  330. /// may not have been recognized as separate dimensions. This function goes
  331. /// again over all memory accesses and updates their dimensionality to match
  332. /// the dimensionality of the underlying ScopArrayInfo object.
  333. void updateAccessDimensionality();
  334. /// Fold size constants to the right.
  335. ///
  336. /// In case all memory accesses in a given dimension are multiplied with a
  337. /// common constant, we can remove this constant from the individual access
  338. /// functions and move it to the size of the memory access. We do this as this
  339. /// increases the size of the innermost dimension, consequently widens the
  340. /// valid range the array subscript in this dimension can evaluate to, and
  341. /// as a result increases the likelihood that our delinearization is
  342. /// correct.
  343. ///
  344. /// Example:
  345. ///
  346. /// A[][n]
  347. /// S[i,j] -> A[2i][2j+1]
  348. /// S[i,j] -> A[2i][2j]
  349. ///
  350. /// =>
  351. ///
  352. /// A[][2n]
  353. /// S[i,j] -> A[i][2j+1]
  354. /// S[i,j] -> A[i][2j]
  355. ///
  356. /// Constants in outer dimensions can arise when the elements of a parametric
  357. /// multi-dimensional array are not elementary data types, but e.g.,
  358. /// structures.
  359. void foldSizeConstantsToRight();
  360. /// Fold memory accesses to handle parametric offset.
  361. ///
  362. /// As a post-processing step, we 'fold' memory accesses to parametric
  363. /// offsets in the access functions. @see MemoryAccess::foldAccess for
  364. /// details.
  365. void foldAccessRelations();
  366. /// Assume that all memory accesses are within bounds.
  367. ///
  368. /// After we have built a model of all memory accesses, we need to assume
  369. /// that the model we built matches reality -- aka. all modeled memory
  370. /// accesses always remain within bounds. We do this as last step, after
  371. /// all memory accesses have been modeled and canonicalized.
  372. void assumeNoOutOfBounds();
  373. /// Mark arrays that have memory accesses with FortranArrayDescriptor.
  374. void markFortranArrays();
  375. /// Build the alias checks for this SCoP.
  376. bool buildAliasChecks();
  377. /// A vector of memory accesses that belong to an alias group.
  378. using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
  379. /// A vector of alias groups.
  380. using AliasGroupVectorTy = SmallVector<AliasGroupTy, 4>;
  381. /// Build a given alias group and its access data.
  382. ///
  383. /// @param AliasGroup The alias group to build.
  384. /// @param HasWriteAccess A set of arrays through which memory is not only
  385. /// read, but also written.
  386. //
  387. /// @returns True if __no__ error occurred, false otherwise.
  388. bool buildAliasGroup(AliasGroupTy &AliasGroup,
  389. DenseSet<const ScopArrayInfo *> HasWriteAccess);
  390. /// Build all alias groups for this SCoP.
  391. ///
  392. /// @returns True if __no__ error occurred, false otherwise.
  393. bool buildAliasGroups();
  394. /// Build alias groups for all memory accesses in the Scop.
  395. ///
  396. /// Using the alias analysis and an alias set tracker we build alias sets
  397. /// for all memory accesses inside the Scop. For each alias set we then map
  398. /// the aliasing pointers back to the memory accesses we know, thus obtain
  399. /// groups of memory accesses which might alias. We also collect the set of
  400. /// arrays through which memory is written.
  401. ///
  402. /// @returns A pair consistent of a vector of alias groups and a set of arrays
  403. /// through which memory is written.
  404. std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
  405. buildAliasGroupsForAccesses();
  406. /// Split alias groups by iteration domains.
  407. ///
  408. /// We split each group based on the domains of the minimal/maximal accesses.
  409. /// That means two minimal/maximal accesses are only in a group if their
  410. /// access domains intersect. Otherwise, they are in different groups.
  411. ///
  412. /// @param AliasGroups The alias groups to split
  413. void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
  414. /// Build an instance of MemoryAccess from the Load/Store instruction.
  415. ///
  416. /// @param Inst The Load/Store instruction that access the memory
  417. /// @param Stmt The parent statement of the instruction
  418. void buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt);
  419. /// Analyze and extract the cross-BB scalar dependences (or, dataflow
  420. /// dependencies) of an instruction.
  421. ///
  422. /// @param UserStmt The statement @p Inst resides in.
  423. /// @param Inst The instruction to be analyzed.
  424. void buildScalarDependences(ScopStmt *UserStmt, Instruction *Inst);
  425. /// Build the escaping dependences for @p Inst.
  426. ///
  427. /// Search for uses of the llvm::Value defined by @p Inst that are not
  428. /// within the SCoP. If there is such use, add a SCALAR WRITE such that
  429. /// it is available after the SCoP as escaping value.
  430. ///
  431. /// @param Inst The instruction to be analyzed.
  432. void buildEscapingDependences(Instruction *Inst);
  433. /// Create MemoryAccesses for the given PHI node in the given region.
  434. ///
  435. /// @param PHIStmt The statement @p PHI resides in.
  436. /// @param PHI The PHI node to be handled
  437. /// @param NonAffineSubRegion The non affine sub-region @p PHI is in.
  438. /// @param IsExitBlock Flag to indicate that @p PHI is in the exit BB.
  439. void buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI,
  440. Region *NonAffineSubRegion, bool IsExitBlock = false);
  441. /// Build the access functions for the subregion @p SR.
  442. void buildAccessFunctions();
  443. /// Should an instruction be modeled in a ScopStmt.
  444. ///
  445. /// @param Inst The instruction to check.
  446. /// @param L The loop in which context the instruction is looked at.
  447. ///
  448. /// @returns True if the instruction should be modeled.
  449. bool shouldModelInst(Instruction *Inst, Loop *L);
  450. /// Create one or more ScopStmts for @p BB.
  451. ///
  452. /// Consecutive instructions are associated to the same statement until a
  453. /// separator is found.
  454. void buildSequentialBlockStmts(BasicBlock *BB, bool SplitOnStore = false);
  455. /// Create one or more ScopStmts for @p BB using equivalence classes.
  456. ///
  457. /// Instructions of a basic block that belong to the same equivalence class
  458. /// are added to the same statement.
  459. void buildEqivClassBlockStmts(BasicBlock *BB);
  460. /// Create ScopStmt for all BBs and non-affine subregions of @p SR.
  461. ///
  462. /// @param SR A subregion of @p R.
  463. ///
  464. /// Some of the statements might be optimized away later when they do not
  465. /// access any memory and thus have no effect.
  466. void buildStmts(Region &SR);
  467. /// Build the access functions for the statement @p Stmt in or represented by
  468. /// @p BB.
  469. ///
  470. /// @param Stmt Statement to add MemoryAccesses to.
  471. /// @param BB A basic block in @p R.
  472. /// @param NonAffineSubRegion The non affine sub-region @p BB is in.
  473. void buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB,
  474. Region *NonAffineSubRegion = nullptr);
  475. /// Create a new MemoryAccess object and add it to #AccFuncMap.
  476. ///
  477. /// @param Stmt The statement where the access takes place.
  478. /// @param Inst The instruction doing the access. It is not necessarily
  479. /// inside @p BB.
  480. /// @param AccType The kind of access.
  481. /// @param BaseAddress The accessed array's base address.
  482. /// @param ElemType The type of the accessed array elements.
  483. /// @param Affine Whether all subscripts are affine expressions.
  484. /// @param AccessValue Value read or written.
  485. /// @param Subscripts Access subscripts per dimension.
  486. /// @param Sizes The array dimension's sizes.
  487. /// @param Kind The kind of memory accessed.
  488. ///
  489. /// @return The created MemoryAccess, or nullptr if the access is not within
  490. /// the SCoP.
  491. MemoryAccess *addMemoryAccess(ScopStmt *Stmt, Instruction *Inst,
  492. MemoryAccess::AccessType AccType,
  493. Value *BaseAddress, Type *ElemType, bool Affine,
  494. Value *AccessValue,
  495. ArrayRef<const SCEV *> Subscripts,
  496. ArrayRef<const SCEV *> Sizes, MemoryKind Kind);
  497. /// Create a MemoryAccess that represents either a LoadInst or
  498. /// StoreInst.
  499. ///
  500. /// @param Stmt The statement to add the MemoryAccess to.
  501. /// @param MemAccInst The LoadInst or StoreInst.
  502. /// @param AccType The kind of access.
  503. /// @param BaseAddress The accessed array's base address.
  504. /// @param ElemType The type of the accessed array elements.
  505. /// @param IsAffine Whether all subscripts are affine expressions.
  506. /// @param Subscripts Access subscripts per dimension.
  507. /// @param Sizes The array dimension's sizes.
  508. /// @param AccessValue Value read or written.
  509. ///
  510. /// @see MemoryKind
  511. void addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst,
  512. MemoryAccess::AccessType AccType, Value *BaseAddress,
  513. Type *ElemType, bool IsAffine,
  514. ArrayRef<const SCEV *> Subscripts,
  515. ArrayRef<const SCEV *> Sizes, Value *AccessValue);
  516. /// Create a MemoryAccess for writing an llvm::Instruction.
  517. ///
  518. /// The access will be created at the position of @p Inst.
  519. ///
  520. /// @param Inst The instruction to be written.
  521. ///
  522. /// @see ensureValueRead()
  523. /// @see MemoryKind
  524. void ensureValueWrite(Instruction *Inst);
  525. /// Ensure an llvm::Value is available in the BB's statement, creating a
  526. /// MemoryAccess for reloading it if necessary.
  527. ///
  528. /// @param V The value expected to be loaded.
  529. /// @param UserStmt Where to reload the value.
  530. ///
  531. /// @see ensureValueStore()
  532. /// @see MemoryKind
  533. void ensureValueRead(Value *V, ScopStmt *UserStmt);
  534. /// Create a write MemoryAccess for the incoming block of a phi node.
  535. ///
  536. /// Each of the incoming blocks write their incoming value to be picked in the
  537. /// phi's block.
  538. ///
  539. /// @param PHI PHINode under consideration.
  540. /// @param IncomingStmt The statement to add the MemoryAccess to.
  541. /// @param IncomingBlock Some predecessor block.
  542. /// @param IncomingValue @p PHI's value when coming from @p IncomingBlock.
  543. /// @param IsExitBlock When true, uses the .s2a alloca instead of the
  544. /// .phiops one. Required for values escaping through a
  545. /// PHINode in the SCoP region's exit block.
  546. /// @see addPHIReadAccess()
  547. /// @see MemoryKind
  548. void ensurePHIWrite(PHINode *PHI, ScopStmt *IncomintStmt,
  549. BasicBlock *IncomingBlock, Value *IncomingValue,
  550. bool IsExitBlock);
  551. /// Add user provided parameter constraints to context (command line).
  552. void addUserContext();
  553. /// Add user provided parameter constraints to context (source code).
  554. void addUserAssumptions(AssumptionCache &AC,
  555. DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
  556. /// Add all recorded assumptions to the assumed context.
  557. void addRecordedAssumptions();
  558. /// Create a MemoryAccess for reading the value of a phi.
  559. ///
  560. /// The modeling assumes that all incoming blocks write their incoming value
  561. /// to the same location. Thus, this access will read the incoming block's
  562. /// value as instructed by this @p PHI.
  563. ///
  564. /// @param PHIStmt Statement @p PHI resides in.
  565. /// @param PHI PHINode under consideration; the READ access will be added
  566. /// here.
  567. ///
  568. /// @see ensurePHIWrite()
  569. /// @see MemoryKind
  570. void addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI);
  571. /// Wrapper function to calculate minimal/maximal accesses to each array.
  572. bool calculateMinMaxAccess(AliasGroupTy AliasGroup,
  573. Scop::MinMaxVectorTy &MinMaxAccesses);
  574. /// Build the domain of @p Stmt.
  575. void buildDomain(ScopStmt &Stmt);
  576. /// Fill NestLoops with loops surrounding @p Stmt.
  577. void collectSurroundingLoops(ScopStmt &Stmt);
  578. /// Check for reductions in @p Stmt.
  579. ///
  580. /// Iterate over all store memory accesses and check for valid binary
  581. /// reduction like chains. For all candidates we check if they have the same
  582. /// base address and there are no other accesses which overlap with them. The
  583. /// base address check rules out impossible reductions candidates early. The
  584. /// overlap check, together with the "only one user" check in
  585. /// collectCandidateReductionLoads, guarantees that none of the intermediate
  586. /// results will escape during execution of the loop nest. We basically check
  587. /// here that no other memory access can access the same memory as the
  588. /// potential reduction.
  589. void checkForReductions(ScopStmt &Stmt);
  590. /// Verify that all required invariant loads have been hoisted.
  591. ///
  592. /// Invariant load hoisting is not guaranteed to hoist all loads that were
  593. /// assumed to be scop invariant during scop detection. This function checks
  594. /// for cases where the hoisting failed, but where it would have been
  595. /// necessary for our scop modeling to be correct. In case of insufficient
  596. /// hoisting the scop is marked as invalid.
  597. ///
  598. /// In the example below Bound[1] is required to be invariant:
  599. ///
  600. /// for (int i = 1; i < Bound[0]; i++)
  601. /// for (int j = 1; j < Bound[1]; j++)
  602. /// ...
  603. void verifyInvariantLoads();
  604. /// Hoist invariant memory loads and check for required ones.
  605. ///
  606. /// We first identify "common" invariant loads, thus loads that are invariant
  607. /// and can be hoisted. Then we check if all required invariant loads have
  608. /// been identified as (common) invariant. A load is a required invariant load
  609. /// if it was assumed to be invariant during SCoP detection, e.g., to assume
  610. /// loop bounds to be affine or runtime alias checks to be placeable. In case
  611. /// a required invariant load was not identified as (common) invariant we will
  612. /// drop this SCoP. An example for both "common" as well as required invariant
  613. /// loads is given below:
  614. ///
  615. /// for (int i = 1; i < *LB[0]; i++)
  616. /// for (int j = 1; j < *LB[1]; j++)
  617. /// A[i][j] += A[0][0] + (*V);
  618. ///
  619. /// Common inv. loads: V, A[0][0], LB[0], LB[1]
  620. /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
  621. void hoistInvariantLoads();
  622. /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
  623. void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
  624. /// Check if @p MA can always be hoisted without execution context.
  625. bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
  626. bool MAInvalidCtxIsEmpty,
  627. bool NonHoistableCtxIsEmpty);
  628. /// Return true if and only if @p LI is a required invariant load.
  629. bool isRequiredInvariantLoad(LoadInst *LI) const {
  630. return scop->getRequiredInvariantLoads().count(LI);
  631. }
  632. /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
  633. bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
  634. /// Return the context under which the access cannot be hoisted.
  635. ///
  636. /// @param Access The access to check.
  637. /// @param Writes The set of all memory writes in the scop.
  638. ///
  639. /// @return Return the context under which the access cannot be hoisted or a
  640. /// nullptr if it cannot be hoisted at all.
  641. isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
  642. /// Collect loads which might form a reduction chain with @p StoreMA.
  643. ///
  644. /// Check if the stored value for @p StoreMA is a binary operator with one or
  645. /// two loads as operands. If the binary operand is commutative & associative,
  646. /// used only once (by @p StoreMA) and its load operands are also used only
  647. /// once, we have found a possible reduction chain. It starts at an operand
  648. /// load and includes the binary operator and @p StoreMA.
  649. ///
  650. /// Note: We allow only one use to ensure the load and binary operator cannot
  651. /// escape this block or into any other store except @p StoreMA.
  652. void collectCandidateReductionLoads(MemoryAccess *StoreMA,
  653. SmallVectorImpl<MemoryAccess *> &Loads);
  654. /// Build the access relation of all memory accesses of @p Stmt.
  655. void buildAccessRelations(ScopStmt &Stmt);
  656. /// Canonicalize arrays with base pointers from the same equivalence class.
  657. ///
  658. /// Some context: in our normal model we assume that each base pointer is
  659. /// related to a single specific memory region, where memory regions
  660. /// associated with different base pointers are disjoint. Consequently we do
  661. /// not need to compute additional data dependences that model possible
  662. /// overlaps of these memory regions. To verify our assumption we compute
  663. /// alias checks that verify that modeled arrays indeed do not overlap. In
  664. /// case an overlap is detected the runtime check fails and we fall back to
  665. /// the original code.
  666. ///
  667. /// In case of arrays where the base pointers are know to be identical,
  668. /// because they are dynamically loaded by accesses that are in the same
  669. /// invariant load equivalence class, such run-time alias check would always
  670. /// be false.
  671. ///
  672. /// This function makes sure that we do not generate consistently failing
  673. /// run-time checks for code that contains distinct arrays with known
  674. /// equivalent base pointers. It identifies for each invariant load
  675. /// equivalence class a single canonical array and canonicalizes all memory
  676. /// accesses that reference arrays that have base pointers that are known to
  677. /// be equal to the base pointer of such a canonical array to this canonical
  678. /// array.
  679. ///
  680. /// We currently do not canonicalize arrays for which certain memory accesses
  681. /// have been hoisted as loop invariant.
  682. void canonicalizeDynamicBasePtrs();
  683. /// Construct the schedule of this SCoP.
  684. void buildSchedule();
  685. /// A loop stack element to keep track of per-loop information during
  686. /// schedule construction.
  687. using LoopStackElementTy = struct LoopStackElement {
  688. // The loop for which we keep information.
  689. Loop *L;
  690. // The (possibly incomplete) schedule for this loop.
  691. isl::schedule Schedule;
  692. // The number of basic blocks in the current loop, for which a schedule has
  693. // already been constructed.
  694. unsigned NumBlocksProcessed;
  695. LoopStackElement(Loop *L, isl::schedule S, unsigned NumBlocksProcessed)
  696. : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
  697. };
  698. /// The loop stack used for schedule construction.
  699. ///
  700. /// The loop stack keeps track of schedule information for a set of nested
  701. /// loops as well as an (optional) 'nullptr' loop that models the outermost
  702. /// schedule dimension. The loops in a loop stack always have a parent-child
  703. /// relation where the loop at position n is the parent of the loop at
  704. /// position n + 1.
  705. using LoopStackTy = SmallVector<LoopStackElementTy, 4>;
  706. /// Construct schedule information for a given Region and add the
  707. /// derived information to @p LoopStack.
  708. ///
  709. /// Given a Region we derive schedule information for all RegionNodes
  710. /// contained in this region ensuring that the assigned execution times
  711. /// correctly model the existing control flow relations.
  712. ///
  713. /// @param R The region which to process.
  714. /// @param LoopStack A stack of loops that are currently under
  715. /// construction.
  716. void buildSchedule(Region *R, LoopStackTy &LoopStack);
  717. /// Build Schedule for the region node @p RN and add the derived
  718. /// information to @p LoopStack.
  719. ///
  720. /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
  721. /// schedule for this @p RN and also finalize loop schedules in case the
  722. /// current @p RN completes the loop.
  723. ///
  724. /// In case @p RN is a not-non-affine Region, we delegate the construction to
  725. /// buildSchedule(Region *R, ...).
  726. ///
  727. /// @param RN The RegionNode region traversed.
  728. /// @param LoopStack A stack of loops that are currently under
  729. /// construction.
  730. void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack);
  731. public:
  732. explicit ScopBuilder(Region *R, AssumptionCache &AC, AAResults &AA,
  733. const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
  734. ScopDetection &SD, ScalarEvolution &SE,
  735. OptimizationRemarkEmitter &ORE);
  736. ScopBuilder(const ScopBuilder &) = delete;
  737. ScopBuilder &operator=(const ScopBuilder &) = delete;
  738. ~ScopBuilder() = default;
  739. /// Try to build the Polly IR of static control part on the current
  740. /// SESE-Region.
  741. ///
  742. /// @return Give up the ownership of the scop object or static control part
  743. /// for the region
  744. std::unique_ptr<Scop> getScop() { return std::move(scop); }
  745. };
  746. } // end namespace polly
  747. #endif // POLLY_SCOPBUILDER_H