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