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