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