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