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