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