1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Take a scop created by ScopInfo and map it to GPU code using the ppcg
10 // GPU mapping strategy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/CodeGen/PPCGCodeGeneration.h"
15 #include "polly/CodeGen/CodeGeneration.h"
16 #include "polly/CodeGen/IslAst.h"
17 #include "polly/CodeGen/IslNodeBuilder.h"
18 #include "polly/CodeGen/PerfMonitor.h"
19 #include "polly/CodeGen/Utils.h"
20 #include "polly/DependenceInfo.h"
21 #include "polly/LinkAllPasses.h"
22 #include "polly/Options.h"
23 #include "polly/ScopDetection.h"
24 #include "polly/ScopInfo.h"
25 #include "polly/Support/ISLTools.h"
26 #include "polly/Support/SCEVValidator.h"
27 #include "llvm/ADT/PostOrderIterator.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/IR/IntrinsicsNVPTX.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Linker/Linker.h"
35 #include "llvm/MC/TargetRegistry.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "isl/union_map.h"
41 #include <algorithm>
42 
43 extern "C" {
44 #include "ppcg/cuda.h"
45 #include "ppcg/gpu.h"
46 #include "ppcg/ppcg.h"
47 }
48 
49 #include "llvm/Support/Debug.h"
50 
51 using namespace polly;
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "polly-codegen-ppcg"
55 
56 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
57                                   cl::desc("Dump the computed GPU Schedule"),
58                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
59                                   cl::cat(PollyCategory));
60 
61 static cl::opt<bool>
62     DumpCode("polly-acc-dump-code",
63              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
64              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
65 
66 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
67                                   cl::desc("Dump the kernel LLVM-IR"),
68                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
69                                   cl::cat(PollyCategory));
70 
71 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
72                                    cl::desc("Dump the kernel assembly code"),
73                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
74                                    cl::cat(PollyCategory));
75 
76 static cl::opt<bool> FastMath("polly-acc-fastmath",
77                               cl::desc("Allow unsafe math optimizations"),
78                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
79                               cl::cat(PollyCategory));
80 static cl::opt<bool> SharedMemory("polly-acc-use-shared",
81                                   cl::desc("Use shared memory"), cl::Hidden,
82                                   cl::init(false), cl::ZeroOrMore,
83                                   cl::cat(PollyCategory));
84 static cl::opt<bool> PrivateMemory("polly-acc-use-private",
85                                    cl::desc("Use private memory"), cl::Hidden,
86                                    cl::init(false), cl::ZeroOrMore,
87                                    cl::cat(PollyCategory));
88 
89 bool polly::PollyManagedMemory;
90 static cl::opt<bool, true>
91     XManagedMemory("polly-acc-codegen-managed-memory",
92                    cl::desc("Generate Host kernel code assuming"
93                             " that all memory has been"
94                             " declared as managed memory"),
95                    cl::location(PollyManagedMemory), cl::Hidden,
96                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
97 
98 static cl::opt<bool>
99     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
100                               cl::desc("Fail and generate a backtrace if"
101                                        " verifyModule fails on the GPU "
102                                        " kernel module."),
103                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
104                               cl::cat(PollyCategory));
105 
106 static cl::opt<std::string> CUDALibDevice(
107     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
108     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
109     cl::ZeroOrMore, cl::cat(PollyCategory));
110 
111 static cl::opt<std::string>
112     CudaVersion("polly-acc-cuda-version",
113                 cl::desc("The CUDA version to compile for"), cl::Hidden,
114                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
115 
116 static cl::opt<int>
117     MinCompute("polly-acc-mincompute",
118                cl::desc("Minimal number of compute statements to run on GPU."),
119                cl::Hidden, cl::init(10 * 512 * 512));
120 
121 GPURuntime polly::GPURuntimeChoice;
122 static cl::opt<GPURuntime, true> XGPURuntimeChoice(
123     "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"),
124     cl::values(clEnumValN(GPURuntime::CUDA, "libcudart",
125                           "use the CUDA Runtime API"),
126                clEnumValN(GPURuntime::OpenCL, "libopencl",
127                           "use the OpenCL Runtime API")),
128     cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA),
129     cl::ZeroOrMore, cl::cat(PollyCategory));
130 
131 GPUArch polly::GPUArchChoice;
132 static cl::opt<GPUArch, true>
133     XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"),
134                    cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64",
135                                          "target NVIDIA 64-bit architecture"),
136                               clEnumValN(GPUArch::SPIR32, "spir32",
137                                          "target SPIR 32-bit architecture"),
138                               clEnumValN(GPUArch::SPIR64, "spir64",
139                                          "target SPIR 64-bit architecture")),
140                    cl::location(polly::GPUArchChoice),
141                    cl::init(GPUArch::NVPTX64), cl::ZeroOrMore,
142                    cl::cat(PollyCategory));
143 
144 extern bool polly::PerfMonitoring;
145 
146 /// Return  a unique name for a Scop, which is the scop region with the
147 /// function name.
148 std::string getUniqueScopName(const Scop *S) {
149   return "Scop Region: " + S->getNameStr() +
150          " | Function: " + std::string(S->getFunction().getName());
151 }
152 
153 /// Used to store information PPCG wants for kills. This information is
154 /// used by live range reordering.
155 ///
156 /// @see computeLiveRangeReordering
157 /// @see GPUNodeBuilder::createPPCGScop
158 /// @see GPUNodeBuilder::createPPCGProg
159 struct MustKillsInfo {
160   /// Collection of all kill statements that will be sequenced at the end of
161   /// PPCGScop->schedule.
162   ///
163   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
164   /// which merges schedules in *arbitrary* order.
165   /// (we don't care about the order of the kills anyway).
166   isl::schedule KillsSchedule;
167   /// Map from kill statement instances to scalars that need to be
168   /// killed.
169   ///
170   /// We currently derive kill information for:
171   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
172   ///     consequently all be killed.
173   ///  2. Scalar arrays that are not used outside the Scop. This is
174   ///     checked by `isScalarUsesContainedInScop`.
175   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
176   isl::union_map TaggedMustKills;
177 
178   /// Tagged must kills stripped of the tags.
179   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
180   isl::union_map MustKills;
181 
182   MustKillsInfo() : KillsSchedule() {}
183 };
184 
185 /// Check if SAI's uses are entirely contained within Scop S.
186 /// If a scalar is used only with a Scop, we are free to kill it, as no data
187 /// can flow in/out of the value any more.
188 /// @see computeMustKillsInfo
189 static bool isScalarUsesContainedInScop(const Scop &S,
190                                         const ScopArrayInfo *SAI) {
191   assert(SAI->isValueKind() && "this function only deals with scalars."
192                                " Dealing with arrays required alias analysis");
193 
194   const Region &R = S.getRegion();
195   for (User *U : SAI->getBasePtr()->users()) {
196     Instruction *I = dyn_cast<Instruction>(U);
197     assert(I && "invalid user of scop array info");
198     if (!R.contains(I))
199       return false;
200   }
201   return true;
202 }
203 
204 /// Compute must-kills needed to enable live range reordering with PPCG.
205 ///
206 /// @params S The Scop to compute live range reordering information
207 /// @returns live range reordering information that can be used to setup
208 /// PPCG.
209 static MustKillsInfo computeMustKillsInfo(const Scop &S) {
210   const isl::space ParamSpace = S.getParamSpace();
211   MustKillsInfo Info;
212 
213   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
214   //      1.1 phi nodes in scop.
215   //      1.2 scalars that are only used within the scop
216   SmallVector<isl::id, 4> KillMemIds;
217   for (ScopArrayInfo *SAI : S.arrays()) {
218     if (SAI->isPHIKind() ||
219         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
220       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
221   }
222 
223   Info.TaggedMustKills = isl::union_map::empty(ParamSpace.ctx());
224   Info.MustKills = isl::union_map::empty(ParamSpace.ctx());
225 
226   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
227   // schedule:
228   //     - filter: "[control] -> { }"
229   // So, we choose to not create this to keep the output a little nicer,
230   // at the cost of some code complexity.
231   Info.KillsSchedule = {};
232 
233   for (isl::id &ToKillId : KillMemIds) {
234     isl::id KillStmtId = isl::id::alloc(
235         S.getIslCtx(),
236         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
237 
238     // NOTE: construction of tagged_must_kill:
239     // 2. We need to construct a map:
240     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
241     // To construct this, we use `isl_map_domain_product` on 2 maps`:
242     // 2a. StmtToScalar:
243     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
244     // 2b. PhantomRefToScalar:
245     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
246     //
247     // Combining these with `isl_map_domain_product` gives us
248     // TaggedMustKill:
249     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
250 
251     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
252     isl::map StmtToScalar = isl::map::universe(ParamSpace);
253     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
254     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
255 
256     isl::id PhantomRefId = isl::id::alloc(
257         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
258         nullptr);
259 
260     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
261     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
262     PhantomRefToScalar =
263         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
264     PhantomRefToScalar =
265         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
266 
267     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
268     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
269     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
270 
271     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
272     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
273 
274     // 3. Create the kill schedule of the form:
275     //     "[param] -> { Stmt_phantom[] }"
276     // Then add this to Info.KillsSchedule.
277     isl::space KillStmtSpace = ParamSpace;
278     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
279     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
280 
281     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
282     if (!Info.KillsSchedule.is_null())
283       Info.KillsSchedule = isl::manage(
284           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
285     else
286       Info.KillsSchedule = KillSchedule;
287   }
288 
289   return Info;
290 }
291 
292 /// Create the ast expressions for a ScopStmt.
293 ///
294 /// This function is a callback for to generate the ast expressions for each
295 /// of the scheduled ScopStmts.
296 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
297     void *StmtT, __isl_take isl_ast_build *Build_C,
298     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
299                                        isl_id *Id, void *User),
300     void *UserIndex,
301     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
302     void *UserExpr) {
303 
304   ScopStmt *Stmt = (ScopStmt *)StmtT;
305 
306   if (!Stmt || !Build_C)
307     return NULL;
308 
309   isl::ast_build Build = isl::manage_copy(Build_C);
310   isl::ctx Ctx = Build.ctx();
311   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
312 
313   Stmt->setAstBuild(Build);
314 
315   for (MemoryAccess *Acc : *Stmt) {
316     isl::map AddrFunc = Acc->getAddressFunction();
317     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
318 
319     isl::id RefId = Acc->getId();
320     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
321 
322     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
323     MPA = MPA.coalesce();
324     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
325 
326     isl::ast_expr Access = Build.access_from(MPA);
327     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
328     RefToExpr = RefToExpr.set(RefId, Access);
329   }
330 
331   return RefToExpr.release();
332 }
333 
334 /// Given a LLVM Type, compute its size in bytes,
335 static int computeSizeInBytes(const Type *T) {
336   int bytes = T->getPrimitiveSizeInBits() / 8;
337   if (bytes == 0)
338     bytes = T->getScalarSizeInBits() / 8;
339   return bytes;
340 }
341 
342 /// Generate code for a GPU specific isl AST.
343 ///
344 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
345 /// generates code for general-purpose AST nodes, with special functionality
346 /// for generating GPU specific user nodes.
347 ///
348 /// @see GPUNodeBuilder::createUser
349 class GPUNodeBuilder final : public IslNodeBuilder {
350 public:
351   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
352                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
353                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
354                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
355       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
356         Prog(Prog), Runtime(Runtime), Arch(Arch) {
357     getExprBuilder().setIDToSAI(&IDToSAI);
358   }
359 
360   /// Create after-run-time-check initialization code.
361   void initializeAfterRTH();
362 
363   /// Finalize the generated scop.
364   void finalize() override;
365 
366   /// Track if the full build process was successful.
367   ///
368   /// This value is set to false, if throughout the build process an error
369   /// occurred which prevents us from generating valid GPU code.
370   bool BuildSuccessful = true;
371 
372   /// The maximal number of loops surrounding a sequential kernel.
373   unsigned DeepestSequential = 0;
374 
375   /// The maximal number of loops surrounding a parallel kernel.
376   unsigned DeepestParallel = 0;
377 
378   /// Return the name to set for the ptx_kernel.
379   std::string getKernelFuncName(int Kernel_id);
380 
381 private:
382   /// A vector of array base pointers for which a new ScopArrayInfo was created.
383   ///
384   /// This vector is used to delete the ScopArrayInfo when it is not needed any
385   /// more.
386   std::vector<Value *> LocalArrays;
387 
388   /// A map from ScopArrays to their corresponding device allocations.
389   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
390 
391   /// The current GPU context.
392   Value *GPUContext;
393 
394   /// The set of isl_ids allocated in the kernel
395   std::vector<isl_id *> KernelIds;
396 
397   /// A module containing GPU code.
398   ///
399   /// This pointer is only set in case we are currently generating GPU code.
400   std::unique_ptr<Module> GPUModule;
401 
402   /// The GPU program we generate code for.
403   gpu_prog *Prog;
404 
405   /// The GPU Runtime implementation to use (OpenCL or CUDA).
406   GPURuntime Runtime;
407 
408   /// The GPU Architecture to target.
409   GPUArch Arch;
410 
411   /// Class to free isl_ids.
412   class IslIdDeleter final {
413   public:
414     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
415   };
416 
417   /// A set containing all isl_ids allocated in a GPU kernel.
418   ///
419   /// By releasing this set all isl_ids will be freed.
420   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
421 
422   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
423 
424   /// Create code for user-defined AST nodes.
425   ///
426   /// These AST nodes can be of type:
427   ///
428   ///   - ScopStmt:      A computational statement (TODO)
429   ///   - Kernel:        A GPU kernel call (TODO)
430   ///   - Data-Transfer: A GPU <-> CPU data-transfer
431   ///   - In-kernel synchronization
432   ///   - In-kernel memory copy statement
433   ///
434   /// @param UserStmt The ast node to generate code for.
435   void createUser(__isl_take isl_ast_node *UserStmt) override;
436 
437   void createFor(__isl_take isl_ast_node *Node) override;
438 
439   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
440 
441   /// Create code for a data transfer statement
442   ///
443   /// @param TransferStmt The data transfer statement.
444   /// @param Direction The direction in which to transfer data.
445   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
446                           enum DataDirection Direction);
447 
448   /// Find llvm::Values referenced in GPU kernel.
449   ///
450   /// @param Kernel The kernel to scan for llvm::Values
451   ///
452   /// @returns A tuple, whose:
453   ///          - First element contains the set of values referenced by the
454   ///            kernel
455   ///          - Second element contains the set of functions referenced by the
456   ///             kernel. All functions in the set satisfy
457   ///             `isValidFunctionInKernel`.
458   ///          - Third element contains loops that have induction variables
459   ///            which are used in the kernel, *and* these loops are *neither*
460   ///            in the scop, nor do they immediately surroung the Scop.
461   ///            See [Code generation of induction variables of loops outside
462   ///            Scops]
463   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
464              isl::space>
465   getReferencesInKernel(ppcg_kernel *Kernel);
466 
467   /// Compute the sizes of the execution grid for a given kernel.
468   ///
469   /// @param Kernel The kernel to compute grid sizes for.
470   ///
471   /// @returns A tuple with grid sizes for X and Y dimension
472   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
473 
474   /// Get the managed array pointer for sending host pointers to the device.
475   /// \note
476   /// This is to be used only with managed memory
477   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
478 
479   /// Compute the sizes of the thread blocks for a given kernel.
480   ///
481   /// @param Kernel The kernel to compute thread block sizes for.
482   ///
483   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
484   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
485 
486   /// Store a specific kernel launch parameter in the array of kernel launch
487   /// parameters.
488   ///
489   /// @param ArrayTy    Array type of \p Parameters.
490   /// @param Parameters The list of parameters in which to store.
491   /// @param Param      The kernel launch parameter to store.
492   /// @param Index      The index in the parameter list, at which to store the
493   ///                   parameter.
494   void insertStoreParameter(Type *ArrayTy, Instruction *Parameters,
495                             Instruction *Param, int Index);
496 
497   /// Create kernel launch parameters.
498   ///
499   /// @param Kernel        The kernel to create parameters for.
500   /// @param F             The kernel function that has been created.
501   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
502   ///
503   /// @returns A stack allocated array with pointers to the parameter
504   ///          values that are passed to the kernel.
505   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
506                                 SetVector<Value *> SubtreeValues);
507 
508   /// Create declarations for kernel variable.
509   ///
510   /// This includes shared memory declarations.
511   ///
512   /// @param Kernel        The kernel definition to create variables for.
513   /// @param FN            The function into which to generate the variables.
514   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
515 
516   /// Add CUDA annotations to module.
517   ///
518   /// Add a set of CUDA annotations that declares the maximal block dimensions
519   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
520   /// PTX compiler to bound the number of allocated registers to ensure the
521   /// resulting kernel is known to run with up to as many block dimensions
522   /// as specified here.
523   ///
524   /// @param M         The module to add the annotations to.
525   /// @param BlockDimX The size of block dimension X.
526   /// @param BlockDimY The size of block dimension Y.
527   /// @param BlockDimZ The size of block dimension Z.
528   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
529                           Value *BlockDimZ);
530 
531   /// Create GPU kernel.
532   ///
533   /// Code generate the kernel described by @p KernelStmt.
534   ///
535   /// @param KernelStmt The ast node to generate kernel code for.
536   void createKernel(__isl_take isl_ast_node *KernelStmt);
537 
538   /// Generate code that computes the size of an array.
539   ///
540   /// @param Array The array for which to compute a size.
541   Value *getArraySize(gpu_array_info *Array);
542 
543   /// Generate code to compute the minimal offset at which an array is accessed.
544   ///
545   /// The offset of an array is the minimal array location accessed in a scop.
546   ///
547   /// Example:
548   ///
549   ///   for (long i = 0; i < 100; i++)
550   ///     A[i + 42] += ...
551   ///
552   ///   getArrayOffset(A) results in 42.
553   ///
554   /// @param Array The array for which to compute the offset.
555   /// @returns An llvm::Value that contains the offset of the array.
556   Value *getArrayOffset(gpu_array_info *Array);
557 
558   /// Prepare the kernel arguments for kernel code generation
559   ///
560   /// @param Kernel The kernel to generate code for.
561   /// @param FN     The function created for the kernel.
562   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
563 
564   /// Create kernel function.
565   ///
566   /// Create a kernel function located in a newly created module that can serve
567   /// as target for device code generation. Set the Builder to point to the
568   /// start block of this newly created function.
569   ///
570   /// @param Kernel The kernel to generate code for.
571   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
572   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
573   ///                         kernel.
574   void createKernelFunction(ppcg_kernel *Kernel,
575                             SetVector<Value *> &SubtreeValues,
576                             SetVector<Function *> &SubtreeFunctions);
577 
578   /// Create the declaration of a kernel function.
579   ///
580   /// The kernel function takes as arguments:
581   ///
582   ///   - One i8 pointer for each external array reference used in the kernel.
583   ///   - Host iterators
584   ///   - Parameters
585   ///   - Other LLVM Value references (TODO)
586   ///
587   /// @param Kernel The kernel to generate the function declaration for.
588   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
589   ///
590   /// @returns The newly declared function.
591   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
592                                      SetVector<Value *> &SubtreeValues);
593 
594   /// Insert intrinsic functions to obtain thread and block ids.
595   ///
596   /// @param The kernel to generate the intrinsic functions for.
597   void insertKernelIntrinsics(ppcg_kernel *Kernel);
598 
599   /// Insert function calls to retrieve the SPIR group/local ids.
600   ///
601   /// @param Kernel The kernel to generate the function calls for.
602   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
603   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
604 
605   /// Setup the creation of functions referenced by the GPU kernel.
606   ///
607   /// 1. Create new function declarations in GPUModule which are the same as
608   /// SubtreeFunctions.
609   ///
610   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
611   /// old functions (that come from the original module) to new functions
612   /// (that are created within GPUModule). That way, we generate references
613   /// to the correct function (in GPUModule) in BlockGenerator.
614   ///
615   /// @see IslNodeBuilder::ValueMap
616   /// @see BlockGenerator::GlobalMap
617   /// @see BlockGenerator::getNewValue
618   /// @see GPUNodeBuilder::getReferencesInKernel.
619   ///
620   /// @param SubtreeFunctions The set of llvm::Functions referenced by
621   ///                         this kernel.
622   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
623 
624   /// Create a global-to-shared or shared-to-global copy statement.
625   ///
626   /// @param CopyStmt The copy statement to generate code for
627   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
628 
629   /// Create code for a ScopStmt called in @p Expr.
630   ///
631   /// @param Expr The expression containing the call.
632   /// @param KernelStmt The kernel statement referenced in the call.
633   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
634 
635   /// Create an in-kernel synchronization call.
636   void createKernelSync();
637 
638   /// Create a PTX assembly string for the current GPU kernel.
639   ///
640   /// @returns A string containing the corresponding PTX assembly code.
641   std::string createKernelASM();
642 
643   /// Remove references from the dominator tree to the kernel function @p F.
644   ///
645   /// @param F The function to remove references to.
646   void clearDominators(Function *F);
647 
648   /// Remove references from scalar evolution to the kernel function @p F.
649   ///
650   /// @param F The function to remove references to.
651   void clearScalarEvolution(Function *F);
652 
653   /// Remove references from loop info to the kernel function @p F.
654   ///
655   /// @param F The function to remove references to.
656   void clearLoops(Function *F);
657 
658   /// Check if the scop requires to be linked with CUDA's libdevice.
659   bool requiresCUDALibDevice();
660 
661   /// Link with the NVIDIA libdevice library (if needed and available).
662   void addCUDALibDevice();
663 
664   /// Finalize the generation of the kernel function.
665   ///
666   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
667   /// dump its IR to stderr.
668   ///
669   /// @returns The Assembly string of the kernel.
670   std::string finalizeKernelFunction();
671 
672   /// Finalize the generation of the kernel arguments.
673   ///
674   /// This function ensures that not-read-only scalars used in a kernel are
675   /// stored back to the global memory location they are backed with before
676   /// the kernel terminates.
677   ///
678   /// @params Kernel The kernel to finalize kernel arguments for.
679   void finalizeKernelArguments(ppcg_kernel *Kernel);
680 
681   /// Create code that allocates memory to store arrays on device.
682   void allocateDeviceArrays();
683 
684   /// Create code to prepare the managed device pointers.
685   void prepareManagedDeviceArrays();
686 
687   /// Free all allocated device arrays.
688   void freeDeviceArrays();
689 
690   /// Create a call to initialize the GPU context.
691   ///
692   /// @returns A pointer to the newly initialized context.
693   Value *createCallInitContext();
694 
695   /// Create a call to get the device pointer for a kernel allocation.
696   ///
697   /// @param Allocation The Polly GPU allocation
698   ///
699   /// @returns The device parameter corresponding to this allocation.
700   Value *createCallGetDevicePtr(Value *Allocation);
701 
702   /// Create a call to free the GPU context.
703   ///
704   /// @param Context A pointer to an initialized GPU context.
705   void createCallFreeContext(Value *Context);
706 
707   /// Create a call to allocate memory on the device.
708   ///
709   /// @param Size The size of memory to allocate
710   ///
711   /// @returns A pointer that identifies this allocation.
712   Value *createCallAllocateMemoryForDevice(Value *Size);
713 
714   /// Create a call to free a device array.
715   ///
716   /// @param Array The device array to free.
717   void createCallFreeDeviceMemory(Value *Array);
718 
719   /// Create a call to copy data from host to device.
720   ///
721   /// @param HostPtr A pointer to the host data that should be copied.
722   /// @param DevicePtr A device pointer specifying the location to copy to.
723   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
724                                       Value *Size);
725 
726   /// Create a call to copy data from device to host.
727   ///
728   /// @param DevicePtr A pointer to the device data that should be copied.
729   /// @param HostPtr A host pointer specifying the location to copy to.
730   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
731                                       Value *Size);
732 
733   /// Create a call to synchronize Host & Device.
734   /// \note
735   /// This is to be used only with managed memory.
736   void createCallSynchronizeDevice();
737 
738   /// Create a call to get a kernel from an assembly string.
739   ///
740   /// @param Buffer The string describing the kernel.
741   /// @param Entry  The name of the kernel function to call.
742   ///
743   /// @returns A pointer to a kernel object
744   Value *createCallGetKernel(Value *Buffer, Value *Entry);
745 
746   /// Create a call to free a GPU kernel.
747   ///
748   /// @param GPUKernel THe kernel to free.
749   void createCallFreeKernel(Value *GPUKernel);
750 
751   /// Create a call to launch a GPU kernel.
752   ///
753   /// @param GPUKernel  The kernel to launch.
754   /// @param GridDimX   The size of the first grid dimension.
755   /// @param GridDimY   The size of the second grid dimension.
756   /// @param GridBlockX The size of the first block dimension.
757   /// @param GridBlockY The size of the second block dimension.
758   /// @param GridBlockZ The size of the third block dimension.
759   /// @param Parameters A pointer to an array that contains itself pointers to
760   ///                   the parameter values passed for each kernel argument.
761   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
762                               Value *GridDimY, Value *BlockDimX,
763                               Value *BlockDimY, Value *BlockDimZ,
764                               Value *Parameters);
765 };
766 
767 std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
768   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
769          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
770 }
771 
772 void GPUNodeBuilder::initializeAfterRTH() {
773   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
774                                  &*Builder.GetInsertPoint(), &DT, &LI);
775   NewBB->setName("polly.acc.initialize");
776   Builder.SetInsertPoint(&NewBB->front());
777 
778   GPUContext = createCallInitContext();
779 
780   if (!PollyManagedMemory)
781     allocateDeviceArrays();
782   else
783     prepareManagedDeviceArrays();
784 }
785 
786 void GPUNodeBuilder::finalize() {
787   if (!PollyManagedMemory)
788     freeDeviceArrays();
789 
790   createCallFreeContext(GPUContext);
791   IslNodeBuilder::finalize();
792 }
793 
794 void GPUNodeBuilder::allocateDeviceArrays() {
795   assert(!PollyManagedMemory &&
796          "Managed memory will directly send host pointers "
797          "to the kernel. There is no need for device arrays");
798   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
799 
800   for (int i = 0; i < Prog->n_array; ++i) {
801     gpu_array_info *Array = &Prog->array[i];
802     auto *ScopArray = (ScopArrayInfo *)Array->user;
803     std::string DevArrayName("p_dev_array_");
804     DevArrayName.append(Array->name);
805 
806     Value *ArraySize = getArraySize(Array);
807     Value *Offset = getArrayOffset(Array);
808     if (Offset)
809       ArraySize = Builder.CreateSub(
810           ArraySize,
811           Builder.CreateMul(Offset,
812                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
813     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
814     // It makes no sense to have an array of size 0. The CUDA API will
815     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
816     // choose to be defensive and catch this at the compile phase. It is
817     // most likely that we are doing something wrong with size computation.
818     if (SizeSCEV->isZero()) {
819       errs() << getUniqueScopName(&S)
820              << " has computed array size 0: " << *ArraySize
821              << " | for array: " << *(ScopArray->getBasePtr())
822              << ". This is illegal, exiting.\n";
823       report_fatal_error("array size was computed to be 0");
824     }
825 
826     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
827     DevArray->setName(DevArrayName);
828     DeviceAllocations[ScopArray] = DevArray;
829   }
830 
831   isl_ast_build_free(Build);
832 }
833 
834 void GPUNodeBuilder::prepareManagedDeviceArrays() {
835   assert(PollyManagedMemory &&
836          "Device array most only be prepared in managed-memory mode");
837   for (int i = 0; i < Prog->n_array; ++i) {
838     gpu_array_info *Array = &Prog->array[i];
839     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
840     Value *HostPtr;
841 
842     if (gpu_array_is_scalar(Array))
843       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
844     else
845       HostPtr = ScopArray->getBasePtr();
846     HostPtr = getLatestValue(HostPtr);
847 
848     Value *Offset = getArrayOffset(Array);
849     if (Offset) {
850       HostPtr = Builder.CreatePointerCast(
851           HostPtr, ScopArray->getElementType()->getPointerTo());
852       HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
853     }
854 
855     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
856     DeviceAllocations[ScopArray] = HostPtr;
857   }
858 }
859 
860 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
861                                         Value *BlockDimY, Value *BlockDimZ) {
862   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
863 
864   for (auto &F : *M) {
865     if (F.getCallingConv() != CallingConv::PTX_Kernel)
866       continue;
867 
868     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
869 
870     Metadata *Elements[] = {
871         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
872         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
873         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
874         ValueAsMetadata::get(V[2]),
875     };
876     MDNode *Node = MDNode::get(M->getContext(), Elements);
877     AnnotationNode->addOperand(Node);
878   }
879 }
880 
881 void GPUNodeBuilder::freeDeviceArrays() {
882   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
883   for (auto &Array : DeviceAllocations)
884     createCallFreeDeviceMemory(Array.second);
885 }
886 
887 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
888   const char *Name = "polly_getKernel";
889   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
890   Function *F = M->getFunction(Name);
891 
892   // If F is not available, declare it.
893   if (!F) {
894     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
895     std::vector<Type *> Args;
896     Args.push_back(Builder.getInt8PtrTy());
897     Args.push_back(Builder.getInt8PtrTy());
898     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
899     F = Function::Create(Ty, Linkage, Name, M);
900   }
901 
902   return Builder.CreateCall(F, {Buffer, Entry});
903 }
904 
905 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
906   const char *Name = "polly_getDevicePtr";
907   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
908   Function *F = M->getFunction(Name);
909 
910   // If F is not available, declare it.
911   if (!F) {
912     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
913     std::vector<Type *> Args;
914     Args.push_back(Builder.getInt8PtrTy());
915     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
916     F = Function::Create(Ty, Linkage, Name, M);
917   }
918 
919   return Builder.CreateCall(F, {Allocation});
920 }
921 
922 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
923                                             Value *GridDimY, Value *BlockDimX,
924                                             Value *BlockDimY, Value *BlockDimZ,
925                                             Value *Parameters) {
926   const char *Name = "polly_launchKernel";
927   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
928   Function *F = M->getFunction(Name);
929 
930   // If F is not available, declare it.
931   if (!F) {
932     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
933     std::vector<Type *> Args;
934     Args.push_back(Builder.getInt8PtrTy());
935     Args.push_back(Builder.getInt32Ty());
936     Args.push_back(Builder.getInt32Ty());
937     Args.push_back(Builder.getInt32Ty());
938     Args.push_back(Builder.getInt32Ty());
939     Args.push_back(Builder.getInt32Ty());
940     Args.push_back(Builder.getInt8PtrTy());
941     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
942     F = Function::Create(Ty, Linkage, Name, M);
943   }
944 
945   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
946                          BlockDimZ, Parameters});
947 }
948 
949 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
950   const char *Name = "polly_freeKernel";
951   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
952   Function *F = M->getFunction(Name);
953 
954   // If F is not available, declare it.
955   if (!F) {
956     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
957     std::vector<Type *> Args;
958     Args.push_back(Builder.getInt8PtrTy());
959     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
960     F = Function::Create(Ty, Linkage, Name, M);
961   }
962 
963   Builder.CreateCall(F, {GPUKernel});
964 }
965 
966 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
967   assert(!PollyManagedMemory &&
968          "Managed memory does not allocate or free memory "
969          "for device");
970   const char *Name = "polly_freeDeviceMemory";
971   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
972   Function *F = M->getFunction(Name);
973 
974   // If F is not available, declare it.
975   if (!F) {
976     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
977     std::vector<Type *> Args;
978     Args.push_back(Builder.getInt8PtrTy());
979     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
980     F = Function::Create(Ty, Linkage, Name, M);
981   }
982 
983   Builder.CreateCall(F, {Array});
984 }
985 
986 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
987   assert(!PollyManagedMemory &&
988          "Managed memory does not allocate or free memory "
989          "for device");
990   const char *Name = "polly_allocateMemoryForDevice";
991   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
992   Function *F = M->getFunction(Name);
993 
994   // If F is not available, declare it.
995   if (!F) {
996     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
997     std::vector<Type *> Args;
998     Args.push_back(Builder.getInt64Ty());
999     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1000     F = Function::Create(Ty, Linkage, Name, M);
1001   }
1002 
1003   return Builder.CreateCall(F, {Size});
1004 }
1005 
1006 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
1007                                                     Value *DeviceData,
1008                                                     Value *Size) {
1009   assert(!PollyManagedMemory &&
1010          "Managed memory does not transfer memory between "
1011          "device and host");
1012   const char *Name = "polly_copyFromHostToDevice";
1013   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1014   Function *F = M->getFunction(Name);
1015 
1016   // If F is not available, declare it.
1017   if (!F) {
1018     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1019     std::vector<Type *> Args;
1020     Args.push_back(Builder.getInt8PtrTy());
1021     Args.push_back(Builder.getInt8PtrTy());
1022     Args.push_back(Builder.getInt64Ty());
1023     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1024     F = Function::Create(Ty, Linkage, Name, M);
1025   }
1026 
1027   Builder.CreateCall(F, {HostData, DeviceData, Size});
1028 }
1029 
1030 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
1031                                                     Value *HostData,
1032                                                     Value *Size) {
1033   assert(!PollyManagedMemory &&
1034          "Managed memory does not transfer memory between "
1035          "device and host");
1036   const char *Name = "polly_copyFromDeviceToHost";
1037   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1038   Function *F = M->getFunction(Name);
1039 
1040   // If F is not available, declare it.
1041   if (!F) {
1042     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1043     std::vector<Type *> Args;
1044     Args.push_back(Builder.getInt8PtrTy());
1045     Args.push_back(Builder.getInt8PtrTy());
1046     Args.push_back(Builder.getInt64Ty());
1047     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1048     F = Function::Create(Ty, Linkage, Name, M);
1049   }
1050 
1051   Builder.CreateCall(F, {DeviceData, HostData, Size});
1052 }
1053 
1054 void GPUNodeBuilder::createCallSynchronizeDevice() {
1055   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1056                                "managed memory");
1057   const char *Name = "polly_synchronizeDevice";
1058   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1059   Function *F = M->getFunction(Name);
1060 
1061   // If F is not available, declare it.
1062   if (!F) {
1063     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1064     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1065     F = Function::Create(Ty, Linkage, Name, M);
1066   }
1067 
1068   Builder.CreateCall(F);
1069 }
1070 
1071 Value *GPUNodeBuilder::createCallInitContext() {
1072   const char *Name;
1073 
1074   switch (Runtime) {
1075   case GPURuntime::CUDA:
1076     Name = "polly_initContextCUDA";
1077     break;
1078   case GPURuntime::OpenCL:
1079     Name = "polly_initContextCL";
1080     break;
1081   }
1082 
1083   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1084   Function *F = M->getFunction(Name);
1085 
1086   // If F is not available, declare it.
1087   if (!F) {
1088     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1089     std::vector<Type *> Args;
1090     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1091     F = Function::Create(Ty, Linkage, Name, M);
1092   }
1093 
1094   return Builder.CreateCall(F, {});
1095 }
1096 
1097 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1098   const char *Name = "polly_freeContext";
1099   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1100   Function *F = M->getFunction(Name);
1101 
1102   // If F is not available, declare it.
1103   if (!F) {
1104     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1105     std::vector<Type *> Args;
1106     Args.push_back(Builder.getInt8PtrTy());
1107     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1108     F = Function::Create(Ty, Linkage, Name, M);
1109   }
1110 
1111   Builder.CreateCall(F, {Context});
1112 }
1113 
1114 /// Check if one string is a prefix of another.
1115 ///
1116 /// @param String The string in which to look for the prefix.
1117 /// @param Prefix The prefix to look for.
1118 static bool isPrefix(std::string String, std::string Prefix) {
1119   return String.find(Prefix) == 0;
1120 }
1121 
1122 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1123   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1124   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
1125 
1126   if (!gpu_array_is_scalar(Array)) {
1127     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1128 
1129     isl::pw_aff OffsetDimZero = ArrayBound.at(0);
1130     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
1131 
1132     for (unsigned int i = 1; i < Array->n_index; i++) {
1133       isl::pw_aff Bound_I = ArrayBound.at(i);
1134       isl::ast_expr Expr = Build.expr_from(Bound_I);
1135       Res = Res.mul(Expr);
1136     }
1137 
1138     Value *NumElements = ExprBuilder.create(Res.release());
1139     if (NumElements->getType() != ArraySize->getType())
1140       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
1141     ArraySize = Builder.CreateMul(ArraySize, NumElements);
1142   }
1143   return ArraySize;
1144 }
1145 
1146 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1147   if (gpu_array_is_scalar(Array))
1148     return nullptr;
1149 
1150   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1151 
1152   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1153 
1154   isl::set ZeroSet = isl::set::universe(Min.get_space());
1155 
1156   for (unsigned i : rangeIslSize(0, Min.tuple_dim()))
1157     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1158 
1159   if (Min.is_subset(ZeroSet)) {
1160     return nullptr;
1161   }
1162 
1163   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.ctx(), 0));
1164 
1165   for (unsigned i : rangeIslSize(0, Min.tuple_dim())) {
1166     if (i > 0) {
1167       isl::pw_aff Bound_I =
1168           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1169       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1170       Result = Result.mul(BExpr);
1171     }
1172     isl::pw_aff DimMin = Min.dim_min(i);
1173     isl::ast_expr MExpr = Build.expr_from(DimMin);
1174     Result = Result.add(MExpr);
1175   }
1176 
1177   return ExprBuilder.create(Result.release());
1178 }
1179 
1180 Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1181                                              ScopArrayInfo *ArrayInfo) {
1182   assert(PollyManagedMemory && "Only used when you wish to get a host "
1183                                "pointer for sending data to the kernel, "
1184                                "with managed memory");
1185   std::map<ScopArrayInfo *, Value *>::iterator it;
1186   it = DeviceAllocations.find(ArrayInfo);
1187   assert(it != DeviceAllocations.end() &&
1188          "Device array expected to be available");
1189   return it->second;
1190 }
1191 
1192 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
1193                                         enum DataDirection Direction) {
1194   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
1195   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
1196   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
1197   isl_id *Id = isl_ast_expr_get_id(Arg);
1198   auto Array = (gpu_array_info *)isl_id_get_user(Id);
1199   auto ScopArray = (ScopArrayInfo *)(Array->user);
1200 
1201   Value *Size = getArraySize(Array);
1202   Value *Offset = getArrayOffset(Array);
1203   Value *DevPtr = DeviceAllocations[ScopArray];
1204 
1205   Value *HostPtr;
1206 
1207   if (gpu_array_is_scalar(Array))
1208     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1209   else
1210     HostPtr = ScopArray->getBasePtr();
1211   HostPtr = getLatestValue(HostPtr);
1212 
1213   if (Offset) {
1214     HostPtr = Builder.CreatePointerCast(
1215         HostPtr, ScopArray->getElementType()->getPointerTo());
1216     HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
1217   }
1218 
1219   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1220 
1221   if (Offset) {
1222     Size = Builder.CreateSub(
1223         Size, Builder.CreateMul(
1224                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1225   }
1226 
1227   if (Direction == HOST_TO_DEVICE)
1228     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
1229   else
1230     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
1231 
1232   isl_id_free(Id);
1233   isl_ast_expr_free(Arg);
1234   isl_ast_expr_free(Expr);
1235   isl_ast_node_free(TransferStmt);
1236 }
1237 
1238 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
1239   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
1240   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1241   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1242   isl_id_free(Id);
1243   isl_ast_expr_free(StmtExpr);
1244 
1245   const char *Str = isl_id_get_name(Id);
1246   if (!strcmp(Str, "kernel")) {
1247     createKernel(UserStmt);
1248     if (PollyManagedMemory)
1249       createCallSynchronizeDevice();
1250     isl_ast_expr_free(Expr);
1251     return;
1252   }
1253   if (!strcmp(Str, "init_device")) {
1254     initializeAfterRTH();
1255     isl_ast_node_free(UserStmt);
1256     isl_ast_expr_free(Expr);
1257     return;
1258   }
1259   if (!strcmp(Str, "clear_device")) {
1260     finalize();
1261     isl_ast_node_free(UserStmt);
1262     isl_ast_expr_free(Expr);
1263     return;
1264   }
1265   if (isPrefix(Str, "to_device")) {
1266     if (!PollyManagedMemory)
1267       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1268     else
1269       isl_ast_node_free(UserStmt);
1270 
1271     isl_ast_expr_free(Expr);
1272     return;
1273   }
1274 
1275   if (isPrefix(Str, "from_device")) {
1276     if (!PollyManagedMemory) {
1277       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1278     } else {
1279       isl_ast_node_free(UserStmt);
1280     }
1281     isl_ast_expr_free(Expr);
1282     return;
1283   }
1284 
1285   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
1286   struct ppcg_kernel_stmt *KernelStmt =
1287       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
1288   isl_id_free(Anno);
1289 
1290   switch (KernelStmt->type) {
1291   case ppcg_kernel_domain:
1292     createScopStmt(Expr, KernelStmt);
1293     isl_ast_node_free(UserStmt);
1294     return;
1295   case ppcg_kernel_copy:
1296     createKernelCopy(KernelStmt);
1297     isl_ast_expr_free(Expr);
1298     isl_ast_node_free(UserStmt);
1299     return;
1300   case ppcg_kernel_sync:
1301     createKernelSync();
1302     isl_ast_expr_free(Expr);
1303     isl_ast_node_free(UserStmt);
1304     return;
1305   }
1306 
1307   isl_ast_expr_free(Expr);
1308   isl_ast_node_free(UserStmt);
1309 }
1310 
1311 void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
1312   createForSequential(isl::manage(Node).as<isl::ast_node_for>(), false);
1313 }
1314 
1315 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1316   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1317   auto LocalAddr = ExprBuilder.createAccessAddress(LocalIndex);
1318   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1319   auto GlobalAddr = ExprBuilder.createAccessAddress(Index);
1320 
1321   if (KernelStmt->u.c.read) {
1322     LoadInst *Load =
1323         Builder.CreateLoad(GlobalAddr.second, GlobalAddr.first, "shared.read");
1324     Builder.CreateStore(Load, LocalAddr.first);
1325   } else {
1326     LoadInst *Load =
1327         Builder.CreateLoad(LocalAddr.second, LocalAddr.first, "shared.write");
1328     Builder.CreateStore(Load, GlobalAddr.first);
1329   }
1330 }
1331 
1332 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1333                                     ppcg_kernel_stmt *KernelStmt) {
1334   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1335   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1336 
1337   LoopToScevMapT LTS;
1338   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1339 
1340   createSubstitutions(Expr, Stmt, LTS);
1341 
1342   if (Stmt->isBlockStmt())
1343     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1344   else
1345     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1346 }
1347 
1348 void GPUNodeBuilder::createKernelSync() {
1349   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1350   const char *SpirName = "__gen_ocl_barrier_global";
1351 
1352   Function *Sync;
1353 
1354   switch (Arch) {
1355   case GPUArch::SPIR64:
1356   case GPUArch::SPIR32:
1357     Sync = M->getFunction(SpirName);
1358 
1359     // If Sync is not available, declare it.
1360     if (!Sync) {
1361       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1362       std::vector<Type *> Args;
1363       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1364       Sync = Function::Create(Ty, Linkage, SpirName, M);
1365       Sync->setCallingConv(CallingConv::SPIR_FUNC);
1366     }
1367     break;
1368   case GPUArch::NVPTX64:
1369     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
1370     break;
1371   }
1372 
1373   Builder.CreateCall(Sync, {});
1374 }
1375 
1376 /// Collect llvm::Values referenced from @p Node
1377 ///
1378 /// This function only applies to isl_ast_nodes that are user_nodes referring
1379 /// to a ScopStmt. All other node types are ignore.
1380 ///
1381 /// @param Node The node to collect references for.
1382 /// @param User A user pointer used as storage for the data that is collected.
1383 ///
1384 /// @returns isl_bool_true if data could be collected successfully.
1385 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1386   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1387     return isl_bool_true;
1388 
1389   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1390   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1391   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1392   const char *Str = isl_id_get_name(Id);
1393   isl_id_free(Id);
1394   isl_ast_expr_free(StmtExpr);
1395   isl_ast_expr_free(Expr);
1396 
1397   if (!isPrefix(Str, "Stmt"))
1398     return isl_bool_true;
1399 
1400   Id = isl_ast_node_get_annotation(Node);
1401   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1402   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1403   isl_id_free(Id);
1404 
1405   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1406 
1407   return isl_bool_true;
1408 }
1409 
1410 /// A list of functions that are available in NVIDIA's libdevice.
1411 const std::set<std::string> CUDALibDeviceFunctions = {
1412     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
1413     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
1414 
1415 // A map from intrinsics to their corresponding libdevice functions.
1416 const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
1417     {"llvm.exp.f64", "exp"},
1418     {"llvm.exp.f32", "expf"},
1419     {"llvm.powi.f64.i32", "powi"},
1420     {"llvm.powi.f32.i32", "powif"}};
1421 
1422 /// Return the corresponding CUDA libdevice function name @p Name.
1423 /// Note that this function will try to convert instrinsics in the list
1424 /// IntrinsicToLibdeviceFunc into libdevice functions.
1425 /// This is because some intrinsics such as `exp`
1426 /// are not supported by the NVPTX backend.
1427 /// If this restriction of the backend is lifted, we should refactor our code
1428 /// so that we use intrinsics whenever possible.
1429 ///
1430 /// Return "" if we are not compiling for CUDA.
1431 std::string getCUDALibDeviceFuntion(StringRef NameRef) {
1432   std::string Name = NameRef.str();
1433   auto It = IntrinsicToLibdeviceFunc.find(Name);
1434   if (It != IntrinsicToLibdeviceFunc.end())
1435     return getCUDALibDeviceFuntion(It->second);
1436 
1437   if (CUDALibDeviceFunctions.count(Name))
1438     return ("__nv_" + Name);
1439 
1440   return "";
1441 }
1442 
1443 /// Check if F is a function that we can code-generate in a GPU kernel.
1444 static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1445   assert(F && "F is an invalid pointer");
1446   // We string compare against the name of the function to allow
1447   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
1448   // "llvm.copysign".
1449   const StringRef Name = F->getName();
1450 
1451   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
1452     return true;
1453 
1454   return F->isIntrinsic() &&
1455          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
1456           Name.startswith("llvm.copysign"));
1457 }
1458 
1459 /// Do not take `Function` as a subtree value.
1460 ///
1461 /// We try to take the reference of all subtree values and pass them along
1462 /// to the kernel from the host. Taking an address of any function and
1463 /// trying to pass along is nonsensical. Only allow `Value`s that are not
1464 /// `Function`s.
1465 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1466 
1467 /// Return `Function`s from `RawSubtreeValues`.
1468 static SetVector<Function *>
1469 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
1470                                  bool AllowCUDALibDevice) {
1471   SetVector<Function *> SubtreeFunctions;
1472   for (Value *It : RawSubtreeValues) {
1473     Function *F = dyn_cast<Function>(It);
1474     if (F) {
1475       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
1476              "Code should have bailed out by "
1477              "this point if an invalid function "
1478              "were present in a kernel.");
1479       SubtreeFunctions.insert(F);
1480     }
1481   }
1482   return SubtreeFunctions;
1483 }
1484 
1485 std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
1486            isl::space>
1487 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1488   SetVector<Value *> SubtreeValues;
1489   SetVector<const SCEV *> SCEVs;
1490   SetVector<const Loop *> Loops;
1491   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1492   SubtreeReferences References = {
1493       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
1494       &ParamSpace};
1495 
1496   for (const auto &I : IDToValue)
1497     SubtreeValues.insert(I.second);
1498 
1499   // NOTE: this is populated in IslNodeBuilder::addParameters
1500   // See [Code generation of induction variables of loops outside Scops].
1501   for (const auto &I : OutsideLoopIterations)
1502     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1503 
1504   isl_ast_node_foreach_descendant_top_down(
1505       Kernel->tree, collectReferencesInGPUStmt, &References);
1506 
1507   for (const SCEV *Expr : SCEVs) {
1508     findValues(Expr, SE, SubtreeValues);
1509     findLoops(Expr, Loops);
1510   }
1511 
1512   Loops.remove_if([this](const Loop *L) {
1513     return S.contains(L) || L->contains(S.getEntry());
1514   });
1515 
1516   for (auto &SAI : S.arrays())
1517     SubtreeValues.remove(SAI->getBasePtr());
1518 
1519   isl_space *Space = S.getParamSpace().release();
1520   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1521     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1522     assert(IDToValue.count(Id));
1523     Value *Val = IDToValue[Id];
1524     SubtreeValues.remove(Val);
1525     isl_id_free(Id);
1526   }
1527   isl_space_free(Space);
1528 
1529   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1530     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1531     assert(IDToValue.count(Id));
1532     Value *Val = IDToValue[Id];
1533     SubtreeValues.remove(Val);
1534     isl_id_free(Id);
1535   }
1536 
1537   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1538   // SubtreeValues. This is important, because we should not lose any
1539   // SubtreeValues in the process of constructing the
1540   // "ValidSubtree{Values, Functions} sets. Nor should the set
1541   // ValidSubtree{Values, Functions} have any common element.
1542   auto ValidSubtreeValuesIt =
1543       make_filter_range(SubtreeValues, isValidSubtreeValue);
1544   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1545                                         ValidSubtreeValuesIt.end());
1546 
1547   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
1548 
1549   SetVector<Function *> ValidSubtreeFunctions(
1550       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1551 
1552   // @see IslNodeBuilder::getReferencesInSubtree
1553   SetVector<Value *> ReplacedValues;
1554   for (Value *V : ValidSubtreeValues) {
1555     auto It = ValueMap.find(V);
1556     if (It == ValueMap.end())
1557       ReplacedValues.insert(V);
1558     else
1559       ReplacedValues.insert(It->second);
1560   }
1561   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
1562                          ParamSpace);
1563 }
1564 
1565 void GPUNodeBuilder::clearDominators(Function *F) {
1566   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
1567   std::vector<BasicBlock *> Nodes;
1568   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
1569     Nodes.push_back(I->getBlock());
1570 
1571   for (BasicBlock *BB : Nodes)
1572     DT.eraseNode(BB);
1573 }
1574 
1575 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
1576   for (BasicBlock &BB : *F) {
1577     Loop *L = LI.getLoopFor(&BB);
1578     if (L)
1579       SE.forgetLoop(L);
1580   }
1581 }
1582 
1583 void GPUNodeBuilder::clearLoops(Function *F) {
1584   SmallSet<Loop *, 1> WorkList;
1585   for (BasicBlock &BB : *F) {
1586     Loop *L = LI.getLoopFor(&BB);
1587     if (L)
1588       WorkList.insert(L);
1589   }
1590   for (auto *L : WorkList)
1591     LI.erase(L);
1592 }
1593 
1594 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
1595   std::vector<Value *> Sizes;
1596   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
1597 
1598   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
1599   for (long i = 0; i < Kernel->n_grid; i++) {
1600     isl::pw_aff Size = GridSizePwAffs.at(i);
1601     isl::ast_expr GridSize = Context.expr_from(Size);
1602     Value *Res = ExprBuilder.create(GridSize.release());
1603     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
1604     Sizes.push_back(Res);
1605   }
1606 
1607   for (long i = Kernel->n_grid; i < 3; i++)
1608     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1609 
1610   return std::make_tuple(Sizes[0], Sizes[1]);
1611 }
1612 
1613 std::tuple<Value *, Value *, Value *>
1614 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
1615   std::vector<Value *> Sizes;
1616 
1617   for (long i = 0; i < Kernel->n_block; i++) {
1618     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
1619     Sizes.push_back(Res);
1620   }
1621 
1622   for (long i = Kernel->n_block; i < 3; i++)
1623     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1624 
1625   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
1626 }
1627 
1628 void GPUNodeBuilder::insertStoreParameter(Type *ArrayTy,
1629                                           Instruction *Parameters,
1630                                           Instruction *Param, int Index) {
1631   Value *Slot = Builder.CreateGEP(
1632       ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1633   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1634   Builder.CreateStore(ParamTyped, Slot);
1635 }
1636 
1637 Value *
1638 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
1639                                        SetVector<Value *> SubtreeValues) {
1640   const int NumArgs = F->arg_size();
1641   std::vector<int> ArgSizes(NumArgs);
1642 
1643   // If we are using the OpenCL Runtime, we need to add the kernel argument
1644   // sizes to the end of the launch-parameter list, so OpenCL can determine
1645   // how big the respective kernel arguments are.
1646   // Here we need to reserve adequate space for that.
1647   Type *ArrayTy;
1648   if (Runtime == GPURuntime::OpenCL)
1649     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
1650   else
1651     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
1652 
1653   BasicBlock *EntryBlock =
1654       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1655   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
1656   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
1657   Instruction *Parameters = new AllocaInst(
1658       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
1659 
1660   int Index = 0;
1661   for (long i = 0; i < Prog->n_array; i++) {
1662     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1663       continue;
1664 
1665     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1666     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1667 
1668     if (Runtime == GPURuntime::OpenCL)
1669       ArgSizes[Index] = SAI->getElemSizeInBytes();
1670 
1671     Value *DevArray = nullptr;
1672     if (PollyManagedMemory) {
1673       DevArray = getManagedDeviceArray(&Prog->array[i],
1674                                        const_cast<ScopArrayInfo *>(SAI));
1675     } else {
1676       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
1677       DevArray = createCallGetDevicePtr(DevArray);
1678     }
1679     assert(DevArray != nullptr && "Array to be offloaded to device not "
1680                                   "initialized");
1681     Value *Offset = getArrayOffset(&Prog->array[i]);
1682 
1683     if (Offset) {
1684       DevArray = Builder.CreatePointerCast(
1685           DevArray, SAI->getElementType()->getPointerTo());
1686       DevArray = Builder.CreateGEP(SAI->getElementType(), DevArray,
1687                                    Builder.CreateNeg(Offset));
1688       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1689     }
1690     Value *Slot = Builder.CreateGEP(
1691         ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1692 
1693     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1694       Value *ValPtr = nullptr;
1695       if (PollyManagedMemory)
1696         ValPtr = DevArray;
1697       else
1698         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1699 
1700       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1701                                   " to be stored into Parameters");
1702       Value *ValPtrCast =
1703           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1704       Builder.CreateStore(ValPtrCast, Slot);
1705     } else {
1706       Instruction *Param =
1707           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
1708                          Launch + "_param_" + std::to_string(Index),
1709                          EntryBlock->getTerminator());
1710       Builder.CreateStore(DevArray, Param);
1711       Value *ParamTyped =
1712           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1713       Builder.CreateStore(ParamTyped, Slot);
1714     }
1715     Index++;
1716   }
1717 
1718   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1719 
1720   for (long i = 0; i < NumHostIters; i++) {
1721     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1722     Value *Val = IDToValue[Id];
1723     isl_id_free(Id);
1724 
1725     if (Runtime == GPURuntime::OpenCL)
1726       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1727 
1728     Instruction *Param =
1729         new AllocaInst(Val->getType(), AddressSpace,
1730                        Launch + "_param_" + std::to_string(Index),
1731                        EntryBlock->getTerminator());
1732     Builder.CreateStore(Val, Param);
1733     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1734     Index++;
1735   }
1736 
1737   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1738 
1739   for (long i = 0; i < NumVars; i++) {
1740     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1741     Value *Val = IDToValue[Id];
1742     if (ValueMap.count(Val))
1743       Val = ValueMap[Val];
1744     isl_id_free(Id);
1745 
1746     if (Runtime == GPURuntime::OpenCL)
1747       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1748 
1749     Instruction *Param =
1750         new AllocaInst(Val->getType(), AddressSpace,
1751                        Launch + "_param_" + std::to_string(Index),
1752                        EntryBlock->getTerminator());
1753     Builder.CreateStore(Val, Param);
1754     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1755     Index++;
1756   }
1757 
1758   for (auto Val : SubtreeValues) {
1759     if (Runtime == GPURuntime::OpenCL)
1760       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1761 
1762     Instruction *Param =
1763         new AllocaInst(Val->getType(), AddressSpace,
1764                        Launch + "_param_" + std::to_string(Index),
1765                        EntryBlock->getTerminator());
1766     Builder.CreateStore(Val, Param);
1767     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1768     Index++;
1769   }
1770 
1771   if (Runtime == GPURuntime::OpenCL) {
1772     for (int i = 0; i < NumArgs; i++) {
1773       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1774       Instruction *Param =
1775           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1776                          Launch + "_param_size_" + std::to_string(i),
1777                          EntryBlock->getTerminator());
1778       Builder.CreateStore(Val, Param);
1779       insertStoreParameter(ArrayTy, Parameters, Param, Index);
1780       Index++;
1781     }
1782   }
1783 
1784   auto Location = EntryBlock->getTerminator();
1785   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1786                          Launch + "_params_i8ptr", Location);
1787 }
1788 
1789 void GPUNodeBuilder::setupKernelSubtreeFunctions(
1790     SetVector<Function *> SubtreeFunctions) {
1791   for (auto Fn : SubtreeFunctions) {
1792     const std::string ClonedFnName = Fn->getName().str();
1793     Function *Clone = GPUModule->getFunction(ClonedFnName);
1794     if (!Clone)
1795       Clone =
1796           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1797                            ClonedFnName, GPUModule.get());
1798     assert(Clone && "Expected cloned function to be initialized.");
1799     assert(ValueMap.find(Fn) == ValueMap.end() &&
1800            "Fn already present in ValueMap");
1801     ValueMap[Fn] = Clone;
1802   }
1803 }
1804 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1805   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1806   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1807   isl_id_free(Id);
1808   isl_ast_node_free(KernelStmt);
1809 
1810   if (Kernel->n_grid > 1)
1811     DeepestParallel = std::max(
1812         DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1813   else
1814     DeepestSequential = std::max(
1815         DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1816 
1817   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1818   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1819 
1820   SetVector<Value *> SubtreeValues;
1821   SetVector<Function *> SubtreeFunctions;
1822   SetVector<const Loop *> Loops;
1823   isl::space ParamSpace;
1824   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1825       getReferencesInKernel(Kernel);
1826 
1827   // Add parameters that appear only in the access function to the kernel
1828   // space. This is important to make sure that all isl_ids are passed as
1829   // parameters to the kernel, even though we may not have all parameters
1830   // in the context to improve compile time.
1831   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
1832 
1833   assert(Kernel->tree && "Device AST of kernel node is empty");
1834 
1835   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1836   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1837   ValueMapT HostValueMap = ValueMap;
1838   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1839   ScalarMap.clear();
1840   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1841   EscapeMap.clear();
1842 
1843   // Create for all loops we depend on values that contain the current loop
1844   // iteration. These values are necessary to generate code for SCEVs that
1845   // depend on such loops. As a result we need to pass them to the subfunction.
1846   for (const Loop *L : Loops) {
1847     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1848                                             SE.getUnknown(Builder.getInt64(1)),
1849                                             L, SCEV::FlagAnyWrap);
1850     Value *V = generateSCEV(OuterLIV);
1851     OutsideLoopIterations[L] = SE.getUnknown(V);
1852     SubtreeValues.insert(V);
1853   }
1854 
1855   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1856   setupKernelSubtreeFunctions(SubtreeFunctions);
1857 
1858   create(isl_ast_node_copy(Kernel->tree));
1859 
1860   finalizeKernelArguments(Kernel);
1861   Function *F = Builder.GetInsertBlock()->getParent();
1862   if (Arch == GPUArch::NVPTX64)
1863     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1864   clearDominators(F);
1865   clearScalarEvolution(F);
1866   clearLoops(F);
1867 
1868   IDToValue = HostIDs;
1869 
1870   ValueMap = std::move(HostValueMap);
1871   ScalarMap = std::move(HostScalarMap);
1872   EscapeMap = std::move(HostEscapeMap);
1873   IDToSAI.clear();
1874   Annotator.resetAlternativeAliasBases();
1875   for (auto &BasePtr : LocalArrays)
1876     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
1877   LocalArrays.clear();
1878 
1879   std::string ASMString = finalizeKernelFunction();
1880   Builder.SetInsertPoint(&HostInsertPoint);
1881   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1882 
1883   std::string Name = getKernelFuncName(Kernel->id);
1884   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1885   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1886   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1887 
1888   Value *GridDimX, *GridDimY;
1889   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1890 
1891   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1892                          BlockDimZ, Parameters);
1893   createCallFreeKernel(GPUKernel);
1894 
1895   for (auto Id : KernelIds)
1896     isl_id_free(Id);
1897 
1898   KernelIds.clear();
1899 }
1900 
1901 /// Compute the DataLayout string for the NVPTX backend.
1902 ///
1903 /// @param is64Bit Are we looking for a 64 bit architecture?
1904 static std::string computeNVPTXDataLayout(bool is64Bit) {
1905   std::string Ret = "";
1906 
1907   if (!is64Bit) {
1908     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1909            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1910            "64-v128:128:128-n16:32:64";
1911   } else {
1912     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1913            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1914            "64-v128:128:128-n16:32:64";
1915   }
1916 
1917   return Ret;
1918 }
1919 
1920 /// Compute the DataLayout string for a SPIR kernel.
1921 ///
1922 /// @param is64Bit Are we looking for a 64 bit architecture?
1923 static std::string computeSPIRDataLayout(bool is64Bit) {
1924   std::string Ret = "";
1925 
1926   if (!is64Bit) {
1927     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1928            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
1929            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
1930            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
1931   } else {
1932     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1933            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
1934            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
1935            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
1936   }
1937 
1938   return Ret;
1939 }
1940 
1941 Function *
1942 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1943                                          SetVector<Value *> &SubtreeValues) {
1944   std::vector<Type *> Args;
1945   std::string Identifier = getKernelFuncName(Kernel->id);
1946 
1947   std::vector<Metadata *> MemoryType;
1948 
1949   for (long i = 0; i < Prog->n_array; i++) {
1950     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1951       continue;
1952 
1953     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1954       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1955       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1956       Args.push_back(SAI->getElementType());
1957       MemoryType.push_back(
1958           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1959     } else {
1960       static const int UseGlobalMemory = 1;
1961       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
1962       MemoryType.push_back(
1963           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
1964     }
1965   }
1966 
1967   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1968 
1969   for (long i = 0; i < NumHostIters; i++) {
1970     Args.push_back(Builder.getInt64Ty());
1971     MemoryType.push_back(
1972         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1973   }
1974 
1975   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1976 
1977   for (long i = 0; i < NumVars; i++) {
1978     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1979     Value *Val = IDToValue[Id];
1980     isl_id_free(Id);
1981     Args.push_back(Val->getType());
1982     MemoryType.push_back(
1983         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1984   }
1985 
1986   for (auto *V : SubtreeValues) {
1987     Args.push_back(V->getType());
1988     MemoryType.push_back(
1989         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1990   }
1991 
1992   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1993   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1994                               GPUModule.get());
1995 
1996   std::vector<Metadata *> EmptyStrings;
1997 
1998   for (unsigned int i = 0; i < MemoryType.size(); i++) {
1999     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
2000   }
2001 
2002   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
2003     FN->setMetadata("kernel_arg_addr_space",
2004                     MDNode::get(FN->getContext(), MemoryType));
2005     FN->setMetadata("kernel_arg_name",
2006                     MDNode::get(FN->getContext(), EmptyStrings));
2007     FN->setMetadata("kernel_arg_access_qual",
2008                     MDNode::get(FN->getContext(), EmptyStrings));
2009     FN->setMetadata("kernel_arg_type",
2010                     MDNode::get(FN->getContext(), EmptyStrings));
2011     FN->setMetadata("kernel_arg_type_qual",
2012                     MDNode::get(FN->getContext(), EmptyStrings));
2013     FN->setMetadata("kernel_arg_base_type",
2014                     MDNode::get(FN->getContext(), EmptyStrings));
2015   }
2016 
2017   switch (Arch) {
2018   case GPUArch::NVPTX64:
2019     FN->setCallingConv(CallingConv::PTX_Kernel);
2020     break;
2021   case GPUArch::SPIR32:
2022   case GPUArch::SPIR64:
2023     FN->setCallingConv(CallingConv::SPIR_KERNEL);
2024     break;
2025   }
2026 
2027   auto Arg = FN->arg_begin();
2028   for (long i = 0; i < Kernel->n_array; i++) {
2029     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2030       continue;
2031 
2032     Arg->setName(Kernel->array[i].array->name);
2033 
2034     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2035     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2036     Type *EleTy = SAI->getElementType();
2037     Value *Val = &*Arg;
2038     SmallVector<const SCEV *, 4> Sizes;
2039     isl_ast_build *Build =
2040         isl_ast_build_from_context(isl_set_copy(Prog->context));
2041     Sizes.push_back(nullptr);
2042     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2043       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
2044           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2045       auto V = ExprBuilder.create(DimSize);
2046       Sizes.push_back(SE.getSCEV(V));
2047     }
2048     const ScopArrayInfo *SAIRep =
2049         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
2050     LocalArrays.push_back(Val);
2051 
2052     isl_ast_build_free(Build);
2053     KernelIds.push_back(Id);
2054     IDToSAI[Id] = SAIRep;
2055     Arg++;
2056   }
2057 
2058   for (long i = 0; i < NumHostIters; i++) {
2059     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2060     Arg->setName(isl_id_get_name(Id));
2061     IDToValue[Id] = &*Arg;
2062     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2063     Arg++;
2064   }
2065 
2066   for (long i = 0; i < NumVars; i++) {
2067     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2068     Arg->setName(isl_id_get_name(Id));
2069     Value *Val = IDToValue[Id];
2070     ValueMap[Val] = &*Arg;
2071     IDToValue[Id] = &*Arg;
2072     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2073     Arg++;
2074   }
2075 
2076   for (auto *V : SubtreeValues) {
2077     Arg->setName(V->getName());
2078     ValueMap[V] = &*Arg;
2079     Arg++;
2080   }
2081 
2082   return FN;
2083 }
2084 
2085 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
2086   Intrinsic::ID IntrinsicsBID[2];
2087   Intrinsic::ID IntrinsicsTID[3];
2088 
2089   switch (Arch) {
2090   case GPUArch::SPIR64:
2091   case GPUArch::SPIR32:
2092     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
2093   case GPUArch::NVPTX64:
2094     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
2095     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
2096 
2097     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
2098     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
2099     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
2100     break;
2101   }
2102 
2103   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2104     std::string Name = isl_id_get_name(Id);
2105     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2106     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2107     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2108     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2109     IDToValue[Id] = Val;
2110     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2111   };
2112 
2113   for (int i = 0; i < Kernel->n_grid; ++i) {
2114     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2115     addId(Id, IntrinsicsBID[i]);
2116   }
2117 
2118   for (int i = 0; i < Kernel->n_block; ++i) {
2119     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2120     addId(Id, IntrinsicsTID[i]);
2121   }
2122 }
2123 
2124 void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2125                                            bool SizeTypeIs64bit) {
2126   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
2127                               "__gen_ocl_get_group_id1",
2128                               "__gen_ocl_get_group_id2"};
2129 
2130   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
2131                               "__gen_ocl_get_local_id1",
2132                               "__gen_ocl_get_local_id2"};
2133   IntegerType *SizeT =
2134       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
2135 
2136   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2137                            IntegerType *SizeT) mutable {
2138     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2139     Function *FN = M->getFunction(Name);
2140 
2141     // If FN is not available, declare it.
2142     if (!FN) {
2143       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
2144       std::vector<Type *> Args;
2145       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
2146       FN = Function::Create(Ty, Linkage, Name, M);
2147       FN->setCallingConv(CallingConv::SPIR_FUNC);
2148     }
2149 
2150     Value *Val = Builder.CreateCall(FN, {});
2151     if (SizeT == Builder.getInt32Ty())
2152       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2153     IDToValue[Id] = Val;
2154     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2155   };
2156 
2157   for (int i = 0; i < Kernel->n_grid; ++i)
2158     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
2159 
2160   for (int i = 0; i < Kernel->n_block; ++i)
2161     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
2162 }
2163 
2164 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
2165   auto Arg = FN->arg_begin();
2166   for (long i = 0; i < Kernel->n_array; i++) {
2167     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2168       continue;
2169 
2170     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2171     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2172     isl_id_free(Id);
2173 
2174     if (SAI->getNumberOfDimensions() > 0) {
2175       Arg++;
2176       continue;
2177     }
2178 
2179     Value *Val = &*Arg;
2180 
2181     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
2182       Type *TypePtr = SAI->getElementType()->getPointerTo();
2183       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2184       Val = Builder.CreateLoad(SAI->getElementType(), TypedArgPtr);
2185     }
2186 
2187     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
2188     Builder.CreateStore(Val, Alloca);
2189 
2190     Arg++;
2191   }
2192 }
2193 
2194 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
2195   auto *FN = Builder.GetInsertBlock()->getParent();
2196   auto Arg = FN->arg_begin();
2197 
2198   bool StoredScalar = false;
2199   for (long i = 0; i < Kernel->n_array; i++) {
2200     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2201       continue;
2202 
2203     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2204     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2205     isl_id_free(Id);
2206 
2207     if (SAI->getNumberOfDimensions() > 0) {
2208       Arg++;
2209       continue;
2210     }
2211 
2212     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
2213       Arg++;
2214       continue;
2215     }
2216 
2217     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
2218     Value *ArgPtr = &*Arg;
2219     Type *TypePtr = SAI->getElementType()->getPointerTo();
2220     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
2221     Value *Val = Builder.CreateLoad(SAI->getElementType(), Alloca);
2222     Builder.CreateStore(Val, TypedArgPtr);
2223     StoredScalar = true;
2224 
2225     Arg++;
2226   }
2227 
2228   if (StoredScalar) {
2229     /// In case more than one thread contains scalar stores, the generated
2230     /// code might be incorrect, if we only store at the end of the kernel.
2231     /// To support this case we need to store these scalars back at each
2232     /// memory store or at least before each kernel barrier.
2233     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
2234       BuildSuccessful = 0;
2235       LLVM_DEBUG(
2236           dbgs() << getUniqueScopName(&S)
2237                  << " has a store to a scalar value that"
2238                     " would be undefined to run in parallel. Bailing out.\n";);
2239     }
2240   }
2241 }
2242 
2243 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2244   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2245 
2246   for (int i = 0; i < Kernel->n_var; ++i) {
2247     struct ppcg_kernel_var &Var = Kernel->var[i];
2248     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2249     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2250 
2251     Type *ArrayTy = EleTy;
2252     SmallVector<const SCEV *, 4> Sizes;
2253 
2254     Sizes.push_back(nullptr);
2255     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2256       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2257       long Bound = isl_val_get_num_si(Val);
2258       isl_val_free(Val);
2259       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2260     }
2261 
2262     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2263       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2264       long Bound = isl_val_get_num_si(Val);
2265       isl_val_free(Val);
2266       ArrayTy = ArrayType::get(ArrayTy, Bound);
2267     }
2268 
2269     const ScopArrayInfo *SAI;
2270     Value *Allocation;
2271     if (Var.type == ppcg_access_shared) {
2272       auto GlobalVar = new GlobalVariable(
2273           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2274           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2275       GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8));
2276       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2277 
2278       Allocation = GlobalVar;
2279     } else if (Var.type == ppcg_access_private) {
2280       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2281     } else {
2282       llvm_unreachable("unknown variable type");
2283     }
2284     SAI =
2285         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2286     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2287     IDToValue[Id] = Allocation;
2288     LocalArrays.push_back(Allocation);
2289     KernelIds.push_back(Id);
2290     IDToSAI[Id] = SAI;
2291   }
2292 }
2293 
2294 void GPUNodeBuilder::createKernelFunction(
2295     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2296     SetVector<Function *> &SubtreeFunctions) {
2297   std::string Identifier = getKernelFuncName(Kernel->id);
2298   GPUModule.reset(new Module(Identifier, Builder.getContext()));
2299 
2300   switch (Arch) {
2301   case GPUArch::NVPTX64:
2302     if (Runtime == GPURuntime::CUDA)
2303       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
2304     else if (Runtime == GPURuntime::OpenCL)
2305       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
2306     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
2307     break;
2308   case GPUArch::SPIR32:
2309     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
2310     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
2311     break;
2312   case GPUArch::SPIR64:
2313     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
2314     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
2315     break;
2316   }
2317 
2318   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
2319 
2320   BasicBlock *PrevBlock = Builder.GetInsertBlock();
2321   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
2322 
2323   DT.addNewBlock(EntryBlock, PrevBlock);
2324 
2325   Builder.SetInsertPoint(EntryBlock);
2326   Builder.CreateRetVoid();
2327   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2328 
2329   ScopDetection::markFunctionAsInvalid(FN);
2330 
2331   prepareKernelArguments(Kernel, FN);
2332   createKernelVariables(Kernel, FN);
2333 
2334   switch (Arch) {
2335   case GPUArch::NVPTX64:
2336     insertKernelIntrinsics(Kernel);
2337     break;
2338   case GPUArch::SPIR32:
2339     insertKernelCallsSPIR(Kernel, false);
2340     break;
2341   case GPUArch::SPIR64:
2342     insertKernelCallsSPIR(Kernel, true);
2343     break;
2344   }
2345 }
2346 
2347 std::string GPUNodeBuilder::createKernelASM() {
2348   llvm::Triple GPUTriple;
2349 
2350   switch (Arch) {
2351   case GPUArch::NVPTX64:
2352     switch (Runtime) {
2353     case GPURuntime::CUDA:
2354       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
2355       break;
2356     case GPURuntime::OpenCL:
2357       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
2358       break;
2359     }
2360     break;
2361   case GPUArch::SPIR64:
2362   case GPUArch::SPIR32:
2363     std::string SPIRAssembly;
2364     raw_string_ostream IROstream(SPIRAssembly);
2365     IROstream << *GPUModule;
2366     IROstream.flush();
2367     return SPIRAssembly;
2368   }
2369 
2370   std::string ErrMsg;
2371   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
2372 
2373   if (!GPUTarget) {
2374     errs() << ErrMsg << "\n";
2375     return "";
2376   }
2377 
2378   TargetOptions Options;
2379   Options.UnsafeFPMath = FastMath;
2380 
2381   std::string subtarget;
2382 
2383   switch (Arch) {
2384   case GPUArch::NVPTX64:
2385     subtarget = CudaVersion;
2386     break;
2387   case GPUArch::SPIR32:
2388   case GPUArch::SPIR64:
2389     llvm_unreachable("No subtarget for SPIR architecture");
2390   }
2391 
2392   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
2393       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
2394 
2395   SmallString<0> ASMString;
2396   raw_svector_ostream ASMStream(ASMString);
2397   llvm::legacy::PassManager PM;
2398 
2399   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
2400 
2401   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile,
2402                                    true /* verify */)) {
2403     errs() << "The target does not support generation of this file type!\n";
2404     return "";
2405   }
2406 
2407   PM.run(*GPUModule);
2408 
2409   return ASMStream.str().str();
2410 }
2411 
2412 bool GPUNodeBuilder::requiresCUDALibDevice() {
2413   bool RequiresLibDevice = false;
2414   for (Function &F : GPUModule->functions()) {
2415     if (!F.isDeclaration())
2416       continue;
2417 
2418     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
2419     if (CUDALibDeviceFunc.length() != 0) {
2420       // We need to handle the case where a module looks like this:
2421       // @expf(..)
2422       // @llvm.exp.f64(..)
2423       // Both of these functions would be renamed to `__nv_expf`.
2424       //
2425       // So, we must first check for the existence of the libdevice function.
2426       // If this exists, we replace our current function with it.
2427       //
2428       // If it does not exist, we rename the current function to the
2429       // libdevice functiono name.
2430       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
2431         F.replaceAllUsesWith(Replacement);
2432       else
2433         F.setName(CUDALibDeviceFunc);
2434       RequiresLibDevice = true;
2435     }
2436   }
2437 
2438   return RequiresLibDevice;
2439 }
2440 
2441 void GPUNodeBuilder::addCUDALibDevice() {
2442   if (Arch != GPUArch::NVPTX64)
2443     return;
2444 
2445   if (requiresCUDALibDevice()) {
2446     SMDiagnostic Error;
2447 
2448     errs() << CUDALibDevice << "\n";
2449     auto LibDeviceModule =
2450         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
2451 
2452     if (!LibDeviceModule) {
2453       BuildSuccessful = false;
2454       report_fatal_error("Could not find or load libdevice. Skipping GPU "
2455                          "kernel generation. Please set -polly-acc-libdevice "
2456                          "accordingly.\n");
2457       return;
2458     }
2459 
2460     Linker L(*GPUModule);
2461 
2462     // Set an nvptx64 target triple to avoid linker warnings. The original
2463     // triple of the libdevice files are nvptx-unknown-unknown.
2464     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
2465     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
2466   }
2467 }
2468 
2469 std::string GPUNodeBuilder::finalizeKernelFunction() {
2470 
2471   if (verifyModule(*GPUModule)) {
2472     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
2473                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2474     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2475                verifyModule(*GPUModule, &dbgs()););
2476 
2477     if (FailOnVerifyModuleFailure)
2478       llvm_unreachable("VerifyModule failed.");
2479 
2480     BuildSuccessful = false;
2481     return "";
2482   }
2483 
2484   addCUDALibDevice();
2485 
2486   if (DumpKernelIR)
2487     outs() << *GPUModule << "\n";
2488 
2489   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
2490     // Optimize module.
2491     llvm::legacy::PassManager OptPasses;
2492     PassManagerBuilder PassBuilder;
2493     PassBuilder.OptLevel = 3;
2494     PassBuilder.SizeLevel = 0;
2495     PassBuilder.populateModulePassManager(OptPasses);
2496     OptPasses.run(*GPUModule);
2497   }
2498 
2499   std::string Assembly = createKernelASM();
2500 
2501   if (DumpKernelASM)
2502     outs() << Assembly << "\n";
2503 
2504   GPUModule.release();
2505   KernelIDs.clear();
2506 
2507   return Assembly;
2508 }
2509 /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2510 /// @param PwAffs The list of piecewise affine functions to create an
2511 ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2512 ///               all the isl_pw_aff are used up by this function.
2513 ///
2514 /// @returns  The `isl_pw_aff_list`.
2515 __isl_give isl_pw_aff_list *
2516 createPwAffList(isl_ctx *Context,
2517                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2518   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2519 
2520   for (unsigned i = 0; i < PwAffs.size(); i++) {
2521     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2522   }
2523   return List;
2524 }
2525 
2526 /// Align all the `PwAffs` such that they have the same parameter dimensions.
2527 ///
2528 /// We loop over all `pw_aff` and align all of their spaces together to
2529 /// create a common space for all the `pw_aff`. This common space is the
2530 /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2531 /// with the given `SeedSpace`.
2532 /// @param PwAffs    The list of piecewise affine functions we want to align.
2533 ///                  This is an rvalue reference because the entire vector is
2534 ///                  used up by the end of the operation.
2535 /// @param SeedSpace The space to start the alignment process with.
2536 /// @returns         A std::pair, whose first element is the aligned space,
2537 ///                  whose second element is the vector of aligned piecewise
2538 ///                  affines.
2539 static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2540 alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2541             __isl_take isl_space *SeedSpace) {
2542   assert(SeedSpace && "Invalid seed space given.");
2543 
2544   isl_space *AlignSpace = SeedSpace;
2545   for (isl_pw_aff *PwAff : PwAffs) {
2546     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2547     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2548   }
2549   std::vector<isl_pw_aff *> AdjustedPwAffs;
2550 
2551   for (unsigned i = 0; i < PwAffs.size(); i++) {
2552     isl_pw_aff *Adjusted = PwAffs[i];
2553     assert(Adjusted && "Invalid pw_aff given.");
2554     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2555     AdjustedPwAffs.push_back(Adjusted);
2556   }
2557   return std::make_pair(AlignSpace, AdjustedPwAffs);
2558 }
2559 
2560 namespace {
2561 class PPCGCodeGeneration final : public ScopPass {
2562 public:
2563   static char ID;
2564 
2565   GPURuntime Runtime = GPURuntime::CUDA;
2566 
2567   GPUArch Architecture = GPUArch::NVPTX64;
2568 
2569   /// The scop that is currently processed.
2570   Scop *S;
2571 
2572   LoopInfo *LI;
2573   DominatorTree *DT;
2574   ScalarEvolution *SE;
2575   const DataLayout *DL;
2576   RegionInfo *RI;
2577 
2578   PPCGCodeGeneration() : ScopPass(ID) {
2579     // Apply defaults.
2580     Runtime = GPURuntimeChoice;
2581     Architecture = GPUArchChoice;
2582   }
2583 
2584   /// Construct compilation options for PPCG.
2585   ///
2586   /// @returns The compilation options.
2587   ppcg_options *createPPCGOptions() {
2588     auto DebugOptions =
2589         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2590     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2591 
2592     DebugOptions->dump_schedule_constraints = false;
2593     DebugOptions->dump_schedule = false;
2594     DebugOptions->dump_final_schedule = false;
2595     DebugOptions->dump_sizes = false;
2596     DebugOptions->verbose = false;
2597 
2598     Options->debug = DebugOptions;
2599 
2600     Options->group_chains = false;
2601     Options->reschedule = true;
2602     Options->scale_tile_loops = false;
2603     Options->wrap = false;
2604 
2605     Options->non_negative_parameters = false;
2606     Options->ctx = nullptr;
2607     Options->sizes = nullptr;
2608 
2609     Options->tile = true;
2610     Options->tile_size = 32;
2611 
2612     Options->isolate_full_tiles = false;
2613 
2614     Options->use_private_memory = PrivateMemory;
2615     Options->use_shared_memory = SharedMemory;
2616     Options->max_shared_memory = 48 * 1024;
2617 
2618     Options->target = PPCG_TARGET_CUDA;
2619     Options->openmp = false;
2620     Options->linearize_device_arrays = true;
2621     Options->allow_gnu_extensions = false;
2622 
2623     Options->unroll_copy_shared = false;
2624     Options->unroll_gpu_tile = false;
2625     Options->live_range_reordering = true;
2626 
2627     Options->live_range_reordering = true;
2628     Options->hybrid = false;
2629     Options->opencl_compiler_options = nullptr;
2630     Options->opencl_use_gpu = false;
2631     Options->opencl_n_include_file = 0;
2632     Options->opencl_include_files = nullptr;
2633     Options->opencl_print_kernel_types = false;
2634     Options->opencl_embed_kernel_code = false;
2635 
2636     Options->save_schedule_file = nullptr;
2637     Options->load_schedule_file = nullptr;
2638 
2639     return Options;
2640   }
2641 
2642   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2643   ///
2644   /// Instead of a normal access of the form:
2645   ///
2646   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2647   ///
2648   /// a tagged access has the form
2649   ///
2650   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2651   ///
2652   /// where 'id' is an additional space that references the memory access that
2653   /// triggered the access.
2654   ///
2655   /// @param AccessTy The type of the memory accesses to collect.
2656   ///
2657   /// @return The relation describing all tagged memory accesses.
2658   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2659     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2660 
2661     for (auto &Stmt : *S)
2662       for (auto &Acc : Stmt)
2663         if (Acc->getType() == AccessTy) {
2664           isl_map *Relation = Acc->getAccessRelation().release();
2665           Relation =
2666               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2667 
2668           isl_space *Space = isl_map_get_space(Relation);
2669           Space = isl_space_range(Space);
2670           Space = isl_space_from_range(Space);
2671           Space =
2672               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2673           isl_map *Universe = isl_map_universe(Space);
2674           Relation = isl_map_domain_product(Relation, Universe);
2675           Accesses = isl_union_map_add_map(Accesses, Relation);
2676         }
2677 
2678     return Accesses;
2679   }
2680 
2681   /// Get the set of all read accesses, tagged with the access id.
2682   ///
2683   /// @see getTaggedAccesses
2684   isl_union_map *getTaggedReads() {
2685     return getTaggedAccesses(MemoryAccess::READ);
2686   }
2687 
2688   /// Get the set of all may (and must) accesses, tagged with the access id.
2689   ///
2690   /// @see getTaggedAccesses
2691   isl_union_map *getTaggedMayWrites() {
2692     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2693                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2694   }
2695 
2696   /// Get the set of all must accesses, tagged with the access id.
2697   ///
2698   /// @see getTaggedAccesses
2699   isl_union_map *getTaggedMustWrites() {
2700     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2701   }
2702 
2703   /// Collect parameter and array names as isl_ids.
2704   ///
2705   /// To reason about the different parameters and arrays used, ppcg requires
2706   /// a list of all isl_ids in use. As PPCG traditionally performs
2707   /// source-to-source compilation each of these isl_ids is mapped to the
2708   /// expression that represents it. As we do not have a corresponding
2709   /// expression in Polly, we just map each id to a 'zero' expression to match
2710   /// the data format that ppcg expects.
2711   ///
2712   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2713   __isl_give isl_id_to_ast_expr *getNames() {
2714     auto *Names = isl_id_to_ast_expr_alloc(
2715         S->getIslCtx().get(),
2716         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2717     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2718 
2719     for (const SCEV *P : S->parameters()) {
2720       isl_id *Id = S->getIdForParam(P).release();
2721       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2722     }
2723 
2724     for (auto &Array : S->arrays()) {
2725       auto Id = Array->getBasePtrId().release();
2726       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2727     }
2728 
2729     isl_ast_expr_free(Zero);
2730 
2731     return Names;
2732   }
2733 
2734   /// Create a new PPCG scop from the current scop.
2735   ///
2736   /// The PPCG scop is initialized with data from the current polly::Scop. From
2737   /// this initial data, the data-dependences in the PPCG scop are initialized.
2738   /// We do not use Polly's dependence analysis for now, to ensure we match
2739   /// the PPCG default behaviour more closely.
2740   ///
2741   /// @returns A new ppcg scop.
2742   ppcg_scop *createPPCGScop() {
2743     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
2744 
2745     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2746 
2747     PPCGScop->options = createPPCGOptions();
2748     // enable live range reordering
2749     PPCGScop->options->live_range_reordering = 1;
2750 
2751     PPCGScop->start = 0;
2752     PPCGScop->end = 0;
2753 
2754     PPCGScop->context = S->getContext().release();
2755     PPCGScop->domain = S->getDomains().release();
2756     // TODO: investigate this further. PPCG calls collect_call_domains.
2757     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2758     PPCGScop->tagged_reads = getTaggedReads();
2759     PPCGScop->reads = S->getReads().release();
2760     PPCGScop->live_in = nullptr;
2761     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2762     PPCGScop->may_writes = S->getWrites().release();
2763     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2764     PPCGScop->must_writes = S->getMustWrites().release();
2765     PPCGScop->live_out = nullptr;
2766     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
2767     PPCGScop->must_kills = KillsInfo.MustKills.release();
2768 
2769     PPCGScop->tagger = nullptr;
2770     PPCGScop->independence =
2771         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2772     PPCGScop->dep_flow = nullptr;
2773     PPCGScop->tagged_dep_flow = nullptr;
2774     PPCGScop->dep_false = nullptr;
2775     PPCGScop->dep_forced = nullptr;
2776     PPCGScop->dep_order = nullptr;
2777     PPCGScop->tagged_dep_order = nullptr;
2778 
2779     PPCGScop->schedule = S->getScheduleTree().release();
2780     // If we have something non-trivial to kill, add it to the schedule
2781     if (KillsInfo.KillsSchedule.get())
2782       PPCGScop->schedule = isl_schedule_sequence(
2783           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2784 
2785     PPCGScop->names = getNames();
2786     PPCGScop->pet = nullptr;
2787 
2788     compute_tagger(PPCGScop);
2789     compute_dependences(PPCGScop);
2790     eliminate_dead_code(PPCGScop);
2791 
2792     return PPCGScop;
2793   }
2794 
2795   /// Collect the array accesses in a statement.
2796   ///
2797   /// @param Stmt The statement for which to collect the accesses.
2798   ///
2799   /// @returns A list of array accesses.
2800   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
2801     gpu_stmt_access *Accesses = nullptr;
2802 
2803     for (MemoryAccess *Acc : Stmt) {
2804       auto Access =
2805           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
2806       Access->read = Acc->isRead();
2807       Access->write = Acc->isWrite();
2808       Access->access = Acc->getAccessRelation().release();
2809       isl_space *Space = isl_map_get_space(Access->access);
2810       Space = isl_space_range(Space);
2811       Space = isl_space_from_range(Space);
2812       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2813       isl_map *Universe = isl_map_universe(Space);
2814       Access->tagged_access =
2815           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2816       Access->exact_write = !Acc->isMayWrite();
2817       Access->ref_id = Acc->getId().release();
2818       Access->next = Accesses;
2819       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2820       // TODO: Also mark one-element accesses to arrays as fixed-element.
2821       Access->fixed_element =
2822           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
2823       Accesses = Access;
2824     }
2825 
2826     return Accesses;
2827   }
2828 
2829   /// Collect the list of GPU statements.
2830   ///
2831   /// Each statement has an id, a pointer to the underlying data structure,
2832   /// as well as a list with all memory accesses.
2833   ///
2834   /// TODO: Initialize the list of memory accesses.
2835   ///
2836   /// @returns A linked-list of statements.
2837   gpu_stmt *getStatements() {
2838     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
2839                                        std::distance(S->begin(), S->end()));
2840 
2841     int i = 0;
2842     for (auto &Stmt : *S) {
2843       gpu_stmt *GPUStmt = &Stmts[i];
2844 
2845       GPUStmt->id = Stmt.getDomainId().release();
2846 
2847       // We use the pet stmt pointer to keep track of the Polly statements.
2848       GPUStmt->stmt = (pet_stmt *)&Stmt;
2849       GPUStmt->accesses = getStmtAccesses(Stmt);
2850       i++;
2851     }
2852 
2853     return Stmts;
2854   }
2855 
2856   /// Derive the extent of an array.
2857   ///
2858   /// The extent of an array is the set of elements that are within the
2859   /// accessed array. For the inner dimensions, the extent constraints are
2860   /// 0 and the size of the corresponding array dimension. For the first
2861   /// (outermost) dimension, the extent constraints are the minimal and maximal
2862   /// subscript value for the first dimension.
2863   ///
2864   /// @param Array The array to derive the extent for.
2865   ///
2866   /// @returns An isl_set describing the extent of the array.
2867   isl::set getExtent(ScopArrayInfo *Array) {
2868     unsigned NumDims = Array->getNumberOfDimensions();
2869 
2870     if (Array->getNumberOfDimensions() == 0)
2871       return isl::set::universe(Array->getSpace());
2872 
2873     isl::union_map Accesses = S->getAccesses(Array);
2874     isl::union_set AccessUSet = Accesses.range();
2875     AccessUSet = AccessUSet.coalesce();
2876     AccessUSet = AccessUSet.detect_equalities();
2877     AccessUSet = AccessUSet.coalesce();
2878 
2879     if (AccessUSet.is_empty())
2880       return isl::set::empty(Array->getSpace());
2881 
2882     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
2883 
2884     isl::local_space LS = isl::local_space(Array->getSpace());
2885 
2886     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2887     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2888     isl::pw_aff OuterMax = AccessSet.dim_max(0);
2889     OuterMin = OuterMin.add_dims(isl::dim::in,
2890                                  unsignedFromIslSize(Val.dim(isl::dim::in)));
2891     OuterMax = OuterMax.add_dims(isl::dim::in,
2892                                  unsignedFromIslSize(Val.dim(isl::dim::in)));
2893     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2894     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2895 
2896     isl::set Extent = isl::set::universe(Array->getSpace());
2897 
2898     Extent = Extent.intersect(OuterMin.le_set(Val));
2899     Extent = Extent.intersect(OuterMax.ge_set(Val));
2900 
2901     for (unsigned i = 1; i < NumDims; ++i)
2902       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2903 
2904     for (unsigned i = 0; i < NumDims; ++i) {
2905       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2906 
2907       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2908       // Fortran array will we have a legitimate dimension.
2909       if (PwAff.is_null()) {
2910         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2911         continue;
2912       }
2913 
2914       isl::pw_aff Val = isl::aff::var_on_domain(
2915           isl::local_space(Array->getSpace()), isl::dim::set, i);
2916       PwAff = PwAff.add_dims(isl::dim::in,
2917                              unsignedFromIslSize(Val.dim(isl::dim::in)));
2918       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2919       isl::set Set = PwAff.gt_set(Val);
2920       Extent = Set.intersect(Extent);
2921     }
2922 
2923     return Extent;
2924   }
2925 
2926   /// Derive the bounds of an array.
2927   ///
2928   /// For the first dimension we derive the bound of the array from the extent
2929   /// of this dimension. For inner dimensions we obtain their size directly from
2930   /// ScopArrayInfo.
2931   ///
2932   /// @param PPCGArray The array to compute bounds for.
2933   /// @param Array The polly array from which to take the information.
2934   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2935     std::vector<isl_pw_aff *> Bounds;
2936 
2937     if (PPCGArray.n_index > 0) {
2938       if (isl_set_is_empty(PPCGArray.extent)) {
2939         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2940         isl_local_space *LS = isl_local_space_from_space(
2941             isl_space_params(isl_set_get_space(Dom)));
2942         isl_set_free(Dom);
2943         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2944         Bounds.push_back(Zero);
2945       } else {
2946         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2947         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
2948         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
2949         isl_set_free(Dom);
2950         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
2951         isl_local_space *LS =
2952             isl_local_space_from_space(isl_set_get_space(Dom));
2953         isl_aff *One = isl_aff_zero_on_domain(LS);
2954         One = isl_aff_add_constant_si(One, 1);
2955         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
2956         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2957         Bounds.push_back(Bound);
2958       }
2959     }
2960 
2961     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
2962       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
2963       auto LS = isl_pw_aff_get_domain_space(Bound);
2964       auto Aff = isl_multi_aff_zero(LS);
2965 
2966       // We need types to work out, which is why we perform this weird dance
2967       // with `Aff` and `Bound`. Consider this example:
2968 
2969       // LS: [p] -> { [] }
2970       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2971       // This `~` is used to denote a "null space" (which is different from
2972       // a *zero dimensional* space), which is something that ISL does not
2973       // show you when pretty printing.
2974 
2975       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2976       // space, not a "null space" which does not exist at all.
2977 
2978       // When we pullback (precompose) `Bound` with `Zero`, we get:
2979       // Bound . Zero =
2980       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2981       //     [p] -> { ~ -> [(10p)] } =
2982       //     [p] -> [(10p)] (as ISL pretty prints it)
2983       // Bound Pullback: [p] -> { [(10p)] }
2984 
2985       // We want this kind of an expression for Bound, without a
2986       // zero dimensional input, but with a "null space" input for the types
2987       // to work out later on, as far as I (Siddharth Bhat) understand.
2988       // I was unable to find a reference to this in the ISL manual.
2989       // References: Tobias Grosser.
2990 
2991       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2992       Bounds.push_back(Bound);
2993     }
2994 
2995     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2996     /// to have the same parameter dimensions. So, we need to align them to an
2997     /// appropriate space.
2998     /// Scop::Context is _not_ an appropriate space, because when we have
2999     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
3000     /// contain all parameter dimensions.
3001     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
3002     isl_space *SeedAlignSpace = S->getParamSpace().release();
3003     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
3004 
3005     isl_space *AlignSpace = nullptr;
3006     std::vector<isl_pw_aff *> AlignedBounds;
3007     std::tie(AlignSpace, AlignedBounds) =
3008         alignPwAffs(std::move(Bounds), SeedAlignSpace);
3009 
3010     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
3011 
3012     isl_pw_aff_list *BoundsList =
3013         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
3014 
3015     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
3016     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
3017 
3018     assert(BoundsSpace && "Unable to access space of array.");
3019     assert(BoundsList && "Unable to access list of bounds.");
3020 
3021     PPCGArray.bound =
3022         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
3023     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
3024   }
3025 
3026   /// Create the arrays for @p PPCGProg.
3027   ///
3028   /// @param PPCGProg The program to compute the arrays for.
3029   void createArrays(gpu_prog *PPCGProg,
3030                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
3031     int i = 0;
3032     for (auto &Array : ValidSAIs) {
3033       std::string TypeName;
3034       raw_string_ostream OS(TypeName);
3035 
3036       OS << *Array->getElementType();
3037       TypeName = OS.str();
3038 
3039       gpu_array_info &PPCGArray = PPCGProg->array[i];
3040 
3041       PPCGArray.space = Array->getSpace().release();
3042       PPCGArray.type = strdup(TypeName.c_str());
3043       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
3044       PPCGArray.name = strdup(Array->getName().c_str());
3045       PPCGArray.extent = nullptr;
3046       PPCGArray.n_index = Array->getNumberOfDimensions();
3047       PPCGArray.extent = getExtent(Array).release();
3048       PPCGArray.n_ref = 0;
3049       PPCGArray.refs = nullptr;
3050       PPCGArray.accessed = true;
3051       PPCGArray.read_only_scalar =
3052           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
3053       PPCGArray.has_compound_element = false;
3054       PPCGArray.local = false;
3055       PPCGArray.declare_local = false;
3056       PPCGArray.global = false;
3057       PPCGArray.linearize = false;
3058       PPCGArray.dep_order = nullptr;
3059       PPCGArray.user = Array;
3060 
3061       PPCGArray.bound = nullptr;
3062       setArrayBounds(PPCGArray, Array);
3063       i++;
3064 
3065       collect_references(PPCGProg, &PPCGArray);
3066       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
3067     }
3068   }
3069 
3070   /// Create an identity map between the arrays in the scop.
3071   ///
3072   /// @returns An identity map between the arrays in the scop.
3073   isl_union_map *getArrayIdentity() {
3074     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
3075 
3076     for (auto &Array : S->arrays()) {
3077       isl_space *Space = Array->getSpace().release();
3078       Space = isl_space_map_from_set(Space);
3079       isl_map *Identity = isl_map_identity(Space);
3080       Maps = isl_union_map_add_map(Maps, Identity);
3081     }
3082 
3083     return Maps;
3084   }
3085 
3086   /// Create a default-initialized PPCG GPU program.
3087   ///
3088   /// @returns A new gpu program description.
3089   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3090 
3091     if (!PPCGScop)
3092       return nullptr;
3093 
3094     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3095 
3096     PPCGProg->ctx = S->getIslCtx().get();
3097     PPCGProg->scop = PPCGScop;
3098     PPCGProg->context = isl_set_copy(PPCGScop->context);
3099     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
3100     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
3101     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
3102     PPCGProg->tagged_must_kill =
3103         isl_union_map_copy(PPCGScop->tagged_must_kills);
3104     PPCGProg->to_inner = getArrayIdentity();
3105     PPCGProg->to_outer = getArrayIdentity();
3106     // TODO: verify that this assignment is correct.
3107     PPCGProg->any_to_outer = nullptr;
3108     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
3109     PPCGProg->stmts = getStatements();
3110 
3111     // Only consider arrays that have a non-empty extent.
3112     // Otherwise, this will cause us to consider the following kinds of
3113     // empty arrays:
3114     //     1. Invariant loads that are represented by SAI objects.
3115     //     2. Arrays with statically known zero size.
3116     auto ValidSAIsRange =
3117         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3118           return !getExtent(SAI).is_empty();
3119         });
3120     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
3121                                               ValidSAIsRange.end());
3122 
3123     PPCGProg->n_array =
3124         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
3125     PPCGProg->array = isl_calloc_array(
3126         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
3127 
3128     createArrays(PPCGProg, ValidSAIs);
3129 
3130     PPCGProg->array_order = nullptr;
3131     collect_order_dependences(PPCGProg);
3132 
3133     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3134     return PPCGProg;
3135   }
3136 
3137   struct PrintGPUUserData {
3138     struct cuda_info *CudaInfo;
3139     struct gpu_prog *PPCGProg;
3140     std::vector<ppcg_kernel *> Kernels;
3141   };
3142 
3143   /// Print a user statement node in the host code.
3144   ///
3145   /// We use ppcg's printing facilities to print the actual statement and
3146   /// additionally build up a list of all kernels that are encountered in the
3147   /// host ast.
3148   ///
3149   /// @param P The printer to print to
3150   /// @param Options The printing options to use
3151   /// @param Node The node to print
3152   /// @param User A user pointer to carry additional data. This pointer is
3153   ///             expected to be of type PrintGPUUserData.
3154   ///
3155   /// @returns A printer to which the output has been printed.
3156   static __isl_give isl_printer *
3157   printHostUser(__isl_take isl_printer *P,
3158                 __isl_take isl_ast_print_options *Options,
3159                 __isl_take isl_ast_node *Node, void *User) {
3160     auto Data = (struct PrintGPUUserData *)User;
3161     auto Id = isl_ast_node_get_annotation(Node);
3162 
3163     if (Id) {
3164       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
3165 
3166       // If this is a user statement, format it ourselves as ppcg would
3167       // otherwise try to call pet functionality that is not available in
3168       // Polly.
3169       if (IsUser) {
3170         P = isl_printer_start_line(P);
3171         P = isl_printer_print_ast_node(P, Node);
3172         P = isl_printer_end_line(P);
3173         isl_id_free(Id);
3174         isl_ast_print_options_free(Options);
3175         return P;
3176       }
3177 
3178       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
3179       isl_id_free(Id);
3180       Data->Kernels.push_back(Kernel);
3181     }
3182 
3183     return print_host_user(P, Options, Node, User);
3184   }
3185 
3186   /// Print C code corresponding to the control flow in @p Kernel.
3187   ///
3188   /// @param Kernel The kernel to print
3189   void printKernel(ppcg_kernel *Kernel) {
3190     auto *P = isl_printer_to_str(S->getIslCtx().get());
3191     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
3192     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
3193     P = isl_ast_node_print(Kernel->tree, P, Options);
3194     char *String = isl_printer_get_str(P);
3195     outs() << String << "\n";
3196     free(String);
3197     isl_printer_free(P);
3198   }
3199 
3200   /// Print C code corresponding to the GPU code described by @p Tree.
3201   ///
3202   /// @param Tree An AST describing GPU code
3203   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
3204   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
3205     auto *P = isl_printer_to_str(S->getIslCtx().get());
3206     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
3207 
3208     PrintGPUUserData Data;
3209     Data.PPCGProg = PPCGProg;
3210 
3211     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
3212     Options =
3213         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
3214     P = isl_ast_node_print(Tree, P, Options);
3215     char *String = isl_printer_get_str(P);
3216     outs() << "# host\n";
3217     outs() << String << "\n";
3218     free(String);
3219     isl_printer_free(P);
3220 
3221     for (auto Kernel : Data.Kernels) {
3222       outs() << "# kernel" << Kernel->id << "\n";
3223       printKernel(Kernel);
3224     }
3225   }
3226 
3227   // Generate a GPU program using PPCG.
3228   //
3229   // GPU mapping consists of multiple steps:
3230   //
3231   //  1) Compute new schedule for the program.
3232   //  2) Map schedule to GPU (TODO)
3233   //  3) Generate code for new schedule (TODO)
3234   //
3235   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3236   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3237   // strategy directly from this pass.
3238   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3239 
3240     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3241 
3242     PPCGGen->ctx = S->getIslCtx().get();
3243     PPCGGen->options = PPCGScop->options;
3244     PPCGGen->print = nullptr;
3245     PPCGGen->print_user = nullptr;
3246     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3247     PPCGGen->prog = PPCGProg;
3248     PPCGGen->tree = nullptr;
3249     PPCGGen->types.n = 0;
3250     PPCGGen->types.name = nullptr;
3251     PPCGGen->sizes = nullptr;
3252     PPCGGen->used_sizes = nullptr;
3253     PPCGGen->kernel_id = 0;
3254 
3255     // Set scheduling strategy to same strategy PPCG is using.
3256     isl_options_set_schedule_serialize_sccs(PPCGGen->ctx, false);
3257     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3258     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
3259     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3260 
3261     isl_schedule *Schedule = get_schedule(PPCGGen);
3262 
3263     int has_permutable = has_any_permutable_node(Schedule);
3264 
3265     Schedule =
3266         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3267 
3268     if (!has_permutable || has_permutable < 0) {
3269       Schedule = isl_schedule_free(Schedule);
3270       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3271                         << " does not have permutable bands. Bailing out\n";);
3272     } else {
3273       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3274       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
3275       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
3276     }
3277 
3278     if (DumpSchedule) {
3279       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3280       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3281       P = isl_printer_print_str(P, "Schedule\n");
3282       P = isl_printer_print_str(P, "========\n");
3283       if (Schedule)
3284         P = isl_printer_print_schedule(P, Schedule);
3285       else
3286         P = isl_printer_print_str(P, "No schedule found\n");
3287 
3288       outs() << isl_printer_get_str(P) << "\n";
3289       isl_printer_free(P);
3290     }
3291 
3292     if (DumpCode) {
3293       outs() << "Code\n";
3294       outs() << "====\n";
3295       if (PPCGGen->tree)
3296         printGPUTree(PPCGGen->tree, PPCGProg);
3297       else
3298         outs() << "No code generated\n";
3299     }
3300 
3301     isl_schedule_free(Schedule);
3302 
3303     return PPCGGen;
3304   }
3305 
3306   /// Free gpu_gen structure.
3307   ///
3308   /// @param PPCGGen The ppcg_gen object to free.
3309   void freePPCGGen(gpu_gen *PPCGGen) {
3310     isl_ast_node_free(PPCGGen->tree);
3311     isl_union_map_free(PPCGGen->sizes);
3312     isl_union_map_free(PPCGGen->used_sizes);
3313     free(PPCGGen);
3314   }
3315 
3316   /// Free the options in the ppcg scop structure.
3317   ///
3318   /// ppcg is not freeing these options for us. To avoid leaks we do this
3319   /// ourselves.
3320   ///
3321   /// @param PPCGScop The scop referencing the options to free.
3322   void freeOptions(ppcg_scop *PPCGScop) {
3323     free(PPCGScop->options->debug);
3324     PPCGScop->options->debug = nullptr;
3325     free(PPCGScop->options);
3326     PPCGScop->options = nullptr;
3327   }
3328 
3329   /// Approximate the number of points in the set.
3330   ///
3331   /// This function returns an ast expression that overapproximates the number
3332   /// of points in an isl set through the rectangular hull surrounding this set.
3333   ///
3334   /// @param Set   The set to count.
3335   /// @param Build The isl ast build object to use for creating the ast
3336   ///              expression.
3337   ///
3338   /// @returns An approximation of the number of points in the set.
3339   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
3340                                              __isl_keep isl_ast_build *Build) {
3341 
3342     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
3343     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
3344 
3345     isl_space *Space = isl_set_get_space(Set);
3346     Space = isl_space_params(Space);
3347     auto *Univ = isl_set_universe(Space);
3348     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
3349 
3350     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
3351       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
3352       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
3353       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
3354       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
3355       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
3356       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
3357     }
3358 
3359     isl_set_free(Set);
3360     isl_pw_aff_free(OneAff);
3361 
3362     return Expr;
3363   }
3364 
3365   /// Approximate a number of dynamic instructions executed by a given
3366   /// statement.
3367   ///
3368   /// @param Stmt  The statement for which to compute the number of dynamic
3369   ///              instructions.
3370   /// @param Build The isl ast build object to use for creating the ast
3371   ///              expression.
3372   /// @returns An approximation of the number of dynamic instructions executed
3373   ///          by @p Stmt.
3374   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
3375                                              __isl_keep isl_ast_build *Build) {
3376     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
3377 
3378     long InstCount = 0;
3379 
3380     if (Stmt.isBlockStmt()) {
3381       auto *BB = Stmt.getBasicBlock();
3382       InstCount = std::distance(BB->begin(), BB->end());
3383     } else {
3384       auto *R = Stmt.getRegion();
3385 
3386       for (auto *BB : R->blocks()) {
3387         InstCount += std::distance(BB->begin(), BB->end());
3388       }
3389     }
3390 
3391     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
3392     auto *InstExpr = isl_ast_expr_from_val(InstVal);
3393     return isl_ast_expr_mul(InstExpr, Iterations);
3394   }
3395 
3396   /// Approximate dynamic instructions executed in scop.
3397   ///
3398   /// @param S     The scop for which to approximate dynamic instructions.
3399   /// @param Build The isl ast build object to use for creating the ast
3400   ///              expression.
3401   /// @returns An approximation of the number of dynamic instructions executed
3402   ///          in @p S.
3403   __isl_give isl_ast_expr *
3404   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
3405     isl_ast_expr *Instructions;
3406 
3407     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
3408     Instructions = isl_ast_expr_from_val(Zero);
3409 
3410     for (ScopStmt &Stmt : S) {
3411       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
3412       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
3413     }
3414     return Instructions;
3415   }
3416 
3417   /// Create a check that ensures sufficient compute in scop.
3418   ///
3419   /// @param S     The scop for which to ensure sufficient compute.
3420   /// @param Build The isl ast build object to use for creating the ast
3421   ///              expression.
3422   /// @returns An expression that evaluates to TRUE in case of sufficient
3423   ///          compute and to FALSE, otherwise.
3424   __isl_give isl_ast_expr *
3425   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
3426     auto Iterations = getNumberOfIterations(S, Build);
3427     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
3428     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
3429     return isl_ast_expr_ge(Iterations, MinComputeExpr);
3430   }
3431 
3432   /// Check if the basic block contains a function we cannot codegen for GPU
3433   /// kernels.
3434   ///
3435   /// If this basic block does something with a `Function` other than calling
3436   /// a function that we support in a kernel, return true.
3437   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
3438                                             bool AllowCUDALibDevice) {
3439     for (const Instruction &Inst : *BB) {
3440       const CallInst *Call = dyn_cast<CallInst>(&Inst);
3441       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
3442                                           AllowCUDALibDevice))
3443         continue;
3444 
3445       for (Value *Op : Inst.operands())
3446         // Look for functions among operands of Inst.
3447         if (isa<Function>(Op->stripPointerCasts())) {
3448           LLVM_DEBUG(dbgs()
3449                      << Inst << " has illegal use of function in kernel.\n");
3450           return true;
3451         }
3452     }
3453     return false;
3454   }
3455 
3456   /// Return whether the Scop S uses functions in a way that we do not support.
3457   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3458     for (auto &Stmt : S) {
3459       if (Stmt.isBlockStmt()) {
3460         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
3461                                                  AllowCUDALibDevice))
3462           return true;
3463       } else {
3464         assert(Stmt.isRegionStmt() &&
3465                "Stmt was neither block nor region statement");
3466         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
3467           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3468             return true;
3469       }
3470     }
3471     return false;
3472   }
3473 
3474   /// Generate code for a given GPU AST described by @p Root.
3475   ///
3476   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
3477   /// @param Prog The GPU Program to generate code for.
3478   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
3479     ScopAnnotator Annotator;
3480     Annotator.buildAliasScopes(*S);
3481 
3482     Region *R = &S->getRegion();
3483 
3484     simplifyRegion(R, DT, LI, RI);
3485 
3486     BasicBlock *EnteringBB = R->getEnteringBlock();
3487 
3488     PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(),
3489                            IRInserter(Annotator));
3490     Builder.SetInsertPoint(EnteringBB->getTerminator());
3491 
3492     // Only build the run-time condition and parameters _after_ having
3493     // introduced the conditional branch. This is important as the conditional
3494     // branch will guard the original scop from new induction variables that
3495     // the SCEVExpander may introduce while code generating the parameters and
3496     // which may introduce scalar dependences that prevent us from correctly
3497     // code generating this scop.
3498     BBPair StartExitBlocks;
3499     BranchInst *CondBr = nullptr;
3500     std::tie(StartExitBlocks, CondBr) =
3501         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3502     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
3503 
3504     assert(CondBr && "CondBr not initialized by executeScopConditionally");
3505 
3506     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
3507                                StartBlock, Prog, Runtime, Architecture);
3508 
3509     // TODO: Handle LICM
3510     auto SplitBlock = StartBlock->getSinglePredecessor();
3511     Builder.SetInsertPoint(SplitBlock->getTerminator());
3512 
3513     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
3514     isl::ast_expr Condition =
3515         IslAst::buildRunCondition(*S, isl::manage_copy(Build));
3516     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
3517     Condition =
3518         isl::manage(isl_ast_expr_and(Condition.release(), SufficientCompute));
3519     isl_ast_build_free(Build);
3520 
3521     // preload invariant loads. Note: This should happen before the RTC
3522     // because the RTC may depend on values that are invariant load hoisted.
3523     if (!NodeBuilder.preloadInvariantLoads()) {
3524       // Patch the introduced branch condition to ensure that we always execute
3525       // the original SCoP.
3526       auto *FalseI1 = Builder.getFalse();
3527       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
3528       SplitBBTerm->setOperand(0, FalseI1);
3529 
3530       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
3531                                S->getFunction().getName() +
3532                                " | Scop Region: " + S->getNameStr());
3533       // adjust the dominator tree accordingly.
3534       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
3535       assert(ExitingBlock);
3536       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
3537       assert(MergeBlock);
3538       polly::markBlockUnreachable(*StartBlock, Builder);
3539       polly::markBlockUnreachable(*ExitingBlock, Builder);
3540       auto *ExitingBB = S->getExitingBlock();
3541       assert(ExitingBB);
3542 
3543       DT->changeImmediateDominator(MergeBlock, ExitingBB);
3544       DT->eraseNode(ExitingBlock);
3545       isl_ast_node_free(Root);
3546     } else {
3547 
3548       if (polly::PerfMonitoring) {
3549         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
3550         P.initialize();
3551         P.insertRegionStart(SplitBlock->getTerminator());
3552 
3553         // TODO: actually think if this is the correct exiting block to place
3554         // the `end` performance marker. Invariant load hoisting changes
3555         // the CFG in a way that I do not precisely understand, so I
3556         // (Siddharth<[email protected]>) should come back to this and
3557         // think about which exiting block to use.
3558         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
3559         assert(ExitingBlock);
3560         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
3561         P.insertRegionEnd(MergeBlock->getTerminator());
3562       }
3563 
3564       NodeBuilder.addParameters(S->getContext().release());
3565       Value *RTC = NodeBuilder.createRTC(Condition.release());
3566       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3567 
3568       Builder.SetInsertPoint(&*StartBlock->begin());
3569 
3570       NodeBuilder.create(Root);
3571     }
3572 
3573     /// In case a sequential kernel has more surrounding loops as any parallel
3574     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3575     /// point in running it on a GPU.
3576     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
3577       CondBr->setOperand(0, Builder.getFalse());
3578 
3579     if (!NodeBuilder.BuildSuccessful)
3580       CondBr->setOperand(0, Builder.getFalse());
3581   }
3582 
3583   bool runOnScop(Scop &CurrentScop) override {
3584     S = &CurrentScop;
3585     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3586     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3587     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3588     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
3589     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3590 
3591     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3592                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3593 
3594     // We currently do not support functions other than intrinsics inside
3595     // kernels, as code generation will need to offload function calls to the
3596     // kernel. This may lead to a kernel trying to call a function on the host.
3597     // This also allows us to prevent codegen from trying to take the
3598     // address of an intrinsic function to send to the kernel.
3599     if (containsInvalidKernelFunction(CurrentScop,
3600                                       Architecture == GPUArch::NVPTX64)) {
3601       LLVM_DEBUG(
3602           dbgs() << getUniqueScopName(S)
3603                  << " contains function which cannot be materialised in a GPU "
3604                     "kernel. Bailing out.\n";);
3605       return false;
3606     }
3607 
3608     auto PPCGScop = createPPCGScop();
3609     auto PPCGProg = createPPCGProg(PPCGScop);
3610     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
3611 
3612     if (PPCGGen->tree) {
3613       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
3614       CurrentScop.markAsToBeSkipped();
3615     } else {
3616       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3617                         << " has empty PPCGGen->tree. Bailing out.\n");
3618     }
3619 
3620     freeOptions(PPCGScop);
3621     freePPCGGen(PPCGGen);
3622     gpu_prog_free(PPCGProg);
3623     ppcg_scop_free(PPCGScop);
3624 
3625     return true;
3626   }
3627 
3628   void printScop(raw_ostream &, Scop &) const override {}
3629 
3630   void getAnalysisUsage(AnalysisUsage &AU) const override {
3631     ScopPass::getAnalysisUsage(AU);
3632 
3633     AU.addRequired<DominatorTreeWrapperPass>();
3634     AU.addRequired<RegionInfoPass>();
3635     AU.addRequired<ScalarEvolutionWrapperPass>();
3636     AU.addRequired<ScopDetectionWrapperPass>();
3637     AU.addRequired<ScopInfoRegionPass>();
3638     AU.addRequired<LoopInfoWrapperPass>();
3639 
3640     // FIXME: We do not yet add regions for the newly generated code to the
3641     //        region tree.
3642   }
3643 };
3644 } // namespace
3645 
3646 char PPCGCodeGeneration::ID = 1;
3647 
3648 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
3649   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
3650   generator->Runtime = Runtime;
3651   generator->Architecture = Arch;
3652   return generator;
3653 }
3654 
3655 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
3656                       "Polly - Apply PPCG translation to SCOP", false, false)
3657 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
3658 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
3659 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
3660 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
3661 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
3662 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
3663 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
3664                     "Polly - Apply PPCG translation to SCOP", false, false)
3665