19248fde5SEugene Zelenko //===- IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST -------===//
20c55cb60STobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60c55cb60STobias Grosser //
70c55cb60STobias Grosser //===----------------------------------------------------------------------===//
80c55cb60STobias Grosser //
90c55cb60STobias Grosser // This file contains the IslNodeBuilder, a class to translate an isl AST into
100c55cb60STobias Grosser // a LLVM-IR AST.
110c55cb60STobias Grosser //
120c55cb60STobias Grosser //===----------------------------------------------------------------------===//
130c55cb60STobias Grosser
140c55cb60STobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
150c55cb60STobias Grosser #include "polly/CodeGen/BlockGenerators.h"
160c55cb60STobias Grosser #include "polly/CodeGen/CodeGeneration.h"
170c55cb60STobias Grosser #include "polly/CodeGen/IslAst.h"
18ba0d0922STobias Grosser #include "polly/CodeGen/IslExprBuilder.h"
1989251edeSMichael Kruse #include "polly/CodeGen/LoopGeneratorsGOMP.h"
2089251edeSMichael Kruse #include "polly/CodeGen/LoopGeneratorsKMP.h"
218c5464a7SJohannes Doerfert #include "polly/CodeGen/RuntimeDebugBuilder.h"
228c5464a7SJohannes Doerfert #include "polly/Options.h"
230c55cb60STobias Grosser #include "polly/ScopInfo.h"
24670482dbSTobias Grosser #include "polly/Support/ISLTools.h"
250c55cb60STobias Grosser #include "polly/Support/SCEVValidator.h"
26ba0d0922STobias Grosser #include "polly/Support/ScopHelper.h"
27d5c87162SMichael Kruse #include "polly/Support/VirtualInstruction.h"
289248fde5SEugene Zelenko #include "llvm/ADT/APInt.h"
290c55cb60STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
309248fde5SEugene Zelenko #include "llvm/ADT/SetVector.h"
310c55cb60STobias Grosser #include "llvm/ADT/SmallPtrSet.h"
329248fde5SEugene Zelenko #include "llvm/ADT/Statistic.h"
330c55cb60STobias Grosser #include "llvm/Analysis/LoopInfo.h"
349248fde5SEugene Zelenko #include "llvm/Analysis/RegionInfo.h"
359248fde5SEugene Zelenko #include "llvm/Analysis/ScalarEvolution.h"
369248fde5SEugene Zelenko #include "llvm/Analysis/ScalarEvolutionExpressions.h"
379248fde5SEugene Zelenko #include "llvm/IR/BasicBlock.h"
389248fde5SEugene Zelenko #include "llvm/IR/Constant.h"
399248fde5SEugene Zelenko #include "llvm/IR/Constants.h"
40ba0d0922STobias Grosser #include "llvm/IR/DataLayout.h"
419248fde5SEugene Zelenko #include "llvm/IR/DerivedTypes.h"
429248fde5SEugene Zelenko #include "llvm/IR/Dominators.h"
439248fde5SEugene Zelenko #include "llvm/IR/Function.h"
449248fde5SEugene Zelenko #include "llvm/IR/InstrTypes.h"
459248fde5SEugene Zelenko #include "llvm/IR/Instruction.h"
469248fde5SEugene Zelenko #include "llvm/IR/Instructions.h"
479248fde5SEugene Zelenko #include "llvm/IR/Type.h"
489248fde5SEugene Zelenko #include "llvm/IR/Value.h"
499248fde5SEugene Zelenko #include "llvm/Support/Casting.h"
500c55cb60STobias Grosser #include "llvm/Support/CommandLine.h"
519248fde5SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
520c55cb60STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53ba0d0922STobias Grosser #include "isl/aff.h"
549248fde5SEugene Zelenko #include "isl/aff_type.h"
550c55cb60STobias Grosser #include "isl/ast.h"
560c55cb60STobias Grosser #include "isl/ast_build.h"
579248fde5SEugene Zelenko #include "isl/isl-noexceptions.h"
580c55cb60STobias Grosser #include "isl/map.h"
59ba0d0922STobias Grosser #include "isl/set.h"
60ba0d0922STobias Grosser #include "isl/union_map.h"
61cd524dc5STobias Grosser #include "isl/union_set.h"
629248fde5SEugene Zelenko #include "isl/val.h"
639248fde5SEugene Zelenko #include <algorithm>
649248fde5SEugene Zelenko #include <cassert>
659248fde5SEugene Zelenko #include <cstdint>
669248fde5SEugene Zelenko #include <cstring>
679248fde5SEugene Zelenko #include <string>
689248fde5SEugene Zelenko #include <utility>
699248fde5SEugene Zelenko #include <vector>
700c55cb60STobias Grosser
710c55cb60STobias Grosser using namespace llvm;
729248fde5SEugene Zelenko using namespace polly;
730c55cb60STobias Grosser
74dae2e928SJohannes Doerfert #define DEBUG_TYPE "polly-codegen"
75dae2e928SJohannes Doerfert
7681aa6e88SJohannes Doerfert STATISTIC(VersionedScops, "Number of SCoPs that required versioning.");
77dae2e928SJohannes Doerfert
7806ed5292SMichael Kruse STATISTIC(SequentialLoops, "Number of generated sequential for-loops");
7906ed5292SMichael Kruse STATISTIC(ParallelLoops, "Number of generated parallel for-loops");
8006ed5292SMichael Kruse STATISTIC(VectorLoops, "Number of generated vector for-loops");
8106ed5292SMichael Kruse STATISTIC(IfConditions, "Number of generated if-conditions");
8206ed5292SMichael Kruse
8389251edeSMichael Kruse /// OpenMP backend options
8489251edeSMichael Kruse enum class OpenMPBackend { GNU, LLVM };
8589251edeSMichael Kruse
868c5464a7SJohannes Doerfert static cl::opt<bool> PollyGenerateRTCPrint(
878c5464a7SJohannes Doerfert "polly-codegen-emit-rtc-print",
888c5464a7SJohannes Doerfert cl::desc("Emit code that prints the runtime check result dynamically."),
89*36c7d79dSFangrui Song cl::Hidden, cl::cat(PollyCategory));
908c5464a7SJohannes Doerfert
91b3c3d149STobias Grosser // If this option is set we always use the isl AST generator to regenerate
92b3c3d149STobias Grosser // memory accesses. Without this option set we regenerate expressions using the
93b3c3d149STobias Grosser // original SCEV expressions and only generate new expressions in case the
94b3c3d149STobias Grosser // access relation has been changed and consequently must be regenerated.
95b3c3d149STobias Grosser static cl::opt<bool> PollyGenerateExpressions(
96b3c3d149STobias Grosser "polly-codegen-generate-expressions",
97b3c3d149STobias Grosser cl::desc("Generate AST expressions for unmodified and modified accesses"),
98*36c7d79dSFangrui Song cl::Hidden, cl::cat(PollyCategory));
99b3c3d149STobias Grosser
100bd5c6039SRoman Gareev static cl::opt<int> PollyTargetFirstLevelCacheLineSize(
101bd5c6039SRoman Gareev "polly-target-first-level-cache-line-size",
102bd5c6039SRoman Gareev cl::desc("The size of the first level cache line size specified in bytes."),
103*36c7d79dSFangrui Song cl::Hidden, cl::init(64), cl::cat(PollyCategory));
104bd5c6039SRoman Gareev
10589251edeSMichael Kruse static cl::opt<OpenMPBackend> PollyOmpBackend(
10689251edeSMichael Kruse "polly-omp-backend", cl::desc("Choose the OpenMP library to use:"),
10789251edeSMichael Kruse cl::values(clEnumValN(OpenMPBackend::GNU, "GNU", "GNU OpenMP"),
10889251edeSMichael Kruse clEnumValN(OpenMPBackend::LLVM, "LLVM", "LLVM OpenMP")),
10989251edeSMichael Kruse cl::Hidden, cl::init(OpenMPBackend::GNU), cl::cat(PollyCategory));
11089251edeSMichael Kruse
getUpperBound(isl::ast_node_for For,ICmpInst::Predicate & Predicate)111d3fdbda6SRiccardo Mori isl::ast_expr IslNodeBuilder::getUpperBound(isl::ast_node_for For,
1120c55cb60STobias Grosser ICmpInst::Predicate &Predicate) {
113d3fdbda6SRiccardo Mori isl::ast_expr Cond = For.cond();
114d3fdbda6SRiccardo Mori isl::ast_expr Iterator = For.iterator();
115ade2242eSMichael Kruse assert(isl_ast_expr_get_type(Cond.get()) == isl_ast_expr_op &&
1160c55cb60STobias Grosser "conditional expression is not an atomic upper bound");
1170c55cb60STobias Grosser
118ade2242eSMichael Kruse isl_ast_op_type OpType = isl_ast_expr_get_op_type(Cond.get());
1190c55cb60STobias Grosser
120ade2242eSMichael Kruse switch (OpType) {
1210c55cb60STobias Grosser case isl_ast_op_le:
1220c55cb60STobias Grosser Predicate = ICmpInst::ICMP_SLE;
1230c55cb60STobias Grosser break;
1240c55cb60STobias Grosser case isl_ast_op_lt:
1250c55cb60STobias Grosser Predicate = ICmpInst::ICMP_SLT;
1260c55cb60STobias Grosser break;
1270c55cb60STobias Grosser default:
128a6d48f59SMichael Kruse llvm_unreachable("Unexpected comparison type in loop condition");
1290c55cb60STobias Grosser }
1300c55cb60STobias Grosser
131ade2242eSMichael Kruse isl::ast_expr Arg0 = Cond.get_op_arg(0);
1320c55cb60STobias Grosser
133ade2242eSMichael Kruse assert(isl_ast_expr_get_type(Arg0.get()) == isl_ast_expr_id &&
1340c55cb60STobias Grosser "conditional expression is not an atomic upper bound");
1350c55cb60STobias Grosser
136ade2242eSMichael Kruse isl::id UBID = Arg0.get_id();
1370c55cb60STobias Grosser
138ade2242eSMichael Kruse assert(isl_ast_expr_get_type(Iterator.get()) == isl_ast_expr_id &&
1390c55cb60STobias Grosser "Could not get the iterator");
1400c55cb60STobias Grosser
141ade2242eSMichael Kruse isl::id IteratorID = Iterator.get_id();
1420c55cb60STobias Grosser
143ade2242eSMichael Kruse assert(UBID.get() == IteratorID.get() &&
1440c55cb60STobias Grosser "conditional expression is not an atomic upper bound");
1450c55cb60STobias Grosser
146ade2242eSMichael Kruse return Cond.get_op_arg(1);
1470c55cb60STobias Grosser }
1480c55cb60STobias Grosser
getNumberOfIterations(isl::ast_node_for For)149d3fdbda6SRiccardo Mori int IslNodeBuilder::getNumberOfIterations(isl::ast_node_for For) {
150e873673bSMichael Kruse assert(isl_ast_node_get_type(For.get()) == isl_ast_node_for);
151d3fdbda6SRiccardo Mori isl::ast_node Body = For.body();
15239f9f30eSTobias Grosser
153c80d6979STobias Grosser // First, check if we can actually handle this code.
154e873673bSMichael Kruse switch (isl_ast_node_get_type(Body.get())) {
15539f9f30eSTobias Grosser case isl_ast_node_user:
15639f9f30eSTobias Grosser break;
15739f9f30eSTobias Grosser case isl_ast_node_block: {
158d3fdbda6SRiccardo Mori isl::ast_node_block BodyBlock = Body.as<isl::ast_node_block>();
159d3fdbda6SRiccardo Mori isl::ast_node_list List = BodyBlock.children();
160e873673bSMichael Kruse for (isl::ast_node Node : List) {
161e873673bSMichael Kruse isl_ast_node_type NodeType = isl_ast_node_get_type(Node.get());
162e873673bSMichael Kruse if (NodeType != isl_ast_node_user)
16339f9f30eSTobias Grosser return -1;
16439f9f30eSTobias Grosser }
16539f9f30eSTobias Grosser break;
16639f9f30eSTobias Grosser }
16739f9f30eSTobias Grosser default:
16839f9f30eSTobias Grosser return -1;
16939f9f30eSTobias Grosser }
17039f9f30eSTobias Grosser
171d3fdbda6SRiccardo Mori isl::ast_expr Init = For.init();
1725bf32a0eSMax Fan if (!Init.isa<isl::ast_expr_int>() || !Init.val().is_zero())
1730c55cb60STobias Grosser return -1;
174d3fdbda6SRiccardo Mori isl::ast_expr Inc = For.inc();
1755bf32a0eSMax Fan if (!Inc.isa<isl::ast_expr_int>() || !Inc.val().is_one())
176c49724f0SRoman Gareev return -1;
177c49724f0SRoman Gareev CmpInst::Predicate Predicate;
178e873673bSMichael Kruse isl::ast_expr UB = getUpperBound(For, Predicate);
1795bf32a0eSMax Fan if (!UB.isa<isl::ast_expr_int>())
180c49724f0SRoman Gareev return -1;
181e873673bSMichael Kruse isl::val UpVal = UB.get_val();
182e873673bSMichael Kruse int NumberIterations = UpVal.get_num_si();
183c49724f0SRoman Gareev if (NumberIterations < 0)
184c49724f0SRoman Gareev return -1;
185c49724f0SRoman Gareev if (Predicate == CmpInst::ICMP_SLT)
186c49724f0SRoman Gareev return NumberIterations;
187c49724f0SRoman Gareev else
1880c55cb60STobias Grosser return NumberIterations + 1;
1890c55cb60STobias Grosser }
1900c55cb60STobias Grosser
findReferencesByUse(Value * SrcVal,ScopStmt * UserStmt,Loop * UserScope,const ValueMapT & GlobalMap,SetVector<Value * > & Values,SetVector<const SCEV * > & SCEVs)191d5c87162SMichael Kruse static void findReferencesByUse(Value *SrcVal, ScopStmt *UserStmt,
192d5c87162SMichael Kruse Loop *UserScope, const ValueMapT &GlobalMap,
193d5c87162SMichael Kruse SetVector<Value *> &Values,
194d5c87162SMichael Kruse SetVector<const SCEV *> &SCEVs) {
195d5c87162SMichael Kruse VirtualUse VUse = VirtualUse::create(UserStmt, UserScope, SrcVal, true);
196d5c87162SMichael Kruse switch (VUse.getKind()) {
197d5c87162SMichael Kruse case VirtualUse::Constant:
198d5c87162SMichael Kruse // When accelerator-offloading, GlobalValue is a host address whose content
199d5c87162SMichael Kruse // must still be transferred to the GPU.
200d5c87162SMichael Kruse if (isa<GlobalValue>(SrcVal))
201d5c87162SMichael Kruse Values.insert(SrcVal);
202d5c87162SMichael Kruse break;
203e2a45f32STobias Grosser
204d5c87162SMichael Kruse case VirtualUse::Synthesizable:
205d5c87162SMichael Kruse SCEVs.insert(VUse.getScevExpr());
206d5c87162SMichael Kruse return;
207d5c87162SMichael Kruse
208d5c87162SMichael Kruse case VirtualUse::Block:
209d5c87162SMichael Kruse case VirtualUse::ReadOnly:
210d5c87162SMichael Kruse case VirtualUse::Hoisted:
211d5c87162SMichael Kruse case VirtualUse::Intra:
212d5c87162SMichael Kruse case VirtualUse::Inter:
213d5c87162SMichael Kruse break;
2140c55cb60STobias Grosser }
2150c55cb60STobias Grosser
216d5c87162SMichael Kruse if (Value *NewVal = GlobalMap.lookup(SrcVal))
217d5c87162SMichael Kruse Values.insert(NewVal);
218d5c87162SMichael Kruse }
219d5c87162SMichael Kruse
findReferencesInInst(Instruction * Inst,ScopStmt * UserStmt,Loop * UserScope,const ValueMapT & GlobalMap,SetVector<Value * > & Values,SetVector<const SCEV * > & SCEVs)220d5c87162SMichael Kruse static void findReferencesInInst(Instruction *Inst, ScopStmt *UserStmt,
221d5c87162SMichael Kruse Loop *UserScope, const ValueMapT &GlobalMap,
222d5c87162SMichael Kruse SetVector<Value *> &Values,
223d5c87162SMichael Kruse SetVector<const SCEV *> &SCEVs) {
224d5c87162SMichael Kruse for (Use &U : Inst->operands())
225d5c87162SMichael Kruse findReferencesByUse(U.get(), UserStmt, UserScope, GlobalMap, Values, SCEVs);
226d5c87162SMichael Kruse }
227d5c87162SMichael Kruse
findReferencesInStmt(ScopStmt * Stmt,SetVector<Value * > & Values,ValueMapT & GlobalMap,SetVector<const SCEV * > & SCEVs)228d5c87162SMichael Kruse static void findReferencesInStmt(ScopStmt *Stmt, SetVector<Value *> &Values,
229d5c87162SMichael Kruse ValueMapT &GlobalMap,
230d5c87162SMichael Kruse SetVector<const SCEV *> &SCEVs) {
231d5c87162SMichael Kruse LoopInfo *LI = Stmt->getParent()->getLI();
232d5c87162SMichael Kruse
233d5c87162SMichael Kruse BasicBlock *BB = Stmt->getBasicBlock();
234d5c87162SMichael Kruse Loop *Scope = LI->getLoopFor(BB);
235d5c87162SMichael Kruse for (Instruction *Inst : Stmt->getInstructions())
236d5c87162SMichael Kruse findReferencesInInst(Inst, Stmt, Scope, GlobalMap, Values, SCEVs);
237d5c87162SMichael Kruse
238d5c87162SMichael Kruse if (Stmt->isRegionStmt()) {
239d5c87162SMichael Kruse for (BasicBlock *BB : Stmt->getRegion()->blocks()) {
240d5c87162SMichael Kruse Loop *Scope = LI->getLoopFor(BB);
241d5c87162SMichael Kruse for (Instruction &Inst : *BB)
242d5c87162SMichael Kruse findReferencesInInst(&Inst, Stmt, Scope, GlobalMap, Values, SCEVs);
243d5c87162SMichael Kruse }
244d5c87162SMichael Kruse }
245d5c87162SMichael Kruse }
246d5c87162SMichael Kruse
addReferencesFromStmt(ScopStmt * Stmt,void * UserPtr,bool CreateScalarRefs)247d5c87162SMichael Kruse void polly::addReferencesFromStmt(ScopStmt *Stmt, void *UserPtr,
24800bb5a99STobias Grosser bool CreateScalarRefs) {
249bd93df93SMichael Kruse auto &References = *static_cast<SubtreeReferences *>(UserPtr);
2500c55cb60STobias Grosser
251d5c87162SMichael Kruse findReferencesInStmt(Stmt, References.Values, References.GlobalMap,
252d5c87162SMichael Kruse References.SCEVs);
2530c55cb60STobias Grosser
25464c0ff41STobias Grosser for (auto &Access : *Stmt) {
25543df2020STobias Grosser if (References.ParamSpace) {
25643df2020STobias Grosser isl::space ParamSpace = Access->getLatestAccessRelation().get_space();
25743df2020STobias Grosser (*References.ParamSpace) =
25843df2020STobias Grosser References.ParamSpace->align_params(ParamSpace);
25943df2020STobias Grosser }
26043df2020STobias Grosser
26140d08395SMichael Kruse if (Access->isLatestArrayKind()) {
26206618bf7SMichael Kruse auto *BasePtr = Access->getLatestScopArrayInfo()->getBasePtr();
26364c0ff41STobias Grosser if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr))
264952b5304SJohannes Doerfert if (Stmt->getParent()->contains(OpInst))
26564c0ff41STobias Grosser continue;
26664c0ff41STobias Grosser
267e3d8c05cSTobias Grosser References.Values.insert(BasePtr);
26864c0ff41STobias Grosser continue;
26964c0ff41STobias Grosser }
27064c0ff41STobias Grosser
27100bb5a99STobias Grosser if (CreateScalarRefs)
272e3d8c05cSTobias Grosser References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access));
27364c0ff41STobias Grosser }
274e3d8c05cSTobias Grosser }
275e3d8c05cSTobias Grosser
276e3d8c05cSTobias Grosser /// Extract the out-of-scop values and SCEVs referenced from a set describing
277e3d8c05cSTobias Grosser /// a ScopStmt.
278e3d8c05cSTobias Grosser ///
279e3d8c05cSTobias Grosser /// This includes the SCEVUnknowns referenced by the SCEVs used in the
280e3d8c05cSTobias Grosser /// statement and the base pointers of the memory accesses. For scalar
281e3d8c05cSTobias Grosser /// statements we force the generation of alloca memory locations and list
282e3d8c05cSTobias Grosser /// these locations in the set of out-of-scop values as well.
283e3d8c05cSTobias Grosser ///
284e3d8c05cSTobias Grosser /// @param Set A set which references the ScopStmt we are interested in.
285e3d8c05cSTobias Grosser /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
286e3d8c05cSTobias Grosser /// structure.
addReferencesFromStmtSet(isl::set Set,SubtreeReferences * UserPtr)287bd93df93SMichael Kruse static void addReferencesFromStmtSet(isl::set Set, SubtreeReferences *UserPtr) {
288670482dbSTobias Grosser isl::id Id = Set.get_tuple_id();
289d5c87162SMichael Kruse auto *Stmt = static_cast<ScopStmt *>(Id.get_user());
290d5c87162SMichael Kruse addReferencesFromStmt(Stmt, UserPtr);
291e3d8c05cSTobias Grosser }
292e3d8c05cSTobias Grosser
293e3d8c05cSTobias Grosser /// Extract the out-of-scop values and SCEVs referenced from a union set
294e3d8c05cSTobias Grosser /// referencing multiple ScopStmts.
295e3d8c05cSTobias Grosser ///
296e3d8c05cSTobias Grosser /// This includes the SCEVUnknowns referenced by the SCEVs used in the
297e3d8c05cSTobias Grosser /// statement and the base pointers of the memory accesses. For scalar
298e3d8c05cSTobias Grosser /// statements we force the generation of alloca memory locations and list
299e3d8c05cSTobias Grosser /// these locations in the set of out-of-scop values as well.
300e3d8c05cSTobias Grosser ///
301e3d8c05cSTobias Grosser /// @param USet A union set referencing the ScopStmts we are interested
302e3d8c05cSTobias Grosser /// in.
303e3d8c05cSTobias Grosser /// @param References The SubtreeReferences data structure through which
304e3d8c05cSTobias Grosser /// results are returned and further information is
305e3d8c05cSTobias Grosser /// provided.
addReferencesFromStmtUnionSet(isl::union_set USet,SubtreeReferences & References)306bd93df93SMichael Kruse static void addReferencesFromStmtUnionSet(isl::union_set USet,
307bd93df93SMichael Kruse SubtreeReferences &References) {
308670482dbSTobias Grosser
309670482dbSTobias Grosser for (isl::set Set : USet.get_set_list())
310670482dbSTobias Grosser addReferencesFromStmtSet(Set, &References);
3110c55cb60STobias Grosser }
3120c55cb60STobias Grosser
31382fbc5d4Spatacca isl::union_map
getScheduleForAstNode(const isl::ast_node & Node)31482fbc5d4Spatacca IslNodeBuilder::getScheduleForAstNode(const isl::ast_node &Node) {
31582fbc5d4Spatacca return IslAstInfo::getSchedule(Node);
316f1ac57c6STobias Grosser }
317f1ac57c6STobias Grosser
getReferencesInSubtree(const isl::ast_node & For,SetVector<Value * > & Values,SetVector<const Loop * > & Loops)31882fbc5d4Spatacca void IslNodeBuilder::getReferencesInSubtree(const isl::ast_node &For,
3190c55cb60STobias Grosser SetVector<Value *> &Values,
3200c55cb60STobias Grosser SetVector<const Loop *> &Loops) {
3210c55cb60STobias Grosser SetVector<const SCEV *> SCEVs;
322bd93df93SMichael Kruse SubtreeReferences References = {
32343df2020STobias Grosser LI, SE, S, ValueMap, Values, SCEVs, getBlockGenerator(), nullptr};
3240c55cb60STobias Grosser
3250c55cb60STobias Grosser for (const auto &I : IDToValue)
3260c55cb60STobias Grosser Values.insert(I.second);
3270c55cb60STobias Grosser
328e53c924bSSiddharth Bhat // NOTE: this is populated in IslNodeBuilder::addParameters
3290c55cb60STobias Grosser for (const auto &I : OutsideLoopIterations)
3300c55cb60STobias Grosser Values.insert(cast<SCEVUnknown>(I.second)->getValue());
3310c55cb60STobias Grosser
33282fbc5d4Spatacca isl::union_set Schedule = getScheduleForAstNode(For).domain();
333e3d8c05cSTobias Grosser addReferencesFromStmtUnionSet(Schedule, References);
3340c55cb60STobias Grosser
3350c55cb60STobias Grosser for (const SCEV *Expr : SCEVs) {
3367b811035SJohannes Doerfert findValues(Expr, SE, Values);
3370c55cb60STobias Grosser findLoops(Expr, Loops);
3380c55cb60STobias Grosser }
3390c55cb60STobias Grosser
3400c55cb60STobias Grosser Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
3410c55cb60STobias Grosser
3420caed1fbSSiddharth Bhat /// Note: Code generation of induction variables of loops outside Scops
3430caed1fbSSiddharth Bhat ///
3440c55cb60STobias Grosser /// Remove loops that contain the scop or that are part of the scop, as they
3450c55cb60STobias Grosser /// are considered local. This leaves only loops that are before the scop, but
3460c55cb60STobias Grosser /// do not contain the scop itself.
3470caed1fbSSiddharth Bhat /// We ignore loops perfectly contained in the Scop because these are already
3480caed1fbSSiddharth Bhat /// generated at `IslNodeBuilder::addParameters`. These `Loops` are loops
3490caed1fbSSiddharth Bhat /// whose induction variables are referred to by the Scop, but the Scop is not
3500caed1fbSSiddharth Bhat /// fully contained in these Loops. Since there can be many of these,
3510caed1fbSSiddharth Bhat /// we choose to codegen these on-demand.
3520caed1fbSSiddharth Bhat /// @see IslNodeBuilder::materializeNonScopLoopInductionVariable.
3530c55cb60STobias Grosser Loops.remove_if([this](const Loop *L) {
354ef74443cSJohannes Doerfert return S.contains(L) || L->contains(S.getEntry());
3550c55cb60STobias Grosser });
356a1b2086aSSiddharth Bhat
357a1b2086aSSiddharth Bhat // Contains Values that may need to be replaced with other values
358a1b2086aSSiddharth Bhat // due to replacements from the ValueMap. We should make sure
359a1b2086aSSiddharth Bhat // that we return correctly remapped values.
360a1b2086aSSiddharth Bhat // NOTE: this code path is tested by:
361a1b2086aSSiddharth Bhat // 1. test/Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
362a1b2086aSSiddharth Bhat // 2. test/Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
363a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues;
364a1b2086aSSiddharth Bhat for (Value *V : Values) {
365f2cfd2a4SSiddharth Bhat ReplacedValues.insert(getLatestValue(V));
366a1b2086aSSiddharth Bhat }
367a1b2086aSSiddharth Bhat Values = ReplacedValues;
3680c55cb60STobias Grosser }
3690c55cb60STobias Grosser
updateValues(ValueMapT & NewValues)370521dd584SJohannes Doerfert void IslNodeBuilder::updateValues(ValueMapT &NewValues) {
3710c55cb60STobias Grosser SmallPtrSet<Value *, 5> Inserted;
3720c55cb60STobias Grosser
3730c55cb60STobias Grosser for (const auto &I : IDToValue) {
3740c55cb60STobias Grosser IDToValue[I.first] = NewValues[I.second];
3750c55cb60STobias Grosser Inserted.insert(I.second);
3760c55cb60STobias Grosser }
3770c55cb60STobias Grosser
3780c55cb60STobias Grosser for (const auto &I : NewValues) {
3790c55cb60STobias Grosser if (Inserted.count(I.first))
3800c55cb60STobias Grosser continue;
3810c55cb60STobias Grosser
3820c55cb60STobias Grosser ValueMap[I.first] = I.second;
3830c55cb60STobias Grosser }
3840c55cb60STobias Grosser }
3850c55cb60STobias Grosser
getLatestValue(Value * Original) const386f2cfd2a4SSiddharth Bhat Value *IslNodeBuilder::getLatestValue(Value *Original) const {
387f2cfd2a4SSiddharth Bhat auto It = ValueMap.find(Original);
388f2cfd2a4SSiddharth Bhat if (It == ValueMap.end())
389f2cfd2a4SSiddharth Bhat return Original;
390f2cfd2a4SSiddharth Bhat return It->second;
391f2cfd2a4SSiddharth Bhat }
392f2cfd2a4SSiddharth Bhat
createUserVector(__isl_take isl_ast_node * User,std::vector<Value * > & IVS,__isl_take isl_id * IteratorID,__isl_take isl_union_map * Schedule)3930c55cb60STobias Grosser void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
3940c55cb60STobias Grosser std::vector<Value *> &IVS,
3950c55cb60STobias Grosser __isl_take isl_id *IteratorID,
3960c55cb60STobias Grosser __isl_take isl_union_map *Schedule) {
3970c55cb60STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
3980c55cb60STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
3990c55cb60STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr);
4000c55cb60STobias Grosser isl_ast_expr_free(StmtExpr);
4010c55cb60STobias Grosser ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
4020c55cb60STobias Grosser std::vector<LoopToScevMapT> VLTS(IVS.size());
4030c55cb60STobias Grosser
404dcf8d696STobias Grosser isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain().release());
4050c55cb60STobias Grosser Schedule = isl_union_map_intersect_domain(Schedule, Domain);
4060c55cb60STobias Grosser isl_map *S = isl_map_from_union_map(Schedule);
4070c55cb60STobias Grosser
408abcec37fSTobias Grosser auto *NewAccesses = createNewAccesses(Stmt, User);
409bc132607STobias Grosser createSubstitutionsVector(Expr, Stmt, VLTS, IVS, IteratorID);
410bc132607STobias Grosser VectorBlockGenerator::generate(BlockGen, *Stmt, VLTS, S, NewAccesses);
4112d1ed0bfSTobias Grosser isl_id_to_ast_expr_free(NewAccesses);
4120c55cb60STobias Grosser isl_map_free(S);
4130c55cb60STobias Grosser isl_id_free(Id);
4140c55cb60STobias Grosser isl_ast_node_free(User);
4150c55cb60STobias Grosser }
4160c55cb60STobias Grosser
createMark(__isl_take isl_ast_node * Node)4171ac884d7STobias Grosser void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) {
41811001e15SRoman Gareev auto *Id = isl_ast_node_mark_get_id(Node);
4191ac884d7STobias Grosser auto Child = isl_ast_node_mark_get_node(Node);
4201ac884d7STobias Grosser isl_ast_node_free(Node);
42111001e15SRoman Gareev // If a child node of a 'SIMD mark' is a loop that has a single iteration,
42211001e15SRoman Gareev // it will be optimized away and we should skip it.
4239248fde5SEugene Zelenko if (strcmp(isl_id_get_name(Id), "SIMD") == 0 &&
42411001e15SRoman Gareev isl_ast_node_get_type(Child) == isl_ast_node_for) {
42511001e15SRoman Gareev bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
426d3fdbda6SRiccardo Mori int VectorWidth =
427d3fdbda6SRiccardo Mori getNumberOfIterations(isl::manage_copy(Child).as<isl::ast_node_for>());
42811001e15SRoman Gareev if (Vector && 1 < VectorWidth && VectorWidth <= 16)
42911001e15SRoman Gareev createForVector(Child, VectorWidth);
43011001e15SRoman Gareev else
431d3fdbda6SRiccardo Mori createForSequential(isl::manage(Child).as<isl::ast_node_for>(), true);
43211001e15SRoman Gareev isl_id_free(Id);
43311001e15SRoman Gareev return;
43411001e15SRoman Gareev }
4353f170eb1SMichael Kruse
4363f170eb1SMichael Kruse BandAttr *ChildLoopAttr = getLoopAttr(isl::manage_copy(Id));
4375f58aae8SMichael Kruse BandAttr *AncestorLoopAttr;
4383f170eb1SMichael Kruse if (ChildLoopAttr) {
4395f58aae8SMichael Kruse // Save current LoopAttr environment to restore again when leaving this
4405f58aae8SMichael Kruse // subtree. This means there was no loop between the ancestor LoopAttr and
4415f58aae8SMichael Kruse // this mark, i.e. the ancestor LoopAttr did not directly mark a loop. This
4425f58aae8SMichael Kruse // can happen e.g. if the AST build peeled or unrolled the loop.
4435f58aae8SMichael Kruse AncestorLoopAttr = Annotator.getStagingAttrEnv();
4445f58aae8SMichael Kruse
4453f170eb1SMichael Kruse Annotator.getStagingAttrEnv() = ChildLoopAttr;
4463f170eb1SMichael Kruse }
4473f170eb1SMichael Kruse
44811001e15SRoman Gareev create(Child);
4493f170eb1SMichael Kruse
4503f170eb1SMichael Kruse if (ChildLoopAttr) {
4513f170eb1SMichael Kruse assert(Annotator.getStagingAttrEnv() == ChildLoopAttr &&
4523f170eb1SMichael Kruse "Nest must not overwrite loop attr environment");
4535f58aae8SMichael Kruse Annotator.getStagingAttrEnv() = AncestorLoopAttr;
4543f170eb1SMichael Kruse }
4553f170eb1SMichael Kruse
45611001e15SRoman Gareev isl_id_free(Id);
4571ac884d7STobias Grosser }
4581ac884d7STobias Grosser
createForVector(__isl_take isl_ast_node * For,int VectorWidth)4590c55cb60STobias Grosser void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
4600c55cb60STobias Grosser int VectorWidth) {
4610c55cb60STobias Grosser isl_ast_node *Body = isl_ast_node_for_get_body(For);
4620c55cb60STobias Grosser isl_ast_expr *Init = isl_ast_node_for_get_init(For);
4630c55cb60STobias Grosser isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
4640c55cb60STobias Grosser isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
4650c55cb60STobias Grosser isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
4660c55cb60STobias Grosser
4670c55cb60STobias Grosser Value *ValueLB = ExprBuilder.create(Init);
4680c55cb60STobias Grosser Value *ValueInc = ExprBuilder.create(Inc);
4690c55cb60STobias Grosser
4703717aa5dSTobias Grosser Type *MaxType = ExprBuilder.getType(Iterator);
4713717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
4723717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
4730767a511SJohannes Doerfert
4743717aa5dSTobias Grosser if (MaxType != ValueLB->getType())
4753717aa5dSTobias Grosser ValueLB = Builder.CreateSExt(ValueLB, MaxType);
4763717aa5dSTobias Grosser if (MaxType != ValueInc->getType())
4773717aa5dSTobias Grosser ValueInc = Builder.CreateSExt(ValueInc, MaxType);
4780c55cb60STobias Grosser
4790c55cb60STobias Grosser std::vector<Value *> IVS(VectorWidth);
4800c55cb60STobias Grosser IVS[0] = ValueLB;
4810c55cb60STobias Grosser
4820c55cb60STobias Grosser for (int i = 1; i < VectorWidth; i++)
4830c55cb60STobias Grosser IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
4840c55cb60STobias Grosser
48582fbc5d4Spatacca isl::union_map Schedule = getScheduleForAstNode(isl::manage_copy(For));
48682fbc5d4Spatacca assert(!Schedule.is_null() &&
48782fbc5d4Spatacca "For statement annotation does not contain its schedule");
4880c55cb60STobias Grosser
4890c55cb60STobias Grosser IDToValue[IteratorID] = ValueLB;
4900c55cb60STobias Grosser
4910c55cb60STobias Grosser switch (isl_ast_node_get_type(Body)) {
4920c55cb60STobias Grosser case isl_ast_node_user:
49382fbc5d4Spatacca createUserVector(Body, IVS, isl_id_copy(IteratorID), Schedule.copy());
4940c55cb60STobias Grosser break;
4950c55cb60STobias Grosser case isl_ast_node_block: {
4960c55cb60STobias Grosser isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
4970c55cb60STobias Grosser
4980c55cb60STobias Grosser for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
4990c55cb60STobias Grosser createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
50082fbc5d4Spatacca isl_id_copy(IteratorID), Schedule.copy());
5010c55cb60STobias Grosser
5020c55cb60STobias Grosser isl_ast_node_free(Body);
5030c55cb60STobias Grosser isl_ast_node_list_free(List);
5040c55cb60STobias Grosser break;
5050c55cb60STobias Grosser }
5060c55cb60STobias Grosser default:
5070c55cb60STobias Grosser isl_ast_node_dump(Body);
5080c55cb60STobias Grosser llvm_unreachable("Unhandled isl_ast_node in vectorizer");
5090c55cb60STobias Grosser }
5100c55cb60STobias Grosser
5110c55cb60STobias Grosser IDToValue.erase(IDToValue.find(IteratorID));
5120c55cb60STobias Grosser isl_id_free(IteratorID);
5130c55cb60STobias Grosser
5140c55cb60STobias Grosser isl_ast_node_free(For);
5150c55cb60STobias Grosser isl_ast_expr_free(Iterator);
51606ed5292SMichael Kruse
51706ed5292SMichael Kruse VectorLoops++;
5180c55cb60STobias Grosser }
5190c55cb60STobias Grosser
5200956a606SRoman Gareev /// Restore the initial ordering of dimensions of the band node
5210956a606SRoman Gareev ///
5220956a606SRoman Gareev /// In case the band node represents all the dimensions of the iteration
5230956a606SRoman Gareev /// domain, recreate the band node to restore the initial ordering of the
5240956a606SRoman Gareev /// dimensions.
5250956a606SRoman Gareev ///
5260956a606SRoman Gareev /// @param Node The band node to be modified.
5270956a606SRoman Gareev /// @return The modified schedule node.
IsLoopVectorizerDisabled(isl::ast_node_for Node)528d3fdbda6SRiccardo Mori static bool IsLoopVectorizerDisabled(isl::ast_node_for Node) {
529d3d3d6b7STobias Grosser assert(isl_ast_node_get_type(Node.get()) == isl_ast_node_for);
530d3fdbda6SRiccardo Mori isl::ast_node Body = Node.body();
531d3d3d6b7STobias Grosser if (isl_ast_node_get_type(Body.get()) != isl_ast_node_mark)
5320956a606SRoman Gareev return false;
533d3fdbda6SRiccardo Mori
534d3fdbda6SRiccardo Mori isl::ast_node_mark BodyMark = Body.as<isl::ast_node_mark>();
535d3fdbda6SRiccardo Mori auto Id = BodyMark.id();
5369248fde5SEugene Zelenko if (strcmp(Id.get_name().c_str(), "Loop Vectorizer Disabled") == 0)
5370956a606SRoman Gareev return true;
5380956a606SRoman Gareev return false;
5390956a606SRoman Gareev }
5400956a606SRoman Gareev
createForSequential(isl::ast_node_for For,bool MarkParallel)541d3fdbda6SRiccardo Mori void IslNodeBuilder::createForSequential(isl::ast_node_for For,
542d3fdbda6SRiccardo Mori bool MarkParallel) {
5430c55cb60STobias Grosser Value *ValueLB, *ValueUB, *ValueInc;
5443717aa5dSTobias Grosser Type *MaxType;
5450c55cb60STobias Grosser BasicBlock *ExitBlock;
5460c55cb60STobias Grosser Value *IV;
5470c55cb60STobias Grosser CmpInst::Predicate Predicate;
5480c55cb60STobias Grosser
549f16378b0SMichael Kruse bool LoopVectorizerDisabled = IsLoopVectorizerDisabled(For);
5500956a606SRoman Gareev
551d3fdbda6SRiccardo Mori isl::ast_node Body = For.body();
5520c55cb60STobias Grosser
5530c55cb60STobias Grosser // isl_ast_node_for_is_degenerate(For)
5540c55cb60STobias Grosser //
5550c55cb60STobias Grosser // TODO: For degenerated loops we could generate a plain assignment.
5560c55cb60STobias Grosser // However, for now we just reuse the logic for normal loops, which will
5570c55cb60STobias Grosser // create a loop with a single iteration.
5580c55cb60STobias Grosser
559d3fdbda6SRiccardo Mori isl::ast_expr Init = For.init();
560d3fdbda6SRiccardo Mori isl::ast_expr Inc = For.inc();
561d3fdbda6SRiccardo Mori isl::ast_expr Iterator = For.iterator();
562f16378b0SMichael Kruse isl::id IteratorID = Iterator.get_id();
563f16378b0SMichael Kruse isl::ast_expr UB = getUpperBound(For, Predicate);
5640c55cb60STobias Grosser
565f16378b0SMichael Kruse ValueLB = ExprBuilder.create(Init.release());
566f16378b0SMichael Kruse ValueUB = ExprBuilder.create(UB.release());
567f16378b0SMichael Kruse ValueInc = ExprBuilder.create(Inc.release());
5680c55cb60STobias Grosser
569f16378b0SMichael Kruse MaxType = ExprBuilder.getType(Iterator.get());
5703717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
5713717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
5723717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
5733717aa5dSTobias Grosser
5743717aa5dSTobias Grosser if (MaxType != ValueLB->getType())
5753717aa5dSTobias Grosser ValueLB = Builder.CreateSExt(ValueLB, MaxType);
5763717aa5dSTobias Grosser if (MaxType != ValueUB->getType())
5773717aa5dSTobias Grosser ValueUB = Builder.CreateSExt(ValueUB, MaxType);
5783717aa5dSTobias Grosser if (MaxType != ValueInc->getType())
5793717aa5dSTobias Grosser ValueInc = Builder.CreateSExt(ValueInc, MaxType);
5800c55cb60STobias Grosser
5810c55cb60STobias Grosser // If we can show that LB <Predicate> UB holds at least once, we can
5820c55cb60STobias Grosser // omit the GuardBB in front of the loop.
5830c55cb60STobias Grosser bool UseGuardBB =
5840c55cb60STobias Grosser !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
5852d950f36SPhilip Pfaffe IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, LI, DT, ExitBlock,
58653c80387SPhilip Pfaffe Predicate, &Annotator, MarkParallel, UseGuardBB,
5870956a606SRoman Gareev LoopVectorizerDisabled);
588f16378b0SMichael Kruse IDToValue[IteratorID.get()] = IV;
5890c55cb60STobias Grosser
590f16378b0SMichael Kruse create(Body.release());
5910c55cb60STobias Grosser
59253c80387SPhilip Pfaffe Annotator.popLoop(MarkParallel);
5930c55cb60STobias Grosser
594f16378b0SMichael Kruse IDToValue.erase(IDToValue.find(IteratorID.get()));
5950c55cb60STobias Grosser
596b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&ExitBlock->front());
5970c55cb60STobias Grosser
59806ed5292SMichael Kruse SequentialLoops++;
5990c55cb60STobias Grosser }
6000c55cb60STobias Grosser
601c80d6979STobias Grosser /// Remove the BBs contained in a (sub)function from the dominator tree.
6020c55cb60STobias Grosser ///
6030c55cb60STobias Grosser /// This function removes the basic blocks that are part of a subfunction from
6040c55cb60STobias Grosser /// the dominator tree. Specifically, when generating code it may happen that at
6050c55cb60STobias Grosser /// some point the code generation continues in a new sub-function (e.g., when
6060c55cb60STobias Grosser /// generating OpenMP code). The basic blocks that are created in this
6070c55cb60STobias Grosser /// sub-function are then still part of the dominator tree of the original
6080c55cb60STobias Grosser /// function, such that the dominator tree reaches over function boundaries.
6090c55cb60STobias Grosser /// This is not only incorrect, but also causes crashes. This function now
6100c55cb60STobias Grosser /// removes from the dominator tree all basic blocks that are dominated (and
6110c55cb60STobias Grosser /// consequently reachable) from the entry block of this (sub)function.
6120c55cb60STobias Grosser ///
6130c55cb60STobias Grosser /// FIXME: A LLVM (function or region) pass should not touch anything outside of
6140c55cb60STobias Grosser /// the function/region it runs on. Hence, the pure need for this function shows
6150c55cb60STobias Grosser /// that we do not comply to this rule. At the moment, this does not cause any
6160c55cb60STobias Grosser /// issues, but we should be aware that such issues may appear. Unfortunately
6170c55cb60STobias Grosser /// the current LLVM pass infrastructure does not allow to make Polly a module
6180c55cb60STobias Grosser /// or call-graph pass to solve this issue, as such a pass would not have access
6190c55cb60STobias Grosser /// to the per-function analyses passes needed by Polly. A future pass manager
6200c55cb60STobias Grosser /// infrastructure is supposed to enable such kind of access possibly allowing
6210c55cb60STobias Grosser /// us to create a cleaner solution here.
6220c55cb60STobias Grosser ///
6230c55cb60STobias Grosser /// FIXME: Instead of adding the dominance information and then dropping it
6240c55cb60STobias Grosser /// later on, we should try to just not add it in the first place. This requires
6250c55cb60STobias Grosser /// some careful testing to make sure this does not break in interaction with
6260c55cb60STobias Grosser /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
6270c55cb60STobias Grosser /// which may try to update it.
6280c55cb60STobias Grosser ///
6290c55cb60STobias Grosser /// @param F The function which contains the BBs to removed.
6300c55cb60STobias Grosser /// @param DT The dominator tree from which to remove the BBs.
removeSubFuncFromDomTree(Function * F,DominatorTree & DT)6310c55cb60STobias Grosser static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
6320c55cb60STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock());
6330c55cb60STobias Grosser std::vector<BasicBlock *> Nodes;
6340c55cb60STobias Grosser
6350c55cb60STobias Grosser // We can only remove an element from the dominator tree, if all its children
6360c55cb60STobias Grosser // have been removed. To ensure this we obtain the list of nodes to remove
6370c55cb60STobias Grosser // using a post-order tree traversal.
6380c55cb60STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
6390c55cb60STobias Grosser Nodes.push_back(I->getBlock());
6400c55cb60STobias Grosser
6410c55cb60STobias Grosser for (BasicBlock *BB : Nodes)
6420c55cb60STobias Grosser DT.eraseNode(BB);
6430c55cb60STobias Grosser }
6440c55cb60STobias Grosser
createForParallel(__isl_take isl_ast_node * For)6450c55cb60STobias Grosser void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
6460c55cb60STobias Grosser isl_ast_node *Body;
6470c55cb60STobias Grosser isl_ast_expr *Init, *Inc, *Iterator, *UB;
6480c55cb60STobias Grosser isl_id *IteratorID;
6490c55cb60STobias Grosser Value *ValueLB, *ValueUB, *ValueInc;
6503717aa5dSTobias Grosser Type *MaxType;
6510c55cb60STobias Grosser Value *IV;
6520c55cb60STobias Grosser CmpInst::Predicate Predicate;
6530c55cb60STobias Grosser
654fb19dd69SJohannes Doerfert // The preamble of parallel code interacts different than normal code with
655fb19dd69SJohannes Doerfert // e.g., scalar initialization. Therefore, we ensure the parallel code is
656fb19dd69SJohannes Doerfert // separated from the last basic block.
657b8f58b53SDuncan P. N. Exon Smith BasicBlock *ParBB = SplitBlock(Builder.GetInsertBlock(),
658b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI);
659fb19dd69SJohannes Doerfert ParBB->setName("polly.parallel.for");
660b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&ParBB->front());
661fb19dd69SJohannes Doerfert
6620c55cb60STobias Grosser Body = isl_ast_node_for_get_body(For);
6630c55cb60STobias Grosser Init = isl_ast_node_for_get_init(For);
6640c55cb60STobias Grosser Inc = isl_ast_node_for_get_inc(For);
6650c55cb60STobias Grosser Iterator = isl_ast_node_for_get_iterator(For);
6660c55cb60STobias Grosser IteratorID = isl_ast_expr_get_id(Iterator);
667d3fdbda6SRiccardo Mori UB = getUpperBound(isl::manage_copy(For).as<isl::ast_node_for>(), Predicate)
668d3fdbda6SRiccardo Mori .release();
6690c55cb60STobias Grosser
6700c55cb60STobias Grosser ValueLB = ExprBuilder.create(Init);
6710c55cb60STobias Grosser ValueUB = ExprBuilder.create(UB);
6720c55cb60STobias Grosser ValueInc = ExprBuilder.create(Inc);
6730c55cb60STobias Grosser
6740c55cb60STobias Grosser // OpenMP always uses SLE. In case the isl generated AST uses a SLT
675a6d48f59SMichael Kruse // expression, we need to adjust the loop bound by one.
6760c55cb60STobias Grosser if (Predicate == CmpInst::ICMP_SLT)
6770c55cb60STobias Grosser ValueUB = Builder.CreateAdd(
6780c55cb60STobias Grosser ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
6790c55cb60STobias Grosser
6803717aa5dSTobias Grosser MaxType = ExprBuilder.getType(Iterator);
6813717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
6823717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
6833717aa5dSTobias Grosser MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
6843717aa5dSTobias Grosser
6853717aa5dSTobias Grosser if (MaxType != ValueLB->getType())
6863717aa5dSTobias Grosser ValueLB = Builder.CreateSExt(ValueLB, MaxType);
6873717aa5dSTobias Grosser if (MaxType != ValueUB->getType())
6883717aa5dSTobias Grosser ValueUB = Builder.CreateSExt(ValueUB, MaxType);
6893717aa5dSTobias Grosser if (MaxType != ValueInc->getType())
6903717aa5dSTobias Grosser ValueInc = Builder.CreateSExt(ValueInc, MaxType);
6910c55cb60STobias Grosser
6920c55cb60STobias Grosser BasicBlock::iterator LoopBody;
6930c55cb60STobias Grosser
6940c55cb60STobias Grosser SetVector<Value *> SubtreeValues;
6950c55cb60STobias Grosser SetVector<const Loop *> Loops;
6960c55cb60STobias Grosser
69782fbc5d4Spatacca getReferencesInSubtree(isl::manage_copy(For), SubtreeValues, Loops);
6980c55cb60STobias Grosser
6990c55cb60STobias Grosser // Create for all loops we depend on values that contain the current loop
7000c55cb60STobias Grosser // iteration. These values are necessary to generate code for SCEVs that
7010c55cb60STobias Grosser // depend on such loops. As a result we need to pass them to the subfunction.
7020caed1fbSSiddharth Bhat // See [Code generation of induction variables of loops outside Scops]
7030c55cb60STobias Grosser for (const Loop *L : Loops) {
7040caed1fbSSiddharth Bhat Value *LoopInductionVar = materializeNonScopLoopInductionVariable(L);
7050caed1fbSSiddharth Bhat SubtreeValues.insert(LoopInductionVar);
7060c55cb60STobias Grosser }
7070c55cb60STobias Grosser
708521dd584SJohannes Doerfert ValueMapT NewValues;
7090c55cb60STobias Grosser
71089251edeSMichael Kruse std::unique_ptr<ParallelLoopGenerator> ParallelLoopGenPtr;
71189251edeSMichael Kruse
71289251edeSMichael Kruse switch (PollyOmpBackend) {
71389251edeSMichael Kruse case OpenMPBackend::GNU:
71489251edeSMichael Kruse ParallelLoopGenPtr.reset(
71589251edeSMichael Kruse new ParallelLoopGeneratorGOMP(Builder, LI, DT, DL));
71689251edeSMichael Kruse break;
71789251edeSMichael Kruse case OpenMPBackend::LLVM:
71889251edeSMichael Kruse ParallelLoopGenPtr.reset(new ParallelLoopGeneratorKMP(Builder, LI, DT, DL));
71989251edeSMichael Kruse break;
72089251edeSMichael Kruse }
72189251edeSMichael Kruse
72289251edeSMichael Kruse IV = ParallelLoopGenPtr->createParallelLoop(
72389251edeSMichael Kruse ValueLB, ValueUB, ValueInc, SubtreeValues, NewValues, &LoopBody);
7240c55cb60STobias Grosser BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
725b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&*LoopBody);
7260c55cb60STobias Grosser
727a9dc5294SJohannes Doerfert // Remember the parallel subfunction
728a9dc5294SJohannes Doerfert ParallelSubfunctions.push_back(LoopBody->getFunction());
729a9dc5294SJohannes Doerfert
7300c55cb60STobias Grosser // Save the current values.
731f4bb7a6aSTobias Grosser auto ValueMapCopy = ValueMap;
7320c55cb60STobias Grosser IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
7330c55cb60STobias Grosser
7340c55cb60STobias Grosser updateValues(NewValues);
7350c55cb60STobias Grosser IDToValue[IteratorID] = IV;
7360c55cb60STobias Grosser
737521dd584SJohannes Doerfert ValueMapT NewValuesReverse;
738b0da42fbSTobias Grosser
739b0da42fbSTobias Grosser for (auto P : NewValues)
740b0da42fbSTobias Grosser NewValuesReverse[P.second] = P.first;
741b0da42fbSTobias Grosser
742b0da42fbSTobias Grosser Annotator.addAlternativeAliasBases(NewValuesReverse);
743b0da42fbSTobias Grosser
7440c55cb60STobias Grosser create(Body);
7450c55cb60STobias Grosser
746b0da42fbSTobias Grosser Annotator.resetAlternativeAliasBases();
7470c55cb60STobias Grosser // Restore the original values.
7480c55cb60STobias Grosser ValueMap = ValueMapCopy;
7490c55cb60STobias Grosser IDToValue = IDToValueCopy;
7500c55cb60STobias Grosser
751b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&*AfterLoop);
7520c55cb60STobias Grosser removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
7530c55cb60STobias Grosser
7540c55cb60STobias Grosser for (const Loop *L : Loops)
7550c55cb60STobias Grosser OutsideLoopIterations.erase(L);
7560c55cb60STobias Grosser
7570c55cb60STobias Grosser isl_ast_node_free(For);
7580c55cb60STobias Grosser isl_ast_expr_free(Iterator);
7590c55cb60STobias Grosser isl_id_free(IteratorID);
76006ed5292SMichael Kruse
76106ed5292SMichael Kruse ParallelLoops++;
7620c55cb60STobias Grosser }
7630c55cb60STobias Grosser
764706f79abSMichael Kruse /// Return whether any of @p Node's statements contain partial accesses.
765706f79abSMichael Kruse ///
766706f79abSMichael Kruse /// Partial accesses are not supported by Polly's vector code generator.
hasPartialAccesses(__isl_take isl_ast_node * Node)767706f79abSMichael Kruse static bool hasPartialAccesses(__isl_take isl_ast_node *Node) {
768706f79abSMichael Kruse return isl_ast_node_foreach_descendant_top_down(
769706f79abSMichael Kruse Node,
770706f79abSMichael Kruse [](isl_ast_node *Node, void *User) -> isl_bool {
771706f79abSMichael Kruse if (isl_ast_node_get_type(Node) != isl_ast_node_user)
772706f79abSMichael Kruse return isl_bool_true;
773706f79abSMichael Kruse
774d3d3d6b7STobias Grosser isl::ast_expr Expr =
775d3d3d6b7STobias Grosser isl::manage(isl_ast_node_user_get_expr(Node));
776d3d3d6b7STobias Grosser isl::ast_expr StmtExpr = Expr.get_op_arg(0);
777d3d3d6b7STobias Grosser isl::id Id = StmtExpr.get_id();
778706f79abSMichael Kruse
779706f79abSMichael Kruse ScopStmt *Stmt =
780d3d3d6b7STobias Grosser static_cast<ScopStmt *>(isl_id_get_user(Id.get()));
781dcf8d696STobias Grosser isl::set StmtDom = Stmt->getDomain();
782706f79abSMichael Kruse for (auto *MA : *Stmt) {
783706f79abSMichael Kruse if (MA->isLatestPartialAccess())
784706f79abSMichael Kruse return isl_bool_error;
785706f79abSMichael Kruse }
786706f79abSMichael Kruse return isl_bool_true;
787706f79abSMichael Kruse },
788706f79abSMichael Kruse nullptr) == isl_stat_error;
789706f79abSMichael Kruse }
790706f79abSMichael Kruse
createFor(__isl_take isl_ast_node * For)7910c55cb60STobias Grosser void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
7920c55cb60STobias Grosser bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
7930c55cb60STobias Grosser
7941ab2753dSKevin Zhou if (Vector && IslAstInfo::isInnermostParallel(isl::manage_copy(For)) &&
79582fbc5d4Spatacca !IslAstInfo::isReductionParallel(isl::manage_copy(For))) {
796d3fdbda6SRiccardo Mori int VectorWidth =
797d3fdbda6SRiccardo Mori getNumberOfIterations(isl::manage_copy(For).as<isl::ast_node_for>());
798706f79abSMichael Kruse if (1 < VectorWidth && VectorWidth <= 16 && !hasPartialAccesses(For)) {
7990c55cb60STobias Grosser createForVector(For, VectorWidth);
8000c55cb60STobias Grosser return;
8010c55cb60STobias Grosser }
8020c55cb60STobias Grosser }
8030c55cb60STobias Grosser
80482fbc5d4Spatacca if (IslAstInfo::isExecutedInParallel(isl::manage_copy(For))) {
8050c55cb60STobias Grosser createForParallel(For);
8060c55cb60STobias Grosser return;
8070c55cb60STobias Grosser }
80882fbc5d4Spatacca bool Parallel = (IslAstInfo::isParallel(isl::manage_copy(For)) &&
80982fbc5d4Spatacca !IslAstInfo::isReductionParallel(isl::manage_copy(For)));
810d3fdbda6SRiccardo Mori createForSequential(isl::manage(For).as<isl::ast_node_for>(), Parallel);
8110c55cb60STobias Grosser }
8120c55cb60STobias Grosser
createIf(__isl_take isl_ast_node * If)8130c55cb60STobias Grosser void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
8140c55cb60STobias Grosser isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
8150c55cb60STobias Grosser
8160c55cb60STobias Grosser Function *F = Builder.GetInsertBlock()->getParent();
8170c55cb60STobias Grosser LLVMContext &Context = F->getContext();
8180c55cb60STobias Grosser
819b8f58b53SDuncan P. N. Exon Smith BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
820b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI);
8210c55cb60STobias Grosser CondBB->setName("polly.cond");
822b8f58b53SDuncan P. N. Exon Smith BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
8230c55cb60STobias Grosser MergeBB->setName("polly.merge");
8240c55cb60STobias Grosser BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
8250c55cb60STobias Grosser BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
8260c55cb60STobias Grosser
8270c55cb60STobias Grosser DT.addNewBlock(ThenBB, CondBB);
8280c55cb60STobias Grosser DT.addNewBlock(ElseBB, CondBB);
8290c55cb60STobias Grosser DT.changeImmediateDominator(MergeBB, CondBB);
8300c55cb60STobias Grosser
8310c55cb60STobias Grosser Loop *L = LI.getLoopFor(CondBB);
8320c55cb60STobias Grosser if (L) {
8330c55cb60STobias Grosser L->addBasicBlockToLoop(ThenBB, LI);
8340c55cb60STobias Grosser L->addBasicBlockToLoop(ElseBB, LI);
8350c55cb60STobias Grosser }
8360c55cb60STobias Grosser
8370c55cb60STobias Grosser CondBB->getTerminator()->eraseFromParent();
8380c55cb60STobias Grosser
8390c55cb60STobias Grosser Builder.SetInsertPoint(CondBB);
8400c55cb60STobias Grosser Value *Predicate = ExprBuilder.create(Cond);
8410c55cb60STobias Grosser Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
8420c55cb60STobias Grosser Builder.SetInsertPoint(ThenBB);
8430c55cb60STobias Grosser Builder.CreateBr(MergeBB);
8440c55cb60STobias Grosser Builder.SetInsertPoint(ElseBB);
8450c55cb60STobias Grosser Builder.CreateBr(MergeBB);
846b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&ThenBB->front());
8470c55cb60STobias Grosser
8480c55cb60STobias Grosser create(isl_ast_node_if_get_then(If));
8490c55cb60STobias Grosser
850b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&ElseBB->front());
8510c55cb60STobias Grosser
8520c55cb60STobias Grosser if (isl_ast_node_if_has_else(If))
8530c55cb60STobias Grosser create(isl_ast_node_if_get_else(If));
8540c55cb60STobias Grosser
855b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&MergeBB->front());
8560c55cb60STobias Grosser
8570c55cb60STobias Grosser isl_ast_node_free(If);
85806ed5292SMichael Kruse
85906ed5292SMichael Kruse IfConditions++;
8600c55cb60STobias Grosser }
8610c55cb60STobias Grosser
8622d1ed0bfSTobias Grosser __isl_give isl_id_to_ast_expr *
createNewAccesses(ScopStmt * Stmt,__isl_keep isl_ast_node * Node)8632d1ed0bfSTobias Grosser IslNodeBuilder::createNewAccesses(ScopStmt *Stmt,
864abcec37fSTobias Grosser __isl_keep isl_ast_node *Node) {
8652a629efcSpatacca isl::id_to_ast_expr NewAccesses =
8662a629efcSpatacca isl::id_to_ast_expr::alloc(Stmt->getParent()->getIslCtx(), 0);
8676a7c3e4bSJohannes Doerfert
8682a629efcSpatacca isl::ast_build Build = IslAstInfo::getBuild(isl::manage_copy(Node));
8692a629efcSpatacca assert(!Build.is_null() && "Could not obtain isl_ast_build from user node");
8702a629efcSpatacca Stmt->setAstBuild(Build);
8716a7c3e4bSJohannes Doerfert
8722d1ed0bfSTobias Grosser for (auto *MA : *Stmt) {
873b3c3d149STobias Grosser if (!MA->hasNewAccessRelation()) {
874b3c3d149STobias Grosser if (PollyGenerateExpressions) {
875b3c3d149STobias Grosser if (!MA->isAffine())
876b3c3d149STobias Grosser continue;
877b3c3d149STobias Grosser if (MA->getLatestScopArrayInfo()->getBasePtrOriginSAI())
8782d1ed0bfSTobias Grosser continue;
8792d1ed0bfSTobias Grosser
880b3c3d149STobias Grosser auto *BasePtr =
881b3c3d149STobias Grosser dyn_cast<Instruction>(MA->getLatestScopArrayInfo()->getBasePtr());
882b3c3d149STobias Grosser if (BasePtr && Stmt->getParent()->getRegion().contains(BasePtr))
883b3c3d149STobias Grosser continue;
884b3c3d149STobias Grosser } else {
885b3c3d149STobias Grosser continue;
886b3c3d149STobias Grosser }
887b3c3d149STobias Grosser }
888b3c3d149STobias Grosser assert(MA->isAffine() &&
889b3c3d149STobias Grosser "Only affine memory accesses can be code generated");
8904b0c5aeaSMichael Kruse
8912a629efcSpatacca isl::union_map Schedule = Build.get_schedule();
89216480186STobias Grosser
89316480186STobias Grosser #ifndef NDEBUG
894706f79abSMichael Kruse if (MA->isRead()) {
895dcf8d696STobias Grosser auto Dom = Stmt->getDomain().release();
8962a629efcSpatacca auto SchedDom = isl_set_from_union_set(Schedule.domain().release());
8971515f6b9STobias Grosser auto AccDom = isl_map_domain(MA->getAccessRelation().release());
898b65ccc43STobias Grosser Dom = isl_set_intersect_params(Dom,
899b65ccc43STobias Grosser Stmt->getParent()->getContext().release());
900b65ccc43STobias Grosser SchedDom = isl_set_intersect_params(
901b65ccc43STobias Grosser SchedDom, Stmt->getParent()->getContext().release());
90216480186STobias Grosser assert(isl_set_is_subset(SchedDom, AccDom) &&
90316480186STobias Grosser "Access relation not defined on full schedule domain");
90416480186STobias Grosser assert(isl_set_is_subset(Dom, AccDom) &&
90516480186STobias Grosser "Access relation not defined on full domain");
90616480186STobias Grosser isl_set_free(AccDom);
90716480186STobias Grosser isl_set_free(SchedDom);
90816480186STobias Grosser isl_set_free(Dom);
909706f79abSMichael Kruse }
91016480186STobias Grosser #endif
91116480186STobias Grosser
9122a629efcSpatacca isl::pw_multi_aff PWAccRel = MA->applyScheduleToAccessRelation(Schedule);
9132d1ed0bfSTobias Grosser
914706f79abSMichael Kruse // isl cannot generate an index expression for access-nothing accesses.
9152a629efcSpatacca isl::set AccDomain = PWAccRel.domain();
916163cacb4SMichael Kruse isl::set Context = S.getContext();
917163cacb4SMichael Kruse AccDomain = AccDomain.intersect_params(Context);
9182a629efcSpatacca if (AccDomain.is_empty())
919706f79abSMichael Kruse continue;
9202a629efcSpatacca
9212a629efcSpatacca isl::ast_expr AccessExpr = Build.access_from(PWAccRel);
9222a629efcSpatacca NewAccesses = NewAccesses.set(MA->getId(), AccessExpr);
923706f79abSMichael Kruse }
924706f79abSMichael Kruse
9252a629efcSpatacca return NewAccesses.release();
9262d1ed0bfSTobias Grosser }
9272d1ed0bfSTobias Grosser
createSubstitutions(__isl_take isl_ast_expr * Expr,ScopStmt * Stmt,LoopToScevMapT & LTS)928a3afe44dSTobias Grosser void IslNodeBuilder::createSubstitutions(__isl_take isl_ast_expr *Expr,
929a3afe44dSTobias Grosser ScopStmt *Stmt, LoopToScevMapT <S) {
9300c55cb60STobias Grosser assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
9310c55cb60STobias Grosser "Expression of type 'op' expected");
9320c55cb60STobias Grosser assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
933a6d48f59SMichael Kruse "Operation of type 'call' expected");
9340c55cb60STobias Grosser for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
9350c55cb60STobias Grosser isl_ast_expr *SubExpr;
9360c55cb60STobias Grosser Value *V;
9370c55cb60STobias Grosser
9380c55cb60STobias Grosser SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
9390c55cb60STobias Grosser V = ExprBuilder.create(SubExpr);
9400c55cb60STobias Grosser ScalarEvolution *SE = Stmt->getParent()->getSE();
9410c55cb60STobias Grosser LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
9420c55cb60STobias Grosser }
9430c55cb60STobias Grosser
9440c55cb60STobias Grosser isl_ast_expr_free(Expr);
9450c55cb60STobias Grosser }
9460c55cb60STobias Grosser
createSubstitutionsVector(__isl_take isl_ast_expr * Expr,ScopStmt * Stmt,std::vector<LoopToScevMapT> & VLTS,std::vector<Value * > & IVS,__isl_take isl_id * IteratorID)9470c55cb60STobias Grosser void IslNodeBuilder::createSubstitutionsVector(
948bc132607STobias Grosser __isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
9490c55cb60STobias Grosser std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
9500c55cb60STobias Grosser __isl_take isl_id *IteratorID) {
9510c55cb60STobias Grosser int i = 0;
9520c55cb60STobias Grosser
9530c55cb60STobias Grosser Value *OldValue = IDToValue[IteratorID];
9540c55cb60STobias Grosser for (Value *IV : IVS) {
9550c55cb60STobias Grosser IDToValue[IteratorID] = IV;
956bc132607STobias Grosser createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]);
9570c55cb60STobias Grosser i++;
9580c55cb60STobias Grosser }
9590c55cb60STobias Grosser
9600c55cb60STobias Grosser IDToValue[IteratorID] = OldValue;
9610c55cb60STobias Grosser isl_id_free(IteratorID);
9620c55cb60STobias Grosser isl_ast_expr_free(Expr);
9630c55cb60STobias Grosser }
9640c55cb60STobias Grosser
generateCopyStmt(ScopStmt * Stmt,__isl_keep isl_id_to_ast_expr * NewAccesses)965b3224adfSRoman Gareev void IslNodeBuilder::generateCopyStmt(
966b3224adfSRoman Gareev ScopStmt *Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
967b3224adfSRoman Gareev assert(Stmt->size() == 2);
968b3224adfSRoman Gareev auto ReadAccess = Stmt->begin();
969b3224adfSRoman Gareev auto WriteAccess = ReadAccess++;
970b3224adfSRoman Gareev assert((*ReadAccess)->isRead() && (*WriteAccess)->isMustWrite());
971b3224adfSRoman Gareev assert((*ReadAccess)->getElementType() == (*WriteAccess)->getElementType() &&
972b3224adfSRoman Gareev "Accesses use the same data type");
973b3224adfSRoman Gareev assert((*ReadAccess)->isArrayKind() && (*WriteAccess)->isArrayKind());
974b3224adfSRoman Gareev auto *AccessExpr =
975fe46c3ffSTobias Grosser isl_id_to_ast_expr_get(NewAccesses, (*ReadAccess)->getId().release());
976b3224adfSRoman Gareev auto *LoadValue = ExprBuilder.create(AccessExpr);
977fe46c3ffSTobias Grosser AccessExpr =
978fe46c3ffSTobias Grosser isl_id_to_ast_expr_get(NewAccesses, (*WriteAccess)->getId().release());
979ff9b37e9SNikita Popov auto *StoreAddr = ExprBuilder.createAccessAddress(AccessExpr).first;
980b3224adfSRoman Gareev Builder.CreateStore(LoadValue, StoreAddr);
981b3224adfSRoman Gareev }
982b3224adfSRoman Gareev
materializeNonScopLoopInductionVariable(const Loop * L)9830caed1fbSSiddharth Bhat Value *IslNodeBuilder::materializeNonScopLoopInductionVariable(const Loop *L) {
9840caed1fbSSiddharth Bhat assert(OutsideLoopIterations.find(L) == OutsideLoopIterations.end() &&
9850caed1fbSSiddharth Bhat "trying to materialize loop induction variable twice");
9860caed1fbSSiddharth Bhat const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
9870caed1fbSSiddharth Bhat SE.getUnknown(Builder.getInt64(1)), L,
9880caed1fbSSiddharth Bhat SCEV::FlagAnyWrap);
9890caed1fbSSiddharth Bhat Value *V = generateSCEV(OuterLIV);
9900caed1fbSSiddharth Bhat OutsideLoopIterations[L] = SE.getUnknown(V);
9910caed1fbSSiddharth Bhat return V;
9920caed1fbSSiddharth Bhat }
9930caed1fbSSiddharth Bhat
createUser(__isl_take isl_ast_node * User)9940c55cb60STobias Grosser void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
9950c55cb60STobias Grosser LoopToScevMapT LTS;
9960c55cb60STobias Grosser isl_id *Id;
9970c55cb60STobias Grosser ScopStmt *Stmt;
9980c55cb60STobias Grosser
9990c55cb60STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
10000c55cb60STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
10010c55cb60STobias Grosser Id = isl_ast_expr_get_id(StmtExpr);
10020c55cb60STobias Grosser isl_ast_expr_free(StmtExpr);
10030c55cb60STobias Grosser
10040c55cb60STobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
10050c55cb60STobias Grosser
10060c55cb60STobias Grosser Stmt = (ScopStmt *)isl_id_get_user(Id);
1007abcec37fSTobias Grosser auto *NewAccesses = createNewAccesses(Stmt, User);
1008b3224adfSRoman Gareev if (Stmt->isCopyStmt()) {
1009b3224adfSRoman Gareev generateCopyStmt(Stmt, NewAccesses);
1010b3224adfSRoman Gareev isl_ast_expr_free(Expr);
1011b3224adfSRoman Gareev } else {
1012bc132607STobias Grosser createSubstitutions(Expr, Stmt, LTS);
10130c55cb60STobias Grosser
10142d1ed0bfSTobias Grosser if (Stmt->isBlockStmt())
1015bc132607STobias Grosser BlockGen.copyStmt(*Stmt, LTS, NewAccesses);
10162d1ed0bfSTobias Grosser else
1017bc132607STobias Grosser RegionGen.copyStmt(*Stmt, LTS, NewAccesses);
1018b3224adfSRoman Gareev }
10192d1ed0bfSTobias Grosser
10202d1ed0bfSTobias Grosser isl_id_to_ast_expr_free(NewAccesses);
10210c55cb60STobias Grosser isl_ast_node_free(User);
10220c55cb60STobias Grosser isl_id_free(Id);
10230c55cb60STobias Grosser }
10240c55cb60STobias Grosser
createBlock(__isl_take isl_ast_node * Block)10250c55cb60STobias Grosser void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
10260c55cb60STobias Grosser isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
10270c55cb60STobias Grosser
10280c55cb60STobias Grosser for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
10290c55cb60STobias Grosser create(isl_ast_node_list_get_ast_node(List, i));
10300c55cb60STobias Grosser
10310c55cb60STobias Grosser isl_ast_node_free(Block);
10320c55cb60STobias Grosser isl_ast_node_list_free(List);
10330c55cb60STobias Grosser }
10340c55cb60STobias Grosser
create(__isl_take isl_ast_node * Node)10350c55cb60STobias Grosser void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
10360c55cb60STobias Grosser switch (isl_ast_node_get_type(Node)) {
10370c55cb60STobias Grosser case isl_ast_node_error:
10380c55cb60STobias Grosser llvm_unreachable("code generation error");
10390c55cb60STobias Grosser case isl_ast_node_mark:
10401ac884d7STobias Grosser createMark(Node);
10411ac884d7STobias Grosser return;
10420c55cb60STobias Grosser case isl_ast_node_for:
10430c55cb60STobias Grosser createFor(Node);
10440c55cb60STobias Grosser return;
10450c55cb60STobias Grosser case isl_ast_node_if:
10460c55cb60STobias Grosser createIf(Node);
10470c55cb60STobias Grosser return;
10480c55cb60STobias Grosser case isl_ast_node_user:
10490c55cb60STobias Grosser createUser(Node);
10500c55cb60STobias Grosser return;
10510c55cb60STobias Grosser case isl_ast_node_block:
10520c55cb60STobias Grosser createBlock(Node);
10530c55cb60STobias Grosser return;
10540c55cb60STobias Grosser }
10550c55cb60STobias Grosser
10560c55cb60STobias Grosser llvm_unreachable("Unknown isl_ast_node type");
10570c55cb60STobias Grosser }
10580c55cb60STobias Grosser
materializeValue(__isl_take isl_id * Id)1059ad84c6f6SMichael Kruse bool IslNodeBuilder::materializeValue(__isl_take isl_id *Id) {
1060ebfd7249SJohannes Doerfert // If the Id is already mapped, skip it.
10611d45c6daSTobias Grosser if (!IDToValue.count(Id)) {
1062af3e301aSJohannes Doerfert auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id);
1063fc4bfc46SJohannes Doerfert Value *V = nullptr;
1064af3e301aSJohannes Doerfert
1065a6d48f59SMichael Kruse // Parameters could refer to invariant loads that need to be
1066af3e301aSJohannes Doerfert // preloaded before we can generate code for the parameter. Thus,
1067a6d48f59SMichael Kruse // check if any value referred to in ParamSCEV is an invariant load
1068af3e301aSJohannes Doerfert // and if so make sure its equivalence class is preloaded.
1069af3e301aSJohannes Doerfert SetVector<Value *> Values;
10707b811035SJohannes Doerfert findValues(ParamSCEV, SE, Values);
1071fdbf201fSJohannes Doerfert for (auto *Val : Values) {
1072fdbf201fSJohannes Doerfert // Check if the value is an instruction in a dead block within the SCoP
1073fdbf201fSJohannes Doerfert // and if so do not code generate it.
1074fdbf201fSJohannes Doerfert if (auto *Inst = dyn_cast<Instruction>(Val)) {
1075952b5304SJohannes Doerfert if (S.contains(Inst)) {
1076fdbf201fSJohannes Doerfert bool IsDead = true;
1077fdbf201fSJohannes Doerfert
1078fdbf201fSJohannes Doerfert // Check for "undef" loads first, then if there is a statement for
1079fdbf201fSJohannes Doerfert // the parent of Inst and lastly if the parent of Inst has an empty
1080fdbf201fSJohannes Doerfert // domain. In the first and last case the instruction is dead but if
1081fdbf201fSJohannes Doerfert // there is a statement or the domain is not empty Inst is not dead.
108270131d34SMichael Kruse auto MemInst = MemAccInst::dyn_cast(Inst);
108370131d34SMichael Kruse auto Address = MemInst ? MemInst.getPointerOperand() : nullptr;
1084ff40087aSTobias Grosser if (Address && SE.getUnknown(UndefValue::get(Address->getType())) ==
1085fdbf201fSJohannes Doerfert SE.getPointerBase(SE.getSCEV(Address))) {
10866f7721f0SMichael Kruse } else if (S.getStmtFor(Inst)) {
1087fdbf201fSJohannes Doerfert IsDead = false;
1088fdbf201fSJohannes Doerfert } else {
108961bd3a48STobias Grosser auto *Domain = S.getDomainConditions(Inst->getParent()).release();
1090fdbf201fSJohannes Doerfert IsDead = isl_set_is_empty(Domain);
1091fdbf201fSJohannes Doerfert isl_set_free(Domain);
1092fdbf201fSJohannes Doerfert }
1093fdbf201fSJohannes Doerfert
1094fdbf201fSJohannes Doerfert if (IsDead) {
1095fdbf201fSJohannes Doerfert V = UndefValue::get(ParamSCEV->getType());
1096fdbf201fSJohannes Doerfert break;
1097fdbf201fSJohannes Doerfert }
1098fdbf201fSJohannes Doerfert }
1099fdbf201fSJohannes Doerfert }
1100fdbf201fSJohannes Doerfert
11018ab2803bSJohannes Doerfert if (auto *IAClass = S.lookupInvariantEquivClass(Val)) {
1102fc4bfc46SJohannes Doerfert // Check if this invariant access class is empty, hence if we never
1103fc4bfc46SJohannes Doerfert // actually added a loads instruction to it. In that case it has no
1104fc4bfc46SJohannes Doerfert // (meaningful) users and we should not try to code generate it.
11054e2d9c45STobias Grosser if (IAClass->InvariantAccesses.empty())
1106fc4bfc46SJohannes Doerfert V = UndefValue::get(ParamSCEV->getType());
1107fc4bfc46SJohannes Doerfert
1108c4898504SJohannes Doerfert if (!preloadInvariantEquivClass(*IAClass)) {
1109c4898504SJohannes Doerfert isl_id_free(Id);
1110c4898504SJohannes Doerfert return false;
1111c4898504SJohannes Doerfert }
1112fc4bfc46SJohannes Doerfert }
1113fdbf201fSJohannes Doerfert }
1114af3e301aSJohannes Doerfert
1115fdbf201fSJohannes Doerfert V = V ? V : generateSCEV(ParamSCEV);
11161d45c6daSTobias Grosser IDToValue[Id] = V;
11171d45c6daSTobias Grosser }
1118ebfd7249SJohannes Doerfert
1119ebfd7249SJohannes Doerfert isl_id_free(Id);
1120c4898504SJohannes Doerfert return true;
1121ebfd7249SJohannes Doerfert }
1122ebfd7249SJohannes Doerfert
materializeParameters(__isl_take isl_set * Set)1123ad84c6f6SMichael Kruse bool IslNodeBuilder::materializeParameters(__isl_take isl_set *Set) {
1124ebfd7249SJohannes Doerfert for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) {
1125b28f86e9STobias Grosser if (!isl_set_involves_dims(Set, isl_dim_param, i, 1))
1126ebfd7249SJohannes Doerfert continue;
1127ebfd7249SJohannes Doerfert isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i);
1128c4898504SJohannes Doerfert if (!materializeValue(Id))
1129c4898504SJohannes Doerfert return false;
1130ebfd7249SJohannes Doerfert }
1131c4898504SJohannes Doerfert return true;
1132ebfd7249SJohannes Doerfert }
1133ebfd7249SJohannes Doerfert
materializeParameters()1134b28f86e9STobias Grosser bool IslNodeBuilder::materializeParameters() {
1135b28f86e9STobias Grosser for (const SCEV *Param : S.parameters()) {
11369a63570bSTobias Grosser isl_id *Id = S.getIdForParam(Param).release();
1137b28f86e9STobias Grosser if (!materializeValue(Id))
1138b28f86e9STobias Grosser return false;
1139b28f86e9STobias Grosser }
1140b28f86e9STobias Grosser return true;
1141b28f86e9STobias Grosser }
1142b28f86e9STobias Grosser
preloadUnconditionally(__isl_take isl_set * AccessRange,isl_ast_build * Build,Instruction * AccInst)1143ad84c6f6SMichael Kruse Value *IslNodeBuilder::preloadUnconditionally(__isl_take isl_set *AccessRange,
1144370cf00cSJohannes Doerfert isl_ast_build *Build,
1145370cf00cSJohannes Doerfert Instruction *AccInst) {
1146c1db67e2SJohannes Doerfert isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange);
1147c1db67e2SJohannes Doerfert isl_ast_expr *Access =
1148c1db67e2SJohannes Doerfert isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
1149107cd5f5STobias Grosser auto *Address = isl_ast_expr_address_of(Access);
1150107cd5f5STobias Grosser auto *AddressValue = ExprBuilder.create(Address);
1151107cd5f5STobias Grosser Value *PreloadVal;
1152370cf00cSJohannes Doerfert
1153dcfedf35SJohannes Doerfert // Correct the type as the SAI might have a different type than the user
1154dcfedf35SJohannes Doerfert // expects, especially if the base pointer is a struct.
1155370cf00cSJohannes Doerfert Type *Ty = AccInst->getType();
1156dcfedf35SJohannes Doerfert
1157107cd5f5STobias Grosser auto *Ptr = AddressValue;
1158107cd5f5STobias Grosser auto Name = Ptr->getName();
11590f8f1776SHongbin Zheng auto AS = Ptr->getType()->getPointerAddressSpace();
11600f8f1776SHongbin Zheng Ptr = Builder.CreatePointerCast(Ptr, Ty->getPointerTo(AS), Name + ".cast");
116146354bacSNikita Popov PreloadVal = Builder.CreateLoad(Ty, Ptr, Name + ".load");
1162370cf00cSJohannes Doerfert if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal))
11633f13ee8aSEli Friedman PreloadInst->setAlignment(cast<LoadInst>(AccInst)->getAlign());
1164370cf00cSJohannes Doerfert
1165a61eda76SJohannes Doerfert // TODO: This is only a hot fix for SCoP sequences that use the same load
1166a61eda76SJohannes Doerfert // instruction contained and hoisted by one of the SCoPs.
1167a61eda76SJohannes Doerfert if (SE.isSCEVable(Ty))
1168a61eda76SJohannes Doerfert SE.forgetValue(AccInst);
1169a61eda76SJohannes Doerfert
1170d8b6ad25SJohannes Doerfert return PreloadVal;
1171c1db67e2SJohannes Doerfert }
1172c1db67e2SJohannes Doerfert
preloadInvariantLoad(const MemoryAccess & MA,__isl_take isl_set * Domain)1173c1db67e2SJohannes Doerfert Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA,
1174ad84c6f6SMichael Kruse __isl_take isl_set *Domain) {
11756a87036eSTobias Grosser isl_set *AccessRange = isl_map_range(MA.getAddressFunction().release());
11768ea1fc19STobias Grosser AccessRange = isl_set_gist_params(AccessRange, S.getContext().release());
1177e243753aSJohannes Doerfert
1178b28f86e9STobias Grosser if (!materializeParameters(AccessRange)) {
1179c4898504SJohannes Doerfert isl_set_free(AccessRange);
1180c4898504SJohannes Doerfert isl_set_free(Domain);
1181c4898504SJohannes Doerfert return nullptr;
1182c4898504SJohannes Doerfert }
118309e3697fSJohannes Doerfert
1184b65ccc43STobias Grosser auto *Build =
1185b65ccc43STobias Grosser isl_ast_build_from_context(isl_set_universe(S.getParamSpace().release()));
1186c1db67e2SJohannes Doerfert isl_set *Universe = isl_set_universe(isl_set_get_space(Domain));
1187c1db67e2SJohannes Doerfert bool AlwaysExecuted = isl_set_is_equal(Domain, Universe);
1188c1db67e2SJohannes Doerfert isl_set_free(Universe);
1189c1db67e2SJohannes Doerfert
1190d8b6ad25SJohannes Doerfert Instruction *AccInst = MA.getAccessInstruction();
1191d8b6ad25SJohannes Doerfert Type *AccInstTy = AccInst->getType();
1192d8b6ad25SJohannes Doerfert
1193c4898504SJohannes Doerfert Value *PreloadVal = nullptr;
1194c1db67e2SJohannes Doerfert if (AlwaysExecuted) {
1195370cf00cSJohannes Doerfert PreloadVal = preloadUnconditionally(AccessRange, Build, AccInst);
1196c4898504SJohannes Doerfert isl_ast_build_free(Build);
1197c4898504SJohannes Doerfert isl_set_free(Domain);
1198c4898504SJohannes Doerfert return PreloadVal;
1199c4898504SJohannes Doerfert }
1200c1db67e2SJohannes Doerfert
1201b28f86e9STobias Grosser if (!materializeParameters(Domain)) {
1202c4898504SJohannes Doerfert isl_ast_build_free(Build);
1203c4898504SJohannes Doerfert isl_set_free(AccessRange);
1204c4898504SJohannes Doerfert isl_set_free(Domain);
1205c4898504SJohannes Doerfert return nullptr;
1206c4898504SJohannes Doerfert }
1207c4898504SJohannes Doerfert
1208c1db67e2SJohannes Doerfert isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain);
1209c4898504SJohannes Doerfert Domain = nullptr;
1210c1db67e2SJohannes Doerfert
1211404a0f81SJohannes Doerfert ExprBuilder.setTrackOverflow(true);
1212c1db67e2SJohannes Doerfert Value *Cond = ExprBuilder.create(DomainCond);
1213404a0f81SJohannes Doerfert Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(),
1214404a0f81SJohannes Doerfert "polly.preload.cond.overflown");
1215404a0f81SJohannes Doerfert Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result");
1216404a0f81SJohannes Doerfert ExprBuilder.setTrackOverflow(false);
1217404a0f81SJohannes Doerfert
1218c1db67e2SJohannes Doerfert if (!Cond->getType()->isIntegerTy(1))
1219c1db67e2SJohannes Doerfert Cond = Builder.CreateIsNotNull(Cond);
1220c1db67e2SJohannes Doerfert
1221c1db67e2SJohannes Doerfert BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1222b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI);
1223c1db67e2SJohannes Doerfert CondBB->setName("polly.preload.cond");
1224c1db67e2SJohannes Doerfert
1225b8f58b53SDuncan P. N. Exon Smith BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
1226c1db67e2SJohannes Doerfert MergeBB->setName("polly.preload.merge");
1227c1db67e2SJohannes Doerfert
1228c1db67e2SJohannes Doerfert Function *F = Builder.GetInsertBlock()->getParent();
1229c1db67e2SJohannes Doerfert LLVMContext &Context = F->getContext();
1230c1db67e2SJohannes Doerfert BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F);
1231c1db67e2SJohannes Doerfert
1232c1db67e2SJohannes Doerfert DT.addNewBlock(ExecBB, CondBB);
1233c1db67e2SJohannes Doerfert if (Loop *L = LI.getLoopFor(CondBB))
1234c1db67e2SJohannes Doerfert L->addBasicBlockToLoop(ExecBB, LI);
1235c1db67e2SJohannes Doerfert
1236c1db67e2SJohannes Doerfert auto *CondBBTerminator = CondBB->getTerminator();
1237c1db67e2SJohannes Doerfert Builder.SetInsertPoint(CondBBTerminator);
1238c1db67e2SJohannes Doerfert Builder.CreateCondBr(Cond, ExecBB, MergeBB);
1239c1db67e2SJohannes Doerfert CondBBTerminator->eraseFromParent();
1240c1db67e2SJohannes Doerfert
1241c1db67e2SJohannes Doerfert Builder.SetInsertPoint(ExecBB);
1242c1db67e2SJohannes Doerfert Builder.CreateBr(MergeBB);
1243c1db67e2SJohannes Doerfert
1244c1db67e2SJohannes Doerfert Builder.SetInsertPoint(ExecBB->getTerminator());
1245370cf00cSJohannes Doerfert Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst);
1246c1db67e2SJohannes Doerfert Builder.SetInsertPoint(MergeBB->getTerminator());
1247c1db67e2SJohannes Doerfert auto *MergePHI = Builder.CreatePHI(
1248c1db67e2SJohannes Doerfert AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge");
1249abadd71dSJohannes Doerfert PreloadVal = MergePHI;
1250abadd71dSJohannes Doerfert
1251abadd71dSJohannes Doerfert if (!PreAccInst) {
1252abadd71dSJohannes Doerfert PreloadVal = nullptr;
1253abadd71dSJohannes Doerfert PreAccInst = UndefValue::get(AccInstTy);
1254abadd71dSJohannes Doerfert }
1255abadd71dSJohannes Doerfert
1256c1db67e2SJohannes Doerfert MergePHI->addIncoming(PreAccInst, ExecBB);
1257c1db67e2SJohannes Doerfert MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB);
1258d8b6ad25SJohannes Doerfert
1259d8b6ad25SJohannes Doerfert isl_ast_build_free(Build);
1260d8b6ad25SJohannes Doerfert return PreloadVal;
1261c1db67e2SJohannes Doerfert }
1262c1db67e2SJohannes Doerfert
preloadInvariantEquivClass(InvariantEquivClassTy & IAClass)1263c4898504SJohannes Doerfert bool IslNodeBuilder::preloadInvariantEquivClass(
12648ab2803bSJohannes Doerfert InvariantEquivClassTy &IAClass) {
1265af3e301aSJohannes Doerfert // For an equivalence class of invariant loads we pre-load the representing
1266697fdf89SJohannes Doerfert // element with the unified execution context. However, we have to map all
1267697fdf89SJohannes Doerfert // elements of the class to the one preloaded load as they are referenced
1268697fdf89SJohannes Doerfert // during the code generation and therefor need to be mapped.
12694e2d9c45STobias Grosser const MemoryAccessList &MAs = IAClass.InvariantAccesses;
1270fc4bfc46SJohannes Doerfert if (MAs.empty())
1271fc4bfc46SJohannes Doerfert return true;
1272fc4bfc46SJohannes Doerfert
1273af3e301aSJohannes Doerfert MemoryAccess *MA = MAs.front();
1274a535dff4STobias Grosser assert(MA->isArrayKind() && MA->isRead());
1275697fdf89SJohannes Doerfert
1276af3e301aSJohannes Doerfert // If the access function was already mapped, the preload of this equivalence
1277af3e301aSJohannes Doerfert // class was triggered earlier already and doesn't need to be done again.
1278af3e301aSJohannes Doerfert if (ValueMap.count(MA->getAccessInstruction()))
1279c4898504SJohannes Doerfert return true;
1280c4898504SJohannes Doerfert
12812219d157STobias Grosser // Check for recursion which can be caused by additional constraints, e.g.,
12822219d157STobias Grosser // non-finite loop constraints. In such a case we have to bail out and insert
1283c4898504SJohannes Doerfert // a "false" runtime check that will cause the original code to be executed.
1284faef9a76STobias Grosser auto PtrId = std::make_pair(IAClass.IdentifyingPointer, IAClass.AccessType);
128596e54711SJohannes Doerfert if (!PreloadedPtrs.insert(PtrId).second)
1286c4898504SJohannes Doerfert return false;
1287c1db67e2SJohannes Doerfert
12882219d157STobias Grosser // The execution context of the IAClass.
128900fd43b3SPhilip Pfaffe isl::set &ExecutionCtx = IAClass.ExecutionContext;
12908ab2803bSJohannes Doerfert
1291475d8e3fSJohannes Doerfert // If the base pointer of this class is dependent on another one we have to
1292475d8e3fSJohannes Doerfert // make sure it was preloaded already.
1293adeab372SJohannes Doerfert auto *SAI = MA->getScopArrayInfo();
12948ab2803bSJohannes Doerfert if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) {
1295c4898504SJohannes Doerfert if (!preloadInvariantEquivClass(*BaseIAClass))
1296c4898504SJohannes Doerfert return false;
1297475d8e3fSJohannes Doerfert
12988ab2803bSJohannes Doerfert // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and
12998ab2803bSJohannes Doerfert // we need to refine the ExecutionCtx.
130000fd43b3SPhilip Pfaffe isl::set BaseExecutionCtx = BaseIAClass->ExecutionContext;
130100fd43b3SPhilip Pfaffe ExecutionCtx = ExecutionCtx.intersect(BaseExecutionCtx);
13028ab2803bSJohannes Doerfert }
13038ab2803bSJohannes Doerfert
13043c1a75bfSEli Friedman // If the size of a dimension is dependent on another class, make sure it is
13053c1a75bfSEli Friedman // preloaded.
13063c1a75bfSEli Friedman for (unsigned i = 1, e = SAI->getNumberOfDimensions(); i < e; ++i) {
13073c1a75bfSEli Friedman const SCEV *Dim = SAI->getDimensionSize(i);
13083c1a75bfSEli Friedman SetVector<Value *> Values;
13093c1a75bfSEli Friedman findValues(Dim, SE, Values);
13103c1a75bfSEli Friedman for (auto *Val : Values) {
13113c1a75bfSEli Friedman if (auto *BaseIAClass = S.lookupInvariantEquivClass(Val)) {
13123c1a75bfSEli Friedman if (!preloadInvariantEquivClass(*BaseIAClass))
13133c1a75bfSEli Friedman return false;
13143c1a75bfSEli Friedman
13153c1a75bfSEli Friedman // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx
13163c1a75bfSEli Friedman // and we need to refine the ExecutionCtx.
131700fd43b3SPhilip Pfaffe isl::set BaseExecutionCtx = BaseIAClass->ExecutionContext;
131800fd43b3SPhilip Pfaffe ExecutionCtx = ExecutionCtx.intersect(BaseExecutionCtx);
13193c1a75bfSEli Friedman }
13203c1a75bfSEli Friedman }
13213c1a75bfSEli Friedman }
13223c1a75bfSEli Friedman
1323c1db67e2SJohannes Doerfert Instruction *AccInst = MA->getAccessInstruction();
1324af3e301aSJohannes Doerfert Type *AccInstTy = AccInst->getType();
1325af3e301aSJohannes Doerfert
132600fd43b3SPhilip Pfaffe Value *PreloadVal = preloadInvariantLoad(*MA, ExecutionCtx.copy());
1327c4898504SJohannes Doerfert if (!PreloadVal)
1328c4898504SJohannes Doerfert return false;
1329c4898504SJohannes Doerfert
1330af3e301aSJohannes Doerfert for (const MemoryAccess *MA : MAs) {
1331af3e301aSJohannes Doerfert Instruction *MAAccInst = MA->getAccessInstruction();
133296e54711SJohannes Doerfert assert(PreloadVal->getType() == MAAccInst->getType());
133396e54711SJohannes Doerfert ValueMap[MAAccInst] = PreloadVal;
1334d8b6ad25SJohannes Doerfert }
1335c1db67e2SJohannes Doerfert
1336af3e301aSJohannes Doerfert if (SE.isSCEVable(AccInstTy)) {
13379a63570bSTobias Grosser isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst)).release();
1338c1db67e2SJohannes Doerfert if (ParamId)
1339c1db67e2SJohannes Doerfert IDToValue[ParamId] = PreloadVal;
1340c1db67e2SJohannes Doerfert isl_id_free(ParamId);
1341c1db67e2SJohannes Doerfert }
1342c1db67e2SJohannes Doerfert
1343af3e301aSJohannes Doerfert BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1344b3e30c32SMatt Arsenault auto *Alloca = new AllocaInst(AccInstTy, DL.getAllocaAddrSpace(),
13454f04db4bSEli Friedman AccInst->getName() + ".preload.s2a",
13464f04db4bSEli Friedman &*EntryBB->getFirstInsertionPt());
1347af3e301aSJohannes Doerfert Builder.CreateStore(PreloadVal, Alloca);
134823df2768SRoman Gareev ValueMapT PreloadedPointer;
134923df2768SRoman Gareev PreloadedPointer[PreloadVal] = AccInst;
135023df2768SRoman Gareev Annotator.addAlternativeAliasBases(PreloadedPointer);
1351af3e301aSJohannes Doerfert
13527a6e292dSJohannes Doerfert for (auto *DerivedSAI : SAI->getDerivedSAIs()) {
13537a6e292dSJohannes Doerfert Value *BasePtr = DerivedSAI->getBasePtr();
13547a6e292dSJohannes Doerfert
13557a6e292dSJohannes Doerfert for (const MemoryAccess *MA : MAs) {
13567a6e292dSJohannes Doerfert // As the derived SAI information is quite coarse, any load from the
13577a6e292dSJohannes Doerfert // current SAI could be the base pointer of the derived SAI, however we
13587a6e292dSJohannes Doerfert // should only change the base pointer of the derived SAI if we actually
13597a6e292dSJohannes Doerfert // preloaded it.
1360f3adab4cSTobias Grosser if (BasePtr == MA->getOriginalBaseAddr()) {
136196e54711SJohannes Doerfert assert(BasePtr->getType() == PreloadVal->getType());
136296e54711SJohannes Doerfert DerivedSAI->setBasePtr(PreloadVal);
13637a6e292dSJohannes Doerfert }
13647a6e292dSJohannes Doerfert
13657a6e292dSJohannes Doerfert // For scalar derived SAIs we remap the alloca used for the derived value.
1366587f1f57STobias Grosser if (BasePtr == MA->getAccessInstruction())
1367587f1f57STobias Grosser ScalarMap[DerivedSAI] = Alloca;
13687a6e292dSJohannes Doerfert }
13697a6e292dSJohannes Doerfert }
13707a6e292dSJohannes Doerfert
1371af3e301aSJohannes Doerfert for (const MemoryAccess *MA : MAs) {
1372af3e301aSJohannes Doerfert Instruction *MAAccInst = MA->getAccessInstruction();
1373af3e301aSJohannes Doerfert // Use the escape system to get the correct value to users outside the SCoP.
1374ef19ead2SJohannes Doerfert BlockGenerator::EscapeUserVectorTy EscapeUsers;
1375af3e301aSJohannes Doerfert for (auto *U : MAAccInst->users())
1376ef19ead2SJohannes Doerfert if (Instruction *UI = dyn_cast<Instruction>(U))
1377952b5304SJohannes Doerfert if (!S.contains(UI))
1378ef19ead2SJohannes Doerfert EscapeUsers.push_back(UI);
1379ef19ead2SJohannes Doerfert
1380ef19ead2SJohannes Doerfert if (EscapeUsers.empty())
1381ef19ead2SJohannes Doerfert continue;
1382ef19ead2SJohannes Doerfert
1383af3e301aSJohannes Doerfert EscapeMap[MA->getAccessInstruction()] =
1384af3e301aSJohannes Doerfert std::make_pair(Alloca, std::move(EscapeUsers));
1385c1db67e2SJohannes Doerfert }
1386c4898504SJohannes Doerfert
1387c4898504SJohannes Doerfert return true;
1388c1db67e2SJohannes Doerfert }
1389c1db67e2SJohannes Doerfert
allocateNewArrays(BBPair StartExitBlocks)1390b738ffa8SMichael Kruse void IslNodeBuilder::allocateNewArrays(BBPair StartExitBlocks) {
1391d7754a12SRoman Gareev for (auto &SAI : S.arrays()) {
1392d7754a12SRoman Gareev if (SAI->getBasePtr())
1393d7754a12SRoman Gareev continue;
1394d7754a12SRoman Gareev
1395f5aff704SRoman Gareev assert(SAI->getNumberOfDimensions() > 0 && SAI->getDimensionSize(0) &&
1396f5aff704SRoman Gareev "The size of the outermost dimension is used to declare newly "
1397f5aff704SRoman Gareev "created arrays that require memory allocation.");
1398f5aff704SRoman Gareev
1399d7754a12SRoman Gareev Type *NewArrayType = nullptr;
1400b738ffa8SMichael Kruse
1401b738ffa8SMichael Kruse // Get the size of the array = size(dim_1)*...*size(dim_n)
1402b738ffa8SMichael Kruse uint64_t ArraySizeInt = 1;
1403f5aff704SRoman Gareev for (int i = SAI->getNumberOfDimensions() - 1; i >= 0; i--) {
1404d7754a12SRoman Gareev auto *DimSize = SAI->getDimensionSize(i);
1405d7754a12SRoman Gareev unsigned UnsignedDimSize = static_cast<const SCEVConstant *>(DimSize)
1406d7754a12SRoman Gareev ->getAPInt()
1407d7754a12SRoman Gareev .getLimitedValue();
1408d7754a12SRoman Gareev
1409d7754a12SRoman Gareev if (!NewArrayType)
1410d7754a12SRoman Gareev NewArrayType = SAI->getElementType();
1411d7754a12SRoman Gareev
1412d7754a12SRoman Gareev NewArrayType = ArrayType::get(NewArrayType, UnsignedDimSize);
1413b738ffa8SMichael Kruse ArraySizeInt *= UnsignedDimSize;
1414d7754a12SRoman Gareev }
1415d7754a12SRoman Gareev
1416b738ffa8SMichael Kruse if (SAI->isOnHeap()) {
1417b738ffa8SMichael Kruse LLVMContext &Ctx = NewArrayType->getContext();
1418b738ffa8SMichael Kruse
1419b738ffa8SMichael Kruse // Get the IntPtrTy from the Datalayout
1420b738ffa8SMichael Kruse auto IntPtrTy = DL.getIntPtrType(Ctx);
1421b738ffa8SMichael Kruse
1422b738ffa8SMichael Kruse // Get the size of the element type in bits
1423b738ffa8SMichael Kruse unsigned Size = SAI->getElemSizeInBytes();
1424b738ffa8SMichael Kruse
1425b738ffa8SMichael Kruse // Insert the malloc call at polly.start
1426b738ffa8SMichael Kruse auto InstIt = std::get<0>(StartExitBlocks)->getTerminator();
1427b738ffa8SMichael Kruse auto *CreatedArray = CallInst::CreateMalloc(
1428b738ffa8SMichael Kruse &*InstIt, IntPtrTy, SAI->getElementType(),
1429b738ffa8SMichael Kruse ConstantInt::get(Type::getInt64Ty(Ctx), Size),
1430b738ffa8SMichael Kruse ConstantInt::get(Type::getInt64Ty(Ctx), ArraySizeInt), nullptr,
1431b738ffa8SMichael Kruse SAI->getName());
1432b738ffa8SMichael Kruse
1433b738ffa8SMichael Kruse SAI->setBasePtr(CreatedArray);
1434b738ffa8SMichael Kruse
1435b738ffa8SMichael Kruse // Insert the free call at polly.exiting
1436b738ffa8SMichael Kruse CallInst::CreateFree(CreatedArray,
1437b738ffa8SMichael Kruse std::get<1>(StartExitBlocks)->getTerminator());
1438b738ffa8SMichael Kruse } else {
1439b738ffa8SMichael Kruse auto InstIt = Builder.GetInsertBlock()
1440b738ffa8SMichael Kruse ->getParent()
1441b738ffa8SMichael Kruse ->getEntryBlock()
1442b738ffa8SMichael Kruse .getTerminator();
1443b738ffa8SMichael Kruse
1444b3e30c32SMatt Arsenault auto *CreatedArray = new AllocaInst(NewArrayType, DL.getAllocaAddrSpace(),
1445b3e30c32SMatt Arsenault SAI->getName(), &*InstIt);
14464f04db4bSEli Friedman if (PollyTargetFirstLevelCacheLineSize)
14474f04db4bSEli Friedman CreatedArray->setAlignment(Align(PollyTargetFirstLevelCacheLineSize));
1448d7754a12SRoman Gareev SAI->setBasePtr(CreatedArray);
1449d7754a12SRoman Gareev }
1450d7754a12SRoman Gareev }
1451b738ffa8SMichael Kruse }
1452d7754a12SRoman Gareev
preloadInvariantLoads()1453c4898504SJohannes Doerfert bool IslNodeBuilder::preloadInvariantLoads() {
14548ab2803bSJohannes Doerfert auto &InvariantEquivClasses = S.getInvariantAccesses();
1455af3e301aSJohannes Doerfert if (InvariantEquivClasses.empty())
1456c4898504SJohannes Doerfert return true;
1457af3e301aSJohannes Doerfert
1458b8f58b53SDuncan P. N. Exon Smith BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(),
1459b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI);
1460af3e301aSJohannes Doerfert PreLoadBB->setName("polly.preload.begin");
1461b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&PreLoadBB->front());
1462af3e301aSJohannes Doerfert
14638ab2803bSJohannes Doerfert for (auto &IAClass : InvariantEquivClasses)
1464c4898504SJohannes Doerfert if (!preloadInvariantEquivClass(IAClass))
1465c4898504SJohannes Doerfert return false;
1466c4898504SJohannes Doerfert
1467c4898504SJohannes Doerfert return true;
1468af3e301aSJohannes Doerfert }
1469af3e301aSJohannes Doerfert
addParameters(__isl_take isl_set * Context)14700c55cb60STobias Grosser void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
1471ebfd7249SJohannes Doerfert // Materialize values for the parameters of the SCoP.
1472b28f86e9STobias Grosser materializeParameters();
14730c55cb60STobias Grosser
14740c55cb60STobias Grosser // Generate values for the current loop iteration for all surrounding loops.
14750c55cb60STobias Grosser //
14760c55cb60STobias Grosser // We may also reference loops outside of the scop which do not contain the
14770c55cb60STobias Grosser // scop itself, but as the number of such scops may be arbitrarily large we do
14780c55cb60STobias Grosser // not generate code for them here, but only at the point of code generation
14790c55cb60STobias Grosser // where these values are needed.
1480ef74443cSJohannes Doerfert Loop *L = LI.getLoopFor(S.getEntry());
14810c55cb60STobias Grosser
1482952b5304SJohannes Doerfert while (L != nullptr && S.contains(L))
14830c55cb60STobias Grosser L = L->getParentLoop();
14840c55cb60STobias Grosser
14850c55cb60STobias Grosser while (L != nullptr) {
14860caed1fbSSiddharth Bhat materializeNonScopLoopInductionVariable(L);
14870c55cb60STobias Grosser L = L->getParentLoop();
14880c55cb60STobias Grosser }
14890c55cb60STobias Grosser
14900c55cb60STobias Grosser isl_set_free(Context);
14910c55cb60STobias Grosser }
14920c55cb60STobias Grosser
generateSCEV(const SCEV * Expr)14930c55cb60STobias Grosser Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
1494000db707STobias Grosser /// We pass the insert location of our Builder, as Polly ensures during IR
1495000db707STobias Grosser /// generation that there is always a valid CFG into which instructions are
1496000db707STobias Grosser /// inserted. As a result, the insertpoint is known to be always followed by a
1497000db707STobias Grosser /// terminator instruction. This means the insert point may be specified by a
1498000db707STobias Grosser /// terminator instruction, but it can never point to an ->end() iterator
1499000db707STobias Grosser /// which does not have a corresponding instruction. Hence, dereferencing
1500000db707STobias Grosser /// the insertpoint to obtain an instruction is known to be save.
1501000db707STobias Grosser ///
1502000db707STobias Grosser /// We also do not need to update the Builder here, as new instructions are
1503000db707STobias Grosser /// always inserted _before_ the given InsertLocation. As a result, the
1504000db707STobias Grosser /// insert location remains valid.
1505fa9abd1fSTobias Grosser assert(Builder.GetInsertBlock()->end() != Builder.GetInsertPoint() &&
1506000db707STobias Grosser "Insert location points after last valid instruction");
1507000db707STobias Grosser Instruction *InsertLocation = &*Builder.GetInsertPoint();
1508e69e1141SJohannes Doerfert return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(),
1509acf80064SEli Friedman InsertLocation, &ValueMap,
1510acf80064SEli Friedman StartBlock->getSinglePredecessor());
15110c55cb60STobias Grosser }
15120aa29532STobias Grosser
15130aa29532STobias Grosser /// The AST expression we generate to perform the run-time check assumes
15140aa29532STobias Grosser /// computations on integer types of infinite size. As we only use 64-bit
15150aa29532STobias Grosser /// arithmetic we check for overflows, in case of which we set the result
1516a6d48f59SMichael Kruse /// of this run-time check to false to be conservatively correct,
createRTC(isl_ast_expr * Condition)15170aa29532STobias Grosser Value *IslNodeBuilder::createRTC(isl_ast_expr *Condition) {
15180aa29532STobias Grosser auto ExprBuilder = getExprBuilder();
151975d133f0STobias Grosser
152075d133f0STobias Grosser // In case the AST expression has integers larger than 64 bit, bail out. The
152175d133f0STobias Grosser // resulting LLVM-IR will contain operations on types that use more than 64
152275d133f0STobias Grosser // bits. These are -- in case wrapping intrinsics are used -- translated to
152375d133f0STobias Grosser // runtime library calls that are not available on all systems (e.g., Android)
152475d133f0STobias Grosser // and consequently will result in linker errors.
1525718d04c6STobias Grosser if (ExprBuilder.hasLargeInts(isl::manage_copy(Condition))) {
152675d133f0STobias Grosser isl_ast_expr_free(Condition);
152775d133f0STobias Grosser return Builder.getFalse();
152875d133f0STobias Grosser }
152975d133f0STobias Grosser
15300aa29532STobias Grosser ExprBuilder.setTrackOverflow(true);
15310aa29532STobias Grosser Value *RTC = ExprBuilder.create(Condition);
15320aa29532STobias Grosser if (!RTC->getType()->isIntegerTy(1))
15330aa29532STobias Grosser RTC = Builder.CreateIsNotNull(RTC);
15340aa29532STobias Grosser Value *OverflowHappened =
15350aa29532STobias Grosser Builder.CreateNot(ExprBuilder.getOverflowState(), "polly.rtc.overflown");
15368c5464a7SJohannes Doerfert
15378c5464a7SJohannes Doerfert if (PollyGenerateRTCPrint) {
15388c5464a7SJohannes Doerfert auto *F = Builder.GetInsertBlock()->getParent();
1539dc6b87c5STobias Grosser RuntimeDebugBuilder::createCPUPrinter(
1540dc6b87c5STobias Grosser Builder,
1541dc6b87c5STobias Grosser "F: " + F->getName().str() + " R: " + S.getRegion().getNameStr() +
15429f2eb24cSTobias Grosser "RTC: ",
15439f2eb24cSTobias Grosser RTC, " Overflow: ", OverflowHappened,
15449f2eb24cSTobias Grosser "\n"
15459f2eb24cSTobias Grosser " (0 failed, -1 succeeded)\n"
15469f2eb24cSTobias Grosser " (if one or both are 0 falling back to original code, if both are -1 "
15479f2eb24cSTobias Grosser "executing Polly code)\n");
15488c5464a7SJohannes Doerfert }
15498c5464a7SJohannes Doerfert
15500aa29532STobias Grosser RTC = Builder.CreateAnd(RTC, OverflowHappened, "polly.rtc.result");
15510aa29532STobias Grosser ExprBuilder.setTrackOverflow(false);
1552dae2e928SJohannes Doerfert
1553dae2e928SJohannes Doerfert if (!isa<ConstantInt>(RTC))
155481aa6e88SJohannes Doerfert VersionedScops++;
1555dae2e928SJohannes Doerfert
15560aa29532STobias Grosser return RTC;
15570aa29532STobias Grosser }
1558