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