RSKernelExpand.cpp revision 57fd9f882f3359be4201c42b02aebf785d311df2
1/*
2 * Copyright 2012, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "bcc/Assert.h"
18#include "bcc/Renderscript/RSTransforms.h"
19#include "bcc/Renderscript/RSUtils.h"
20
21#include <cstdlib>
22#include <functional>
23#include <unordered_set>
24
25#include <llvm/IR/DerivedTypes.h>
26#include <llvm/IR/Function.h>
27#include <llvm/IR/Instructions.h>
28#include <llvm/IR/IRBuilder.h>
29#include <llvm/IR/MDBuilder.h>
30#include <llvm/IR/Module.h>
31#include <llvm/Pass.h>
32#include <llvm/Support/raw_ostream.h>
33#include <llvm/IR/DataLayout.h>
34#include <llvm/IR/Function.h>
35#include <llvm/IR/Type.h>
36#include <llvm/Transforms/Utils/BasicBlockUtils.h>
37
38#include "bcc/Config/Config.h"
39#include "bcc/Support/Log.h"
40
41#include "bcinfo/MetadataExtractor.h"
42
43#ifndef __DISABLE_ASSERTS
44// Only used in bccAssert()
45const int kNumExpandedForeachParams = 4;
46const int kNumExpandedReduceParams = 3;
47const int kNumExpandedReduceNewAccumulatorParams = 4;
48#endif
49
50const char kRenderScriptTBAARootName[] = "RenderScript Distinct TBAA";
51const char kRenderScriptTBAANodeName[] = "RenderScript TBAA";
52
53using namespace bcc;
54
55namespace {
56
57static const bool gEnableRsTbaa = true;
58
59/* RSKernelExpandPass - This pass operates on functions that are able
60 * to be called via rsForEach(), "foreach_<NAME>", or
61 * "reduce_<NAME>". We create an inner loop for the function to be
62 * invoked over the appropriate data cells of the input/output
63 * allocations (adjusting other relevant parameters as we go). We
64 * support doing this for any forEach or reduce style compute
65 * kernels. The new function name is the original function name
66 * followed by ".expand". Note that we still generate code for the
67 * original function.
68 */
69class RSKernelExpandPass : public llvm::ModulePass {
70public:
71  static char ID;
72
73private:
74  static const size_t RS_KERNEL_INPUT_LIMIT = 8; // see frameworks/base/libs/rs/cpu_ref/rsCpuCoreRuntime.h
75
76  typedef std::unordered_set<llvm::Function *> FunctionSet;
77
78  enum RsLaunchDimensionsField {
79    RsLaunchDimensionsFieldX,
80    RsLaunchDimensionsFieldY,
81    RsLaunchDimensionsFieldZ,
82    RsLaunchDimensionsFieldLod,
83    RsLaunchDimensionsFieldFace,
84    RsLaunchDimensionsFieldArray,
85
86    RsLaunchDimensionsFieldCount
87  };
88
89  enum RsExpandKernelDriverInfoPfxField {
90    RsExpandKernelDriverInfoPfxFieldInPtr,
91    RsExpandKernelDriverInfoPfxFieldInStride,
92    RsExpandKernelDriverInfoPfxFieldInLen,
93    RsExpandKernelDriverInfoPfxFieldOutPtr,
94    RsExpandKernelDriverInfoPfxFieldOutStride,
95    RsExpandKernelDriverInfoPfxFieldOutLen,
96    RsExpandKernelDriverInfoPfxFieldDim,
97    RsExpandKernelDriverInfoPfxFieldCurrent,
98    RsExpandKernelDriverInfoPfxFieldUsr,
99    RsExpandKernelDriverInfoPfxFieldUsLenr,
100
101    RsExpandKernelDriverInfoPfxFieldCount
102  };
103
104  llvm::Module *Module;
105  llvm::LLVMContext *Context;
106
107  /*
108   * Pointers to LLVM type information for the the function signatures
109   * for expanded functions. These must be re-calculated for each module
110   * the pass is run on.
111   */
112  llvm::FunctionType *ExpandedForEachType, *ExpandedReduceType;
113  llvm::Type *RsExpandKernelDriverInfoPfxTy;
114
115  uint32_t mExportForEachCount;
116  const char **mExportForEachNameList;
117  const uint32_t *mExportForEachSignatureList;
118
119  uint32_t mExportReduceCount;
120  const char **mExportReduceNameList;
121
122  // Turns on optimization of allocation stride values.
123  bool mEnableStepOpt;
124
125  uint32_t getRootSignature(llvm::Function *Function) {
126    const llvm::NamedMDNode *ExportForEachMetadata =
127        Module->getNamedMetadata("#rs_export_foreach");
128
129    if (!ExportForEachMetadata) {
130      llvm::SmallVector<llvm::Type*, 8> RootArgTys;
131      for (llvm::Function::arg_iterator B = Function->arg_begin(),
132                                        E = Function->arg_end();
133           B != E;
134           ++B) {
135        RootArgTys.push_back(B->getType());
136      }
137
138      // For pre-ICS bitcode, we may not have signature information. In that
139      // case, we use the size of the RootArgTys to select the number of
140      // arguments.
141      return (1 << RootArgTys.size()) - 1;
142    }
143
144    if (ExportForEachMetadata->getNumOperands() == 0) {
145      return 0;
146    }
147
148    bccAssert(ExportForEachMetadata->getNumOperands() > 0);
149
150    // We only handle the case for legacy root() functions here, so this is
151    // hard-coded to look at only the first such function.
152    llvm::MDNode *SigNode = ExportForEachMetadata->getOperand(0);
153    if (SigNode != nullptr && SigNode->getNumOperands() == 1) {
154      llvm::Metadata *SigMD = SigNode->getOperand(0);
155      if (llvm::MDString *SigS = llvm::dyn_cast<llvm::MDString>(SigMD)) {
156        llvm::StringRef SigString = SigS->getString();
157        uint32_t Signature = 0;
158        if (SigString.getAsInteger(10, Signature)) {
159          ALOGE("Non-integer signature value '%s'", SigString.str().c_str());
160          return 0;
161        }
162        return Signature;
163      }
164    }
165
166    return 0;
167  }
168
169  bool isStepOptSupported(llvm::Type *AllocType) {
170
171    llvm::PointerType *PT = llvm::dyn_cast<llvm::PointerType>(AllocType);
172    llvm::Type *VoidPtrTy = llvm::Type::getInt8PtrTy(*Context);
173
174    if (mEnableStepOpt) {
175      return false;
176    }
177
178    if (AllocType == VoidPtrTy) {
179      return false;
180    }
181
182    if (!PT) {
183      return false;
184    }
185
186    // remaining conditions are 64-bit only
187    if (VoidPtrTy->getPrimitiveSizeInBits() == 32) {
188      return true;
189    }
190
191    // coerce suggests an upconverted struct type, which we can't support
192    if (AllocType->getStructName().find("coerce") != llvm::StringRef::npos) {
193      return false;
194    }
195
196    // 2xi64 and i128 suggest an upconverted struct type, which are also unsupported
197    llvm::Type *V2xi64Ty = llvm::VectorType::get(llvm::Type::getInt64Ty(*Context), 2);
198    llvm::Type *Int128Ty = llvm::Type::getIntNTy(*Context, 128);
199    if (AllocType == V2xi64Ty || AllocType == Int128Ty) {
200      return false;
201    }
202
203    return true;
204  }
205
206  // Get the actual value we should use to step through an allocation.
207  //
208  // Normally the value we use to step through an allocation is given to us by
209  // the driver. However, for certain primitive data types, we can derive an
210  // integer constant for the step value. We use this integer constant whenever
211  // possible to allow further compiler optimizations to take place.
212  //
213  // DL - Target Data size/layout information.
214  // T - Type of allocation (should be a pointer).
215  // OrigStep - Original step increment (root.expand() input from driver).
216  llvm::Value *getStepValue(llvm::DataLayout *DL, llvm::Type *AllocType,
217                            llvm::Value *OrigStep) {
218    bccAssert(DL);
219    bccAssert(AllocType);
220    bccAssert(OrigStep);
221    llvm::PointerType *PT = llvm::dyn_cast<llvm::PointerType>(AllocType);
222    if (isStepOptSupported(AllocType)) {
223      llvm::Type *ET = PT->getElementType();
224      uint64_t ETSize = DL->getTypeAllocSize(ET);
225      llvm::Type *Int32Ty = llvm::Type::getInt32Ty(*Context);
226      return llvm::ConstantInt::get(Int32Ty, ETSize);
227    } else {
228      return OrigStep;
229    }
230  }
231
232  /// Builds the types required by the pass for the given context.
233  void buildTypes(void) {
234    // Create the RsLaunchDimensionsTy and RsExpandKernelDriverInfoPfxTy structs.
235
236    llvm::Type *Int8Ty                   = llvm::Type::getInt8Ty(*Context);
237    llvm::Type *Int8PtrTy                = Int8Ty->getPointerTo();
238    llvm::Type *Int8PtrArrayInputLimitTy = llvm::ArrayType::get(Int8PtrTy, RS_KERNEL_INPUT_LIMIT);
239    llvm::Type *Int32Ty                  = llvm::Type::getInt32Ty(*Context);
240    llvm::Type *Int32ArrayInputLimitTy   = llvm::ArrayType::get(Int32Ty, RS_KERNEL_INPUT_LIMIT);
241    llvm::Type *VoidPtrTy                = llvm::Type::getInt8PtrTy(*Context);
242    llvm::Type *Int32Array4Ty            = llvm::ArrayType::get(Int32Ty, 4);
243
244    /* Defined in frameworks/base/libs/rs/cpu_ref/rsCpuCore.h:
245     *
246     * struct RsLaunchDimensions {
247     *   uint32_t x;
248     *   uint32_t y;
249     *   uint32_t z;
250     *   uint32_t lod;
251     *   uint32_t face;
252     *   uint32_t array[4];
253     * };
254     */
255    llvm::SmallVector<llvm::Type*, RsLaunchDimensionsFieldCount> RsLaunchDimensionsTypes;
256    RsLaunchDimensionsTypes.push_back(Int32Ty);       // uint32_t x
257    RsLaunchDimensionsTypes.push_back(Int32Ty);       // uint32_t y
258    RsLaunchDimensionsTypes.push_back(Int32Ty);       // uint32_t z
259    RsLaunchDimensionsTypes.push_back(Int32Ty);       // uint32_t lod
260    RsLaunchDimensionsTypes.push_back(Int32Ty);       // uint32_t face
261    RsLaunchDimensionsTypes.push_back(Int32Array4Ty); // uint32_t array[4]
262    llvm::StructType *RsLaunchDimensionsTy =
263        llvm::StructType::create(RsLaunchDimensionsTypes, "RsLaunchDimensions");
264
265    /* Defined as the beginning of RsExpandKernelDriverInfo in frameworks/base/libs/rs/cpu_ref/rsCpuCoreRuntime.h:
266     *
267     * struct RsExpandKernelDriverInfoPfx {
268     *     const uint8_t *inPtr[RS_KERNEL_INPUT_LIMIT];
269     *     uint32_t inStride[RS_KERNEL_INPUT_LIMIT];
270     *     uint32_t inLen;
271     *
272     *     uint8_t *outPtr[RS_KERNEL_INPUT_LIMIT];
273     *     uint32_t outStride[RS_KERNEL_INPUT_LIMIT];
274     *     uint32_t outLen;
275     *
276     *     // Dimension of the launch
277     *     RsLaunchDimensions dim;
278     *
279     *     // The walking iterator of the launch
280     *     RsLaunchDimensions current;
281     *
282     *     const void *usr;
283     *     uint32_t usrLen;
284     *
285     *     // Items below this line are not used by the compiler and can be change in the driver.
286     *     // So the compiler must assume there are an unknown number of fields of unknown type
287     *     // beginning here.
288     * };
289     *
290     * The name "RsExpandKernelDriverInfoPfx" is known to RSInvariantPass (RSInvariant.cpp).
291     */
292    llvm::SmallVector<llvm::Type*, RsExpandKernelDriverInfoPfxFieldCount> RsExpandKernelDriverInfoPfxTypes;
293    RsExpandKernelDriverInfoPfxTypes.push_back(Int8PtrArrayInputLimitTy); // const uint8_t *inPtr[RS_KERNEL_INPUT_LIMIT]
294    RsExpandKernelDriverInfoPfxTypes.push_back(Int32ArrayInputLimitTy);   // uint32_t inStride[RS_KERNEL_INPUT_LIMIT]
295    RsExpandKernelDriverInfoPfxTypes.push_back(Int32Ty);                  // uint32_t inLen
296    RsExpandKernelDriverInfoPfxTypes.push_back(Int8PtrArrayInputLimitTy); // uint8_t *outPtr[RS_KERNEL_INPUT_LIMIT]
297    RsExpandKernelDriverInfoPfxTypes.push_back(Int32ArrayInputLimitTy);   // uint32_t outStride[RS_KERNEL_INPUT_LIMIT]
298    RsExpandKernelDriverInfoPfxTypes.push_back(Int32Ty);                  // uint32_t outLen
299    RsExpandKernelDriverInfoPfxTypes.push_back(RsLaunchDimensionsTy);     // RsLaunchDimensions dim
300    RsExpandKernelDriverInfoPfxTypes.push_back(RsLaunchDimensionsTy);     // RsLaunchDimensions current
301    RsExpandKernelDriverInfoPfxTypes.push_back(VoidPtrTy);                // const void *usr
302    RsExpandKernelDriverInfoPfxTypes.push_back(Int32Ty);                  // uint32_t usrLen
303    RsExpandKernelDriverInfoPfxTy =
304        llvm::StructType::create(RsExpandKernelDriverInfoPfxTypes, "RsExpandKernelDriverInfoPfx");
305
306    // Create the function type for expanded kernels.
307    llvm::Type *VoidTy = llvm::Type::getVoidTy(*Context);
308
309    llvm::Type *RsExpandKernelDriverInfoPfxPtrTy = RsExpandKernelDriverInfoPfxTy->getPointerTo();
310    // void (const RsExpandKernelDriverInfoPfxTy *p, uint32_t x1, uint32_t x2, uint32_t outstep)
311    ExpandedForEachType = llvm::FunctionType::get(VoidTy,
312        {RsExpandKernelDriverInfoPfxPtrTy, Int32Ty, Int32Ty, Int32Ty}, false);
313
314    // void (void *inBuf, void *outBuf, uint32_t len)
315    ExpandedReduceType = llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy, Int32Ty}, false);
316  }
317
318  /// @brief Create skeleton of the expanded foreach kernel.
319  ///
320  /// This creates a function with the following signature:
321  ///
322  ///   void (const RsForEachStubParamStruct *p, uint32_t x1, uint32_t x2,
323  ///         uint32_t outstep)
324  ///
325  llvm::Function *createEmptyExpandedForEachKernel(llvm::StringRef OldName) {
326    llvm::Function *ExpandedFunction =
327      llvm::Function::Create(ExpandedForEachType,
328                             llvm::GlobalValue::ExternalLinkage,
329                             OldName + ".expand", Module);
330    bccAssert(ExpandedFunction->arg_size() == kNumExpandedForeachParams);
331    llvm::Function::arg_iterator AI = ExpandedFunction->arg_begin();
332    (AI++)->setName("p");
333    (AI++)->setName("x1");
334    (AI++)->setName("x2");
335    (AI++)->setName("arg_outstep");
336    llvm::BasicBlock *Begin = llvm::BasicBlock::Create(*Context, "Begin",
337                                                       ExpandedFunction);
338    llvm::IRBuilder<> Builder(Begin);
339    Builder.CreateRetVoid();
340    return ExpandedFunction;
341  }
342
343  // Create skeleton of the expanded reduce kernel.
344  //
345  // This creates a function with the following signature:
346  //
347  //   void @func.expand(i8* nocapture %inBuf, i8* nocapture %outBuf, i32 len)
348  //
349  llvm::Function *createEmptyExpandedReduceKernel(llvm::StringRef OldName) {
350    llvm::Function *ExpandedFunction =
351      llvm::Function::Create(ExpandedReduceType,
352                             llvm::GlobalValue::ExternalLinkage,
353                             OldName + ".expand", Module);
354    bccAssert(ExpandedFunction->arg_size() == kNumExpandedReduceParams);
355
356    llvm::Function::arg_iterator AI = ExpandedFunction->arg_begin();
357
358    using llvm::Attribute;
359
360    llvm::Argument *InBuf = &(*AI++);
361    InBuf->setName("inBuf");
362    InBuf->addAttr(llvm::AttributeSet::get(*Context, InBuf->getArgNo() + 1, llvm::makeArrayRef(Attribute::NoCapture)));
363
364    llvm::Argument *OutBuf = &(*AI++);
365    OutBuf->setName("outBuf");
366    OutBuf->addAttr(llvm::AttributeSet::get(*Context, OutBuf->getArgNo() + 1, llvm::makeArrayRef(Attribute::NoCapture)));
367
368    (AI++)->setName("len");
369
370    llvm::BasicBlock *Begin = llvm::BasicBlock::Create(*Context, "Begin",
371                                                       ExpandedFunction);
372    llvm::IRBuilder<> Builder(Begin);
373    Builder.CreateRetVoid();
374
375    return ExpandedFunction;
376  }
377
378  // Create skeleton of a general reduce kernel's expanded accumulator.
379  //
380  // This creates a function with the following signature:
381  //
382  //  void @func.expand(%RsExpandKernelDriverInfoPfx* nocapture %p,
383  //                    i32 %x1, i32 %x2, accumType* nocapture %accum)
384  //
385  llvm::Function *createEmptyExpandedReduceNewAccumulator(llvm::StringRef OldName,
386                                                          llvm::Type *AccumArgTy) {
387    llvm::Type *Int32Ty = llvm::Type::getInt32Ty(*Context);
388    llvm::Type *VoidTy = llvm::Type::getVoidTy(*Context);
389    llvm::FunctionType *ExpandedReduceNewAccumulatorType =
390        llvm::FunctionType::get(VoidTy,
391                                {RsExpandKernelDriverInfoPfxTy->getPointerTo(),
392                                 Int32Ty, Int32Ty, AccumArgTy}, false);
393    llvm::Function *FnExpandedAccumulator =
394      llvm::Function::Create(ExpandedReduceNewAccumulatorType,
395                             llvm::GlobalValue::ExternalLinkage,
396                             OldName + ".expand", Module);
397    bccAssert(FnExpandedAccumulator->arg_size() == kNumExpandedReduceNewAccumulatorParams);
398
399    llvm::Function::arg_iterator AI = FnExpandedAccumulator->arg_begin();
400
401    using llvm::Attribute;
402
403    llvm::Argument *Arg_p = &(*AI++);
404    Arg_p->setName("p");
405    Arg_p->addAttr(llvm::AttributeSet::get(*Context, Arg_p->getArgNo() + 1,
406                                           llvm::makeArrayRef(Attribute::NoCapture)));
407
408    llvm::Argument *Arg_x1 = &(*AI++);
409    Arg_x1->setName("x1");
410
411    llvm::Argument *Arg_x2 = &(*AI++);
412    Arg_x2->setName("x2");
413
414    llvm::Argument *Arg_accum = &(*AI++);
415    Arg_accum->setName("accum");
416    Arg_accum->addAttr(llvm::AttributeSet::get(*Context, Arg_accum->getArgNo() + 1,
417                                               llvm::makeArrayRef(Attribute::NoCapture)));
418
419    llvm::BasicBlock *Begin = llvm::BasicBlock::Create(*Context, "Begin",
420                                                       FnExpandedAccumulator);
421    llvm::IRBuilder<> Builder(Begin);
422    Builder.CreateRetVoid();
423
424    return FnExpandedAccumulator;
425  }
426
427  /// @brief Create an empty loop
428  ///
429  /// Create a loop of the form:
430  ///
431  /// for (i = LowerBound; i < UpperBound; i++)
432  ///   ;
433  ///
434  /// After the loop has been created, the builder is set such that
435  /// instructions can be added to the loop body.
436  ///
437  /// @param Builder The builder to use to build this loop. The current
438  ///                position of the builder is the position the loop
439  ///                will be inserted.
440  /// @param LowerBound The first value of the loop iterator
441  /// @param UpperBound The maximal value of the loop iterator
442  /// @param LoopIV A reference that will be set to the loop iterator.
443  /// @return The BasicBlock that will be executed after the loop.
444  llvm::BasicBlock *createLoop(llvm::IRBuilder<> &Builder,
445                               llvm::Value *LowerBound,
446                               llvm::Value *UpperBound,
447                               llvm::Value **LoopIV) {
448    bccAssert(LowerBound->getType() == UpperBound->getType());
449
450    llvm::BasicBlock *CondBB, *AfterBB, *HeaderBB;
451    llvm::Value *Cond, *IVNext, *IV, *IVVar;
452
453    CondBB = Builder.GetInsertBlock();
454    AfterBB = llvm::SplitBlock(CondBB, &*Builder.GetInsertPoint(), nullptr, nullptr);
455    HeaderBB = llvm::BasicBlock::Create(*Context, "Loop", CondBB->getParent());
456
457    CondBB->getTerminator()->eraseFromParent();
458    Builder.SetInsertPoint(CondBB);
459
460    // decltype(LowerBound) *ivvar = alloca(sizeof(int))
461    // *ivvar = LowerBound
462    IVVar = Builder.CreateAlloca(LowerBound->getType(), nullptr, BCC_INDEX_VAR_NAME);
463    Builder.CreateStore(LowerBound, IVVar);
464
465    // if (LowerBound < Upperbound)
466    //   goto LoopHeader
467    // else
468    //   goto AfterBB
469    Cond = Builder.CreateICmpULT(LowerBound, UpperBound);
470    Builder.CreateCondBr(Cond, HeaderBB, AfterBB);
471
472    // LoopHeader:
473    //   iv = *ivvar
474    //   <insertion point here>
475    //   iv.next = iv + 1
476    //   *ivvar = iv.next
477    //   if (iv.next < Upperbound)
478    //     goto LoopHeader
479    //   else
480    //     goto AfterBB
481    // AfterBB:
482    Builder.SetInsertPoint(HeaderBB);
483    IV = Builder.CreateLoad(IVVar, "X");
484    IVNext = Builder.CreateNUWAdd(IV, Builder.getInt32(1));
485    Builder.CreateStore(IVNext, IVVar);
486    Cond = Builder.CreateICmpULT(IVNext, UpperBound);
487    Builder.CreateCondBr(Cond, HeaderBB, AfterBB);
488    AfterBB->setName("Exit");
489    Builder.SetInsertPoint(llvm::cast<llvm::Instruction>(IVNext));
490
491    // Record information about this loop.
492    *LoopIV = IV;
493    return AfterBB;
494  }
495
496  // Finish building the outgoing argument list for calling a ForEach-able function.
497  //
498  // ArgVector - on input, the non-special arguments
499  //             on output, the non-special arguments combined with the special arguments
500  //               from SpecialArgVector
501  // SpecialArgVector - special arguments (from ExpandSpecialArguments())
502  // SpecialArgContextIdx - return value of ExpandSpecialArguments()
503  //                          (position of context argument in SpecialArgVector)
504  // CalleeFunction - the ForEach-able function being called
505  // Builder - for inserting code into the caller function
506  template<unsigned int ArgVectorLen, unsigned int SpecialArgVectorLen>
507  void finishArgList(      llvm::SmallVector<llvm::Value *, ArgVectorLen>        &ArgVector,
508                     const llvm::SmallVector<llvm::Value *, SpecialArgVectorLen> &SpecialArgVector,
509                     const int SpecialArgContextIdx,
510                     const llvm::Function &CalleeFunction,
511                     llvm::IRBuilder<> &CallerBuilder) {
512    /* The context argument (if any) is a pointer to an opaque user-visible type that differs from
513     * the RsExpandKernelDriverInfoPfx type used in the function we are generating (although the
514     * two types represent the same thing).  Therefore, we must introduce a pointer cast when
515     * generating a call to the kernel function.
516     */
517    const int ArgContextIdx =
518        SpecialArgContextIdx >= 0 ? (ArgVector.size() + SpecialArgContextIdx) : SpecialArgContextIdx;
519    ArgVector.append(SpecialArgVector.begin(), SpecialArgVector.end());
520    if (ArgContextIdx >= 0) {
521      llvm::Type *ContextArgType = nullptr;
522      int ArgIdx = ArgContextIdx;
523      for (const auto &Arg : CalleeFunction.getArgumentList()) {
524        if (!ArgIdx--) {
525          ContextArgType = Arg.getType();
526          break;
527        }
528      }
529      bccAssert(ContextArgType);
530      ArgVector[ArgContextIdx] = CallerBuilder.CreatePointerCast(ArgVector[ArgContextIdx], ContextArgType);
531    }
532  }
533
534  // GEPHelper() returns a SmallVector of values suitable for passing
535  // to IRBuilder::CreateGEP(), and SmallGEPIndices is a typedef for
536  // the returned data type. It is sized so that the SmallVector
537  // returned by GEPHelper() never needs to do a heap allocation for
538  // any list of GEP indices it encounters in the code.
539  typedef llvm::SmallVector<llvm::Value *, 3> SmallGEPIndices;
540
541  // Helper for turning a list of constant integer GEP indices into a
542  // SmallVector of llvm::Value*. The return value is suitable for
543  // passing to a GetElementPtrInst constructor or IRBuilder::CreateGEP().
544  //
545  // Inputs:
546  //   I32Args should be integers which represent the index arguments
547  //   to a GEP instruction.
548  //
549  // Returns:
550  //   Returns a SmallVector of ConstantInts.
551  SmallGEPIndices GEPHelper(const std::initializer_list<int32_t> I32Args) {
552    SmallGEPIndices Out(I32Args.size());
553    llvm::IntegerType *I32Ty = llvm::Type::getInt32Ty(*Context);
554    std::transform(I32Args.begin(), I32Args.end(), Out.begin(),
555                   [I32Ty](int32_t Arg) { return llvm::ConstantInt::get(I32Ty, Arg); });
556    return Out;
557  }
558
559public:
560  RSKernelExpandPass(bool pEnableStepOpt = true)
561      : ModulePass(ID), Module(nullptr), Context(nullptr),
562        mEnableStepOpt(pEnableStepOpt) {
563
564  }
565
566  virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
567    // This pass does not use any other analysis passes, but it does
568    // add/wrap the existing functions in the module (thus altering the CFG).
569  }
570
571  // Build contribution to outgoing argument list for calling a
572  // ForEach-able function or a general reduction accumulator
573  // function, based on the special parameters of that function.
574  //
575  // Signature - metadata bits for the signature of the callee
576  // X, Arg_p - values derived directly from expanded function,
577  //            suitable for computing arguments for the callee
578  // CalleeArgs - contribution is accumulated here
579  // Bump - invoked once for each contributed outgoing argument
580  // LoopHeaderInsertionPoint - an Instruction in the loop header, before which
581  //                            this function can insert loop-invariant loads
582  //
583  // Return value is the (zero-based) position of the context (Arg_p)
584  // argument in the CalleeArgs vector, or a negative value if the
585  // context argument is not placed in the CalleeArgs vector.
586  int ExpandSpecialArguments(uint32_t Signature,
587                             llvm::Value *X,
588                             llvm::Value *Arg_p,
589                             llvm::IRBuilder<> &Builder,
590                             llvm::SmallVector<llvm::Value*, 8> &CalleeArgs,
591                             std::function<void ()> Bump,
592                             llvm::Instruction *LoopHeaderInsertionPoint) {
593
594    bccAssert(CalleeArgs.empty());
595
596    int Return = -1;
597    if (bcinfo::MetadataExtractor::hasForEachSignatureCtxt(Signature)) {
598      CalleeArgs.push_back(Arg_p);
599      Bump();
600      Return = CalleeArgs.size() - 1;
601    }
602
603    if (bcinfo::MetadataExtractor::hasForEachSignatureX(Signature)) {
604      CalleeArgs.push_back(X);
605      Bump();
606    }
607
608    if (bcinfo::MetadataExtractor::hasForEachSignatureY(Signature) ||
609        bcinfo::MetadataExtractor::hasForEachSignatureZ(Signature)) {
610      bccAssert(LoopHeaderInsertionPoint);
611
612      // Y and Z are loop invariant, so they can be hoisted out of the
613      // loop. Set the IRBuilder insertion point to the loop header.
614      auto OldInsertionPoint = Builder.saveIP();
615      Builder.SetInsertPoint(LoopHeaderInsertionPoint);
616
617      if (bcinfo::MetadataExtractor::hasForEachSignatureY(Signature)) {
618        SmallGEPIndices YValueGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldCurrent,
619          RsLaunchDimensionsFieldY}));
620        llvm::Value *YAddr = Builder.CreateInBoundsGEP(Arg_p, YValueGEP, "Y.gep");
621        CalleeArgs.push_back(Builder.CreateLoad(YAddr, "Y"));
622        Bump();
623      }
624
625      if (bcinfo::MetadataExtractor::hasForEachSignatureZ(Signature)) {
626        SmallGEPIndices ZValueGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldCurrent,
627          RsLaunchDimensionsFieldZ}));
628        llvm::Value *ZAddr = Builder.CreateInBoundsGEP(Arg_p, ZValueGEP, "Z.gep");
629        CalleeArgs.push_back(Builder.CreateLoad(ZAddr, "Z"));
630        Bump();
631      }
632
633      Builder.restoreIP(OldInsertionPoint);
634    }
635
636    return Return;
637  }
638
639  // Generate loop-invariant input processing setup code for an expanded
640  // ForEach-able function or an expanded general reduction accumulator
641  // function.
642  //
643  // LoopHeader - block at the end of which the setup code will be inserted
644  // Arg_p - RSKernelDriverInfo pointer passed to the expanded function
645  // TBAAPointer - metadata for marking loads of pointer values out of RSKernelDriverInfo
646  // ArgIter - iterator pointing to first input of the UNexpanded function
647  // NumInputs - number of inputs (NOT number of ARGUMENTS)
648  //
649  // InBufPtrs[] - this function sets each array element to point to the first
650  //               cell of the corresponding input allocation
651  // InStructTempSlots[] - this function sets each array element either to nullptr
652  //                       or to the result of an alloca (for the case where the
653  //                       calling convention dictates that a value must be passed
654  //                       by reference, and so we need a stacked temporary to hold
655  //                       a copy of that value)
656  void ExpandInputsLoopInvariant(llvm::IRBuilder<> &Builder, llvm::BasicBlock *LoopHeader,
657                                 llvm::Value *Arg_p,
658                                 llvm::MDNode *TBAAPointer,
659                                 llvm::Function::arg_iterator ArgIter,
660                                 const size_t NumInputs,
661                                 llvm::SmallVectorImpl<llvm::Value *> &InBufPtrs,
662                                 llvm::SmallVectorImpl<llvm::Value *> &InStructTempSlots) {
663    bccAssert(NumInputs <= RS_KERNEL_INPUT_LIMIT);
664
665    // Extract information about input slots. The work done
666    // here is loop-invariant, so we can hoist the operations out of the loop.
667    auto OldInsertionPoint = Builder.saveIP();
668    Builder.SetInsertPoint(LoopHeader->getTerminator());
669
670    for (size_t InputIndex = 0; InputIndex < NumInputs; ++InputIndex, ArgIter++) {
671      llvm::Type *InType = ArgIter->getType();
672
673      /*
674       * AArch64 calling conventions dictate that structs of sufficient size
675       * get passed by pointer instead of passed by value.  This, combined
676       * with the fact that we don't allow kernels to operate on pointer
677       * data means that if we see a kernel with a pointer parameter we know
678       * that it is a struct input that has been promoted.  As such we don't
679       * need to convert its type to a pointer.  Later we will need to know
680       * to create a temporary copy on the stack, so we save this information
681       * in InStructTempSlots.
682       */
683      if (auto PtrType = llvm::dyn_cast<llvm::PointerType>(InType)) {
684        llvm::Type *ElementType = PtrType->getElementType();
685        InStructTempSlots.push_back(Builder.CreateAlloca(ElementType, nullptr,
686                                                         "input_struct_slot"));
687      } else {
688        InType = InType->getPointerTo();
689        InStructTempSlots.push_back(nullptr);
690      }
691
692      SmallGEPIndices InBufPtrGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldInPtr,
693                                             static_cast<int32_t>(InputIndex)}));
694      llvm::Value    *InBufPtrAddr = Builder.CreateInBoundsGEP(Arg_p, InBufPtrGEP, "input_buf.gep");
695      llvm::LoadInst *InBufPtr = Builder.CreateLoad(InBufPtrAddr, "input_buf");
696      llvm::Value    *CastInBufPtr = Builder.CreatePointerCast(InBufPtr, InType, "casted_in");
697
698      if (gEnableRsTbaa) {
699        InBufPtr->setMetadata("tbaa", TBAAPointer);
700      }
701
702      InBufPtrs.push_back(CastInBufPtr);
703    }
704
705    Builder.restoreIP(OldInsertionPoint);
706  }
707
708  // Generate loop-varying input processing code for an expanded ForEach-able function
709  // or an expanded general reduction accumulator function.  Also, for the call to the
710  // UNexpanded function, collect the portion of the argument list corresponding to the
711  // inputs.
712  //
713  // Arg_x1 - first X coordinate to be processed by the expanded function
714  // TBAAAllocation - metadata for marking loads of input values out of allocations
715  // NumInputs -- number of inputs (NOT number of ARGUMENTS)
716  // InBufPtrs[] - this function consumes the information produced by ExpandInputsLoopInvariant()
717  // InStructTempSlots[] - this function consumes the information produced by ExpandInputsLoopInvariant()
718  // IndVar - value of loop induction variable (X coordinate) for a given loop iteration
719  //
720  // RootArgs - this function sets this to the list of outgoing argument values corresponding
721  //            to the inputs
722  void ExpandInputsBody(llvm::IRBuilder<> &Builder,
723                        llvm::Value *Arg_x1,
724                        llvm::MDNode *TBAAAllocation,
725                        const size_t NumInputs,
726                        const llvm::SmallVectorImpl<llvm::Value *> &InBufPtrs,
727                        const llvm::SmallVectorImpl<llvm::Value *> &InStructTempSlots,
728                        llvm::Value *IndVar,
729                        llvm::SmallVectorImpl<llvm::Value *> &RootArgs) {
730    llvm::Value *Offset = Builder.CreateSub(IndVar, Arg_x1);
731
732    for (size_t Index = 0; Index < NumInputs; ++Index) {
733      llvm::Value *InPtr = Builder.CreateInBoundsGEP(InBufPtrs[Index], Offset);
734      llvm::Value *Input;
735
736      llvm::LoadInst *InputLoad = Builder.CreateLoad(InPtr, "input");
737
738      if (gEnableRsTbaa) {
739        InputLoad->setMetadata("tbaa", TBAAAllocation);
740      }
741
742      if (llvm::Value *TemporarySlot = InStructTempSlots[Index]) {
743        // Pass a pointer to a temporary on the stack, rather than
744        // passing a pointer to the original value. We do not want
745        // the kernel to potentially modify the input data.
746
747        // Note: don't annotate with TBAA, since the kernel might
748        // have its own TBAA annotations for the pointer argument.
749        Builder.CreateStore(InputLoad, TemporarySlot);
750        Input = TemporarySlot;
751      } else {
752        Input = InputLoad;
753      }
754
755      RootArgs.push_back(Input);
756    }
757  }
758
759  /* Performs the actual optimization on a selected function. On success, the
760   * Module will contain a new function of the name "<NAME>.expand" that
761   * invokes <NAME>() in a loop with the appropriate parameters.
762   */
763  bool ExpandOldStyleForEach(llvm::Function *Function, uint32_t Signature) {
764    ALOGV("Expanding ForEach-able Function %s",
765          Function->getName().str().c_str());
766
767    if (!Signature) {
768      Signature = getRootSignature(Function);
769      if (!Signature) {
770        // We couldn't determine how to expand this function based on its
771        // function signature.
772        return false;
773      }
774    }
775
776    llvm::DataLayout DL(Module);
777
778    llvm::Function *ExpandedFunction =
779      createEmptyExpandedForEachKernel(Function->getName());
780
781    /*
782     * Extract the expanded function's parameters.  It is guaranteed by
783     * createEmptyExpandedForEachKernel that there will be four parameters.
784     */
785
786    bccAssert(ExpandedFunction->arg_size() == kNumExpandedForeachParams);
787
788    llvm::Function::arg_iterator ExpandedFunctionArgIter =
789      ExpandedFunction->arg_begin();
790
791    llvm::Value *Arg_p       = &*(ExpandedFunctionArgIter++);
792    llvm::Value *Arg_x1      = &*(ExpandedFunctionArgIter++);
793    llvm::Value *Arg_x2      = &*(ExpandedFunctionArgIter++);
794    llvm::Value *Arg_outstep = &*(ExpandedFunctionArgIter);
795
796    llvm::Value *InStep  = nullptr;
797    llvm::Value *OutStep = nullptr;
798
799    // Construct the actual function body.
800    llvm::IRBuilder<> Builder(&*ExpandedFunction->getEntryBlock().begin());
801
802    // Collect and construct the arguments for the kernel().
803    // Note that we load any loop-invariant arguments before entering the Loop.
804    llvm::Function::arg_iterator FunctionArgIter = Function->arg_begin();
805
806    llvm::Type  *InTy      = nullptr;
807    llvm::Value *InBufPtr = nullptr;
808    if (bcinfo::MetadataExtractor::hasForEachSignatureIn(Signature)) {
809      SmallGEPIndices InStepGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldInStride, 0}));
810      llvm::LoadInst *InStepArg  = Builder.CreateLoad(
811        Builder.CreateInBoundsGEP(Arg_p, InStepGEP, "instep_addr.gep"), "instep_addr");
812
813      InTy = (FunctionArgIter++)->getType();
814      InStep = getStepValue(&DL, InTy, InStepArg);
815
816      InStep->setName("instep");
817
818      SmallGEPIndices InputAddrGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldInPtr, 0}));
819      InBufPtr = Builder.CreateLoad(
820        Builder.CreateInBoundsGEP(Arg_p, InputAddrGEP, "input_buf.gep"), "input_buf");
821    }
822
823    llvm::Type *OutTy = nullptr;
824    llvm::Value *OutBasePtr = nullptr;
825    if (bcinfo::MetadataExtractor::hasForEachSignatureOut(Signature)) {
826      OutTy = (FunctionArgIter++)->getType();
827      OutStep = getStepValue(&DL, OutTy, Arg_outstep);
828      OutStep->setName("outstep");
829      SmallGEPIndices OutBaseGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldOutPtr, 0}));
830      OutBasePtr = Builder.CreateLoad(Builder.CreateInBoundsGEP(Arg_p, OutBaseGEP, "out_buf.gep"));
831    }
832
833    llvm::Value *UsrData = nullptr;
834    if (bcinfo::MetadataExtractor::hasForEachSignatureUsrData(Signature)) {
835      llvm::Type *UsrDataTy = (FunctionArgIter++)->getType();
836      llvm::Value *UsrDataPointerAddr = Builder.CreateStructGEP(nullptr, Arg_p, RsExpandKernelDriverInfoPfxFieldUsr);
837      UsrData = Builder.CreatePointerCast(Builder.CreateLoad(UsrDataPointerAddr), UsrDataTy);
838      UsrData->setName("UsrData");
839    }
840
841    llvm::BasicBlock *LoopHeader = Builder.GetInsertBlock();
842    llvm::Value *IV;
843    createLoop(Builder, Arg_x1, Arg_x2, &IV);
844
845    llvm::SmallVector<llvm::Value*, 8> CalleeArgs;
846    const int CalleeArgsContextIdx = ExpandSpecialArguments(Signature, IV, Arg_p, Builder, CalleeArgs,
847                                                            [&FunctionArgIter]() { FunctionArgIter++; },
848                                                            LoopHeader->getTerminator());
849
850    bccAssert(FunctionArgIter == Function->arg_end());
851
852    // Populate the actual call to kernel().
853    llvm::SmallVector<llvm::Value*, 8> RootArgs;
854
855    llvm::Value *InPtr  = nullptr;
856    llvm::Value *OutPtr = nullptr;
857
858    // Calculate the current input and output pointers
859    //
860    // We always calculate the input/output pointers with a GEP operating on i8
861    // values and only cast at the very end to OutTy. This is because the step
862    // between two values is given in bytes.
863    //
864    // TODO: We could further optimize the output by using a GEP operation of
865    // type 'OutTy' in cases where the element type of the allocation allows.
866    if (OutBasePtr) {
867      llvm::Value *OutOffset = Builder.CreateSub(IV, Arg_x1);
868      OutOffset = Builder.CreateMul(OutOffset, OutStep);
869      OutPtr = Builder.CreateInBoundsGEP(OutBasePtr, OutOffset);
870      OutPtr = Builder.CreatePointerCast(OutPtr, OutTy);
871    }
872
873    if (InBufPtr) {
874      llvm::Value *InOffset = Builder.CreateSub(IV, Arg_x1);
875      InOffset = Builder.CreateMul(InOffset, InStep);
876      InPtr = Builder.CreateInBoundsGEP(InBufPtr, InOffset);
877      InPtr = Builder.CreatePointerCast(InPtr, InTy);
878    }
879
880    if (InPtr) {
881      RootArgs.push_back(InPtr);
882    }
883
884    if (OutPtr) {
885      RootArgs.push_back(OutPtr);
886    }
887
888    if (UsrData) {
889      RootArgs.push_back(UsrData);
890    }
891
892    finishArgList(RootArgs, CalleeArgs, CalleeArgsContextIdx, *Function, Builder);
893
894    Builder.CreateCall(Function, RootArgs);
895
896    return true;
897  }
898
899  /* Expand a pass-by-value foreach kernel.
900   */
901  bool ExpandForEach(llvm::Function *Function, uint32_t Signature) {
902    bccAssert(bcinfo::MetadataExtractor::hasForEachSignatureKernel(Signature));
903    ALOGV("Expanding kernel Function %s", Function->getName().str().c_str());
904
905    // TODO: Refactor this to share functionality with ExpandOldStyleForEach.
906    llvm::DataLayout DL(Module);
907
908    llvm::Function *ExpandedFunction =
909      createEmptyExpandedForEachKernel(Function->getName());
910
911    /*
912     * Extract the expanded function's parameters.  It is guaranteed by
913     * createEmptyExpandedForEachKernel that there will be four parameters.
914     */
915
916    bccAssert(ExpandedFunction->arg_size() == kNumExpandedForeachParams);
917
918    llvm::Function::arg_iterator ExpandedFunctionArgIter =
919      ExpandedFunction->arg_begin();
920
921    llvm::Value *Arg_p       = &*(ExpandedFunctionArgIter++);
922    llvm::Value *Arg_x1      = &*(ExpandedFunctionArgIter++);
923    llvm::Value *Arg_x2      = &*(ExpandedFunctionArgIter++);
924    // Arg_outstep is not used by expanded new-style forEach kernels.
925
926    // Construct the actual function body.
927    llvm::IRBuilder<> Builder(&*ExpandedFunction->getEntryBlock().begin());
928
929    // Create TBAA meta-data.
930    llvm::MDNode *TBAARenderScriptDistinct, *TBAARenderScript,
931                 *TBAAAllocation, *TBAAPointer;
932    llvm::MDBuilder MDHelper(*Context);
933
934    TBAARenderScriptDistinct =
935      MDHelper.createTBAARoot(kRenderScriptTBAARootName);
936    TBAARenderScript = MDHelper.createTBAANode(kRenderScriptTBAANodeName,
937        TBAARenderScriptDistinct);
938    TBAAAllocation = MDHelper.createTBAAScalarTypeNode("allocation",
939                                                       TBAARenderScript);
940    TBAAAllocation = MDHelper.createTBAAStructTagNode(TBAAAllocation,
941                                                      TBAAAllocation, 0);
942    TBAAPointer = MDHelper.createTBAAScalarTypeNode("pointer",
943                                                    TBAARenderScript);
944    TBAAPointer = MDHelper.createTBAAStructTagNode(TBAAPointer, TBAAPointer, 0);
945
946    /*
947     * Collect and construct the arguments for the kernel().
948     *
949     * Note that we load any loop-invariant arguments before entering the Loop.
950     */
951    size_t NumRemainingInputs = Function->arg_size();
952
953    // No usrData parameter on kernels.
954    bccAssert(
955        !bcinfo::MetadataExtractor::hasForEachSignatureUsrData(Signature));
956
957    llvm::Function::arg_iterator ArgIter = Function->arg_begin();
958
959    // Check the return type
960    llvm::Type     *OutTy            = nullptr;
961    llvm::LoadInst *OutBasePtr       = nullptr;
962    llvm::Value    *CastedOutBasePtr = nullptr;
963
964    bool PassOutByPointer = false;
965
966    if (bcinfo::MetadataExtractor::hasForEachSignatureOut(Signature)) {
967      llvm::Type *OutBaseTy = Function->getReturnType();
968
969      if (OutBaseTy->isVoidTy()) {
970        PassOutByPointer = true;
971        OutTy = ArgIter->getType();
972
973        ArgIter++;
974        --NumRemainingInputs;
975      } else {
976        // We don't increment Args, since we are using the actual return type.
977        OutTy = OutBaseTy->getPointerTo();
978      }
979
980      SmallGEPIndices OutBaseGEP(GEPHelper({0, RsExpandKernelDriverInfoPfxFieldOutPtr, 0}));
981      OutBasePtr = Builder.CreateLoad(Builder.CreateInBoundsGEP(Arg_p, OutBaseGEP, "out_buf.gep"));
982
983      if (gEnableRsTbaa) {
984        OutBasePtr->setMetadata("tbaa", TBAAPointer);
985      }
986
987      CastedOutBasePtr = Builder.CreatePointerCast(OutBasePtr, OutTy, "casted_out");
988    }
989
990    llvm::SmallVector<llvm::Value*, 8> InBufPtrs;
991    llvm::SmallVector<llvm::Value*, 8> InStructTempSlots;
992
993    bccAssert(NumRemainingInputs <= RS_KERNEL_INPUT_LIMIT);
994
995    // Create the loop structure.
996    llvm::BasicBlock *LoopHeader = Builder.GetInsertBlock();
997    llvm::Value *IV;
998    createLoop(Builder, Arg_x1, Arg_x2, &IV);
999
1000    llvm::SmallVector<llvm::Value*, 8> CalleeArgs;
1001    const int CalleeArgsContextIdx =
1002      ExpandSpecialArguments(Signature, IV, Arg_p, Builder, CalleeArgs,
1003                             [&NumRemainingInputs]() { --NumRemainingInputs; },
1004                             LoopHeader->getTerminator());
1005
1006    // After ExpandSpecialArguments() gets called, NumRemainingInputs
1007    // counts the number of arguments to the kernel that correspond to
1008    // an array entry from the InPtr field of the DriverInfo
1009    // structure.
1010    const size_t NumInPtrArguments = NumRemainingInputs;
1011
1012    if (NumInPtrArguments > 0) {
1013      ExpandInputsLoopInvariant(Builder, LoopHeader, Arg_p, TBAAPointer, ArgIter, NumInPtrArguments,
1014                                InBufPtrs, InStructTempSlots);
1015    }
1016
1017    // Populate the actual call to kernel().
1018    llvm::SmallVector<llvm::Value*, 8> RootArgs;
1019
1020    // Calculate the current input and output pointers.
1021
1022    // Output
1023
1024    llvm::Value *OutPtr = nullptr;
1025    if (CastedOutBasePtr) {
1026      llvm::Value *OutOffset = Builder.CreateSub(IV, Arg_x1);
1027      OutPtr = Builder.CreateInBoundsGEP(CastedOutBasePtr, OutOffset);
1028
1029      if (PassOutByPointer) {
1030        RootArgs.push_back(OutPtr);
1031      }
1032    }
1033
1034    // Inputs
1035
1036    if (NumInPtrArguments > 0) {
1037      ExpandInputsBody(Builder, Arg_x1, TBAAAllocation, NumInPtrArguments,
1038                       InBufPtrs, InStructTempSlots, IV, RootArgs);
1039    }
1040
1041    finishArgList(RootArgs, CalleeArgs, CalleeArgsContextIdx, *Function, Builder);
1042
1043    llvm::Value *RetVal = Builder.CreateCall(Function, RootArgs);
1044
1045    if (OutPtr && !PassOutByPointer) {
1046      RetVal->setName("call.result");
1047      llvm::StoreInst *Store = Builder.CreateStore(RetVal, OutPtr);
1048      if (gEnableRsTbaa) {
1049        Store->setMetadata("tbaa", TBAAAllocation);
1050      }
1051    }
1052
1053    return true;
1054  }
1055
1056  // Expand a simple reduce-style kernel function.
1057  //
1058  // The input is a kernel which represents a binary operation,
1059  // of the form
1060  //
1061  //   define foo @func(foo %a, foo %b),
1062  //
1063  // (More generally, it can be of the forms
1064  //
1065  //   define void @func(foo* %ret, foo* %a, foo* %b)
1066  //   define void @func(foo* %ret, foo1 %a, foo1 %b)
1067  //   define foo1 @func(foo2 %a, foo2 %b)
1068  //
1069  // as a result of argument / return value conversions. Here, "foo1"
1070  // and "foo2" refer to possibly coerced types, and the coerced
1071  // argument type may be different from the coerced return type. See
1072  // "Note on coercion" below.)
1073  //
1074  // Note also, we do not expect to encounter any case when the
1075  // arguments are promoted to pointers but the return value is
1076  // unpromoted to pointer, e.g.
1077  //
1078  //   define foo1 @func(foo* %a, foo* %b)
1079  //
1080  // and we will throw an assertion in this case.)
1081  //
1082  // The input kernel gets expanded into a kernel of the form
1083  //
1084  //   define void @func.expand(i8* %inBuf, i8* outBuf, i32 len)
1085  //
1086  // which performs a serial reduction of `len` elements from `inBuf`,
1087  // and stores the result into `outBuf`. In pseudocode, @func.expand
1088  // does:
1089  //
1090  //   inArr := (foo *)inBuf;
1091  //   accum := inArr[0];
1092  //   for (i := 1; i < len; ++i) {
1093  //     accum := foo(accum, inArr[i]);
1094  //   }
1095  //   *(foo *)outBuf := accum;
1096  //
1097  // Note on coercion
1098  //
1099  // Both the return value and the argument types may undergo internal
1100  // coercion in clang as part of call lowering. As a result, the
1101  // return value type may differ from the argument type even if the
1102  // types in the RenderScript signaure are the same. For instance, the
1103  // kernel
1104  //
1105  //   int3 add(int3 a, int3 b) { return a + b; }
1106  //
1107  // gets lowered by clang as
1108  //
1109  //   define <3 x i32> @add(<4 x i32> %a.coerce, <4 x i32> %b.coerce)
1110  //
1111  // under AArch64. The details of this process are found in clang,
1112  // lib/CodeGen/TargetInfo.cpp, under classifyArgumentType() and
1113  // classifyReturnType() in ARMABIInfo, AArch64ABIInfo. If the value
1114  // is passed by pointer, then the pointed-to type is not coerced.
1115  //
1116  // Since we lack the original type information, this code does loads
1117  // and stores of allocation data by way of pointers to the coerced
1118  // type.
1119  bool ExpandReduce(llvm::Function *Function) {
1120    bccAssert(Function);
1121
1122    ALOGV("Expanding simple reduce kernel %s", Function->getName().str().c_str());
1123
1124    llvm::DataLayout DL(Module);
1125
1126    // TBAA Metadata
1127    llvm::MDNode *TBAARenderScriptDistinct, *TBAARenderScript, *TBAAAllocation;
1128    llvm::MDBuilder MDHelper(*Context);
1129
1130    TBAARenderScriptDistinct =
1131      MDHelper.createTBAARoot(kRenderScriptTBAARootName);
1132    TBAARenderScript = MDHelper.createTBAANode(kRenderScriptTBAANodeName,
1133        TBAARenderScriptDistinct);
1134    TBAAAllocation = MDHelper.createTBAAScalarTypeNode("allocation",
1135                                                       TBAARenderScript);
1136    TBAAAllocation = MDHelper.createTBAAStructTagNode(TBAAAllocation,
1137                                                      TBAAAllocation, 0);
1138
1139    llvm::Function *ExpandedFunction =
1140      createEmptyExpandedReduceKernel(Function->getName());
1141
1142    // Extract the expanded kernel's parameters.  It is guaranteed by
1143    // createEmptyExpandedReduceKernel that there will be 3 parameters.
1144    auto ExpandedFunctionArgIter = ExpandedFunction->arg_begin();
1145
1146    llvm::Value *Arg_inBuf  = &*(ExpandedFunctionArgIter++);
1147    llvm::Value *Arg_outBuf = &*(ExpandedFunctionArgIter++);
1148    llvm::Value *Arg_len    = &*(ExpandedFunctionArgIter++);
1149
1150    bccAssert(Function->arg_size() == 2 || Function->arg_size() == 3);
1151
1152    // Check if, instead of returning a value, the original kernel has
1153    // a pointer parameter which points to a temporary buffer into
1154    // which the return value gets written.
1155    const bool ReturnValuePointerStyle = (Function->arg_size() == 3);
1156    bccAssert(Function->getReturnType()->isVoidTy() == ReturnValuePointerStyle);
1157
1158    // Check if, instead of being passed by value, the inputs to the
1159    // original kernel are passed by pointer.
1160    auto FirstArgIter = Function->arg_begin();
1161    // The second argument is always an input to the original kernel.
1162    auto SecondArgIter = std::next(FirstArgIter);
1163    const bool InputsPointerStyle = SecondArgIter->getType()->isPointerTy();
1164
1165    // Get the output type (i.e. return type of the original kernel).
1166    llvm::PointerType *OutPtrTy = nullptr;
1167    llvm::Type *OutTy = nullptr;
1168    if (ReturnValuePointerStyle) {
1169      OutPtrTy = llvm::dyn_cast<llvm::PointerType>(FirstArgIter->getType());
1170      bccAssert(OutPtrTy && "Expected a pointer parameter to kernel");
1171      OutTy = OutPtrTy->getElementType();
1172    } else {
1173      OutTy = Function->getReturnType();
1174      bccAssert(!OutTy->isVoidTy());
1175      OutPtrTy = OutTy->getPointerTo();
1176    }
1177
1178    // Get the input type (type of the arguments to the original
1179    // kernel). Some input types are different from the output type,
1180    // due to explicit coercion that the compiler performs when
1181    // lowering the parameters. See "Note on coercion" above.
1182    llvm::PointerType *InPtrTy;
1183    llvm::Type *InTy;
1184    if (InputsPointerStyle) {
1185      InPtrTy = llvm::dyn_cast<llvm::PointerType>(SecondArgIter->getType());
1186      bccAssert(InPtrTy && "Expected a pointer parameter to kernel");
1187      bccAssert(ReturnValuePointerStyle);
1188      bccAssert(std::next(SecondArgIter)->getType() == InPtrTy &&
1189                "Input type mismatch");
1190      InTy = InPtrTy->getElementType();
1191    } else {
1192      InTy = SecondArgIter->getType();
1193      InPtrTy = InTy->getPointerTo();
1194      if (!ReturnValuePointerStyle) {
1195        bccAssert(InTy == FirstArgIter->getType() && "Input type mismatch");
1196      } else {
1197        bccAssert(InTy == std::next(SecondArgIter)->getType() &&
1198                  "Input type mismatch");
1199      }
1200    }
1201
1202    // The input type should take up the same amount of space in
1203    // memory as the output type.
1204    bccAssert(DL.getTypeAllocSize(InTy) == DL.getTypeAllocSize(OutTy));
1205
1206    // Construct the actual function body.
1207    llvm::IRBuilder<> Builder(&*ExpandedFunction->getEntryBlock().begin());
1208
1209    // Cast input and output buffers to appropriate types.
1210    llvm::Value *InBuf = Builder.CreatePointerCast(Arg_inBuf, InPtrTy);
1211    llvm::Value *OutBuf = Builder.CreatePointerCast(Arg_outBuf, OutPtrTy);
1212
1213    // Create a slot to pass temporary results back. This needs to be
1214    // separate from the accumulator slot because the kernel may mark
1215    // the return value slot as noalias.
1216    llvm::Value *ReturnBuf = nullptr;
1217    if (ReturnValuePointerStyle) {
1218      ReturnBuf = Builder.CreateAlloca(OutTy, nullptr, "ret.tmp");
1219    }
1220
1221    // Create a slot to hold the second input if the inputs are passed
1222    // by pointer to the original kernel. We cannot directly pass a
1223    // pointer to the input buffer, because the kernel may modify its
1224    // inputs.
1225    llvm::Value *SecondInputTempBuf = nullptr;
1226    if (InputsPointerStyle) {
1227      SecondInputTempBuf = Builder.CreateAlloca(InTy, nullptr, "in.tmp");
1228    }
1229
1230    // Create a slot to accumulate temporary results, and fill it with
1231    // the first value.
1232    llvm::Value *AccumBuf = Builder.CreateAlloca(OutTy, nullptr, "accum");
1233    // Cast to OutPtrTy before loading, since AccumBuf has type OutPtrTy.
1234    llvm::LoadInst *FirstElementLoad = Builder.CreateLoad(
1235      Builder.CreatePointerCast(InBuf, OutPtrTy));
1236    if (gEnableRsTbaa) {
1237      FirstElementLoad->setMetadata("tbaa", TBAAAllocation);
1238    }
1239    // Memory operations with AccumBuf shouldn't be marked with
1240    // RenderScript TBAA, since this might conflict with TBAA metadata
1241    // in the kernel function when AccumBuf is passed by pointer.
1242    Builder.CreateStore(FirstElementLoad, AccumBuf);
1243
1244    // Loop body
1245
1246    // Create the loop structure. Note that the first input in the input buffer
1247    // has already been accumulated, so that we start at index 1.
1248    llvm::Value *IndVar;
1249    llvm::Value *Start = llvm::ConstantInt::get(Arg_len->getType(), 1);
1250    llvm::BasicBlock *Exit = createLoop(Builder, Start, Arg_len, &IndVar);
1251
1252    llvm::Value *InputPtr = Builder.CreateInBoundsGEP(InBuf, IndVar, "next_input.gep");
1253
1254    // Set up arguments and call the original (unexpanded) kernel.
1255    //
1256    // The original kernel can have at most 3 arguments, which is
1257    // achieved when the signature looks like:
1258    //
1259    //    define void @func(foo* %ret, bar %a, bar %b)
1260    //
1261    // (bar can be one of foo/foo.coerce/foo*).
1262    llvm::SmallVector<llvm::Value *, 3> KernelArgs;
1263
1264    if (ReturnValuePointerStyle) {
1265      KernelArgs.push_back(ReturnBuf);
1266    }
1267
1268    if (InputsPointerStyle) {
1269      bccAssert(ReturnValuePointerStyle);
1270      // Because the return buffer is copied back into the
1271      // accumulator, it's okay if the accumulator is overwritten.
1272      KernelArgs.push_back(AccumBuf);
1273
1274      llvm::LoadInst *InputLoad = Builder.CreateLoad(InputPtr);
1275      if (gEnableRsTbaa) {
1276        InputLoad->setMetadata("tbaa", TBAAAllocation);
1277      }
1278      Builder.CreateStore(InputLoad, SecondInputTempBuf);
1279
1280      KernelArgs.push_back(SecondInputTempBuf);
1281    } else {
1282      // InPtrTy may be different from OutPtrTy (the type of
1283      // AccumBuf), so first cast the accumulator buffer to the
1284      // pointer type corresponding to the input argument type.
1285      KernelArgs.push_back(
1286        Builder.CreateLoad(Builder.CreatePointerCast(AccumBuf, InPtrTy)));
1287
1288      llvm::LoadInst *LoadedArg = Builder.CreateLoad(InputPtr);
1289      if (gEnableRsTbaa) {
1290        LoadedArg->setMetadata("tbaa", TBAAAllocation);
1291      }
1292      KernelArgs.push_back(LoadedArg);
1293    }
1294
1295    llvm::Value *RetVal = Builder.CreateCall(Function, KernelArgs);
1296
1297    const uint64_t ElementSize = DL.getTypeStoreSize(OutTy);
1298    const uint64_t ElementAlign = DL.getABITypeAlignment(OutTy);
1299
1300    // Store the output in the accumulator.
1301    if (ReturnValuePointerStyle) {
1302      Builder.CreateMemCpy(AccumBuf, ReturnBuf, ElementSize, ElementAlign);
1303    } else {
1304      Builder.CreateStore(RetVal, AccumBuf);
1305    }
1306
1307    // Loop exit
1308    Builder.SetInsertPoint(Exit, Exit->begin());
1309
1310    llvm::LoadInst *OutputLoad = Builder.CreateLoad(AccumBuf);
1311    llvm::StoreInst *OutputStore = Builder.CreateStore(OutputLoad, OutBuf);
1312    if (gEnableRsTbaa) {
1313      OutputStore->setMetadata("tbaa", TBAAAllocation);
1314    }
1315
1316    return true;
1317  }
1318
1319  // Certain categories of functions that make up a general
1320  // reduce-style kernel are called directly from the driver with no
1321  // expansion needed.  For a function in such a category, we need to
1322  // promote linkage from static to external, to ensure that the
1323  // function is visible to the driver in the dynamic symbol table.
1324  // This promotion is safe because we don't have any kind of cross
1325  // translation unit linkage model (except for linking against
1326  // RenderScript libraries), so we do not risk name clashes.
1327  bool PromoteReduceNewFunction(const char *Name, FunctionSet &PromotedFunctions) {
1328    if (!Name)  // a presumably-optional function that is not present
1329      return false;
1330
1331    llvm::Function *Fn = Module->getFunction(Name);
1332    bccAssert(Fn != nullptr);
1333    if (PromotedFunctions.insert(Fn).second) {
1334      bccAssert(Fn->getLinkage() == llvm::GlobalValue::InternalLinkage);
1335      Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1336      return true;
1337    }
1338
1339    return false;
1340  }
1341
1342  // Expand the accumulator function for a general reduce-style kernel.
1343  //
1344  // The input is a function of the form
1345  //
1346  //   define void @func(accumType* %accum, foo1 in1[, ... fooN inN] [, special arguments])
1347  //
1348  // where all arguments except the first are the same as for a foreach kernel.
1349  //
1350  // The input accumulator function gets expanded into a function of the form
1351  //
1352  //   define void @func.expand(%RsExpandKernelDriverInfoPfx* %p, i32 %x1, i32 %x2, accumType* %accum)
1353  //
1354  // which performs a serial accumulaion of elements [x1, x2) into *%accum.
1355  //
1356  // In pseudocode, @func.expand does:
1357  //
1358  //   for (i = %x1; i < %x2; ++i) {
1359  //     func(%accum,
1360  //          *((foo1 *)p->inPtr[0] + i)[, ... *((fooN *)p->inPtr[N-1] + i)
1361  //          [, p] [, i] [, p->current.y] [, p->current.z]);
1362  //   }
1363  //
1364  // This is very similar to foreach kernel expansion with no output.
1365  bool ExpandReduceNewAccumulator(llvm::Function *FnAccumulator, uint32_t Signature, size_t NumInputs) {
1366    ALOGV("Expanding accumulator %s for general reduce kernel",
1367          FnAccumulator->getName().str().c_str());
1368
1369    // Create TBAA meta-data.
1370    llvm::MDNode *TBAARenderScriptDistinct, *TBAARenderScript,
1371                 *TBAAAllocation, *TBAAPointer;
1372    llvm::MDBuilder MDHelper(*Context);
1373    TBAARenderScriptDistinct =
1374      MDHelper.createTBAARoot(kRenderScriptTBAARootName);
1375    TBAARenderScript = MDHelper.createTBAANode(kRenderScriptTBAANodeName,
1376        TBAARenderScriptDistinct);
1377    TBAAAllocation = MDHelper.createTBAAScalarTypeNode("allocation",
1378                                                       TBAARenderScript);
1379    TBAAAllocation = MDHelper.createTBAAStructTagNode(TBAAAllocation,
1380                                                      TBAAAllocation, 0);
1381    TBAAPointer = MDHelper.createTBAAScalarTypeNode("pointer",
1382                                                    TBAARenderScript);
1383    TBAAPointer = MDHelper.createTBAAStructTagNode(TBAAPointer, TBAAPointer, 0);
1384
1385    auto AccumulatorArgIter = FnAccumulator->arg_begin();
1386
1387    // Create empty accumulator function.
1388    llvm::Function *FnExpandedAccumulator =
1389        createEmptyExpandedReduceNewAccumulator(FnAccumulator->getName(),
1390                                                (AccumulatorArgIter++)->getType());
1391
1392    // Extract the expanded accumulator's parameters.  It is
1393    // guaranteed by createEmptyExpandedReduceNewAccumulator that
1394    // there will be 4 parameters.
1395    bccAssert(FnExpandedAccumulator->arg_size() == kNumExpandedReduceNewAccumulatorParams);
1396    auto ExpandedAccumulatorArgIter = FnExpandedAccumulator->arg_begin();
1397    llvm::Value *Arg_p     = &*(ExpandedAccumulatorArgIter++);
1398    llvm::Value *Arg_x1    = &*(ExpandedAccumulatorArgIter++);
1399    llvm::Value *Arg_x2    = &*(ExpandedAccumulatorArgIter++);
1400    llvm::Value *Arg_accum = &*(ExpandedAccumulatorArgIter++);
1401
1402    // Construct the actual function body.
1403    llvm::IRBuilder<> Builder(&*FnExpandedAccumulator->getEntryBlock().begin());
1404
1405    // Create the loop structure.
1406    llvm::BasicBlock *LoopHeader = Builder.GetInsertBlock();
1407    llvm::Value *IndVar;
1408    createLoop(Builder, Arg_x1, Arg_x2, &IndVar);
1409
1410    llvm::SmallVector<llvm::Value*, 8> CalleeArgs;
1411    const int CalleeArgsContextIdx =
1412        ExpandSpecialArguments(Signature, IndVar, Arg_p, Builder, CalleeArgs,
1413                               [](){}, LoopHeader->getTerminator());
1414
1415    llvm::SmallVector<llvm::Value*, 8> InBufPtrs;
1416    llvm::SmallVector<llvm::Value*, 8> InStructTempSlots;
1417    ExpandInputsLoopInvariant(Builder, LoopHeader, Arg_p, TBAAPointer, AccumulatorArgIter, NumInputs,
1418                              InBufPtrs, InStructTempSlots);
1419
1420    // Populate the actual call to the original accumulator.
1421    llvm::SmallVector<llvm::Value*, 8> RootArgs;
1422    RootArgs.push_back(Arg_accum);
1423    ExpandInputsBody(Builder, Arg_x1, TBAAAllocation, NumInputs, InBufPtrs, InStructTempSlots,
1424                     IndVar, RootArgs);
1425    finishArgList(RootArgs, CalleeArgs, CalleeArgsContextIdx, *FnAccumulator, Builder);
1426    Builder.CreateCall(FnAccumulator, RootArgs);
1427
1428    return true;
1429  }
1430
1431  // Create a combiner function for a general reduce-style kernel that lacks one,
1432  // by calling the accumulator function.
1433  //
1434  // The accumulator function must be of the form
1435  //
1436  //   define void @accumFn(accumType* %accum, accumType %in)
1437  //
1438  // A combiner function will be generated of the form
1439  //
1440  //   define void @accumFn.combiner(accumType* %accum, accumType* %other) {
1441  //     %1 = load accumType, accumType* %other
1442  //     call void @accumFn(accumType* %accum, accumType %1);
1443  //   }
1444  bool CreateReduceNewCombinerFromAccumulator(llvm::Function *FnAccumulator) {
1445    ALOGV("Creating combiner from accumulator %s for general reduce kernel",
1446          FnAccumulator->getName().str().c_str());
1447
1448    using llvm::Attribute;
1449
1450    bccAssert(FnAccumulator->arg_size() == 2);
1451    auto AccumulatorArgIter = FnAccumulator->arg_begin();
1452    llvm::Value *AccumulatorArg_accum = &*(AccumulatorArgIter++);
1453    llvm::Value *AccumulatorArg_in    = &*(AccumulatorArgIter++);
1454    llvm::Type *AccumulatorArgType = AccumulatorArg_accum->getType();
1455    bccAssert(AccumulatorArgType->isPointerTy());
1456
1457    llvm::Type *VoidTy = llvm::Type::getVoidTy(*Context);
1458    llvm::FunctionType *CombinerType =
1459        llvm::FunctionType::get(VoidTy, { AccumulatorArgType, AccumulatorArgType }, false);
1460    llvm::Function *FnCombiner =
1461        llvm::Function::Create(CombinerType, llvm::GlobalValue::ExternalLinkage,
1462                               nameReduceNewCombinerFromAccumulator(FnAccumulator->getName()),
1463                               Module);
1464
1465    auto CombinerArgIter = FnCombiner->arg_begin();
1466
1467    llvm::Argument *CombinerArg_accum = &(*CombinerArgIter++);
1468    CombinerArg_accum->setName("accum");
1469    CombinerArg_accum->addAttr(llvm::AttributeSet::get(*Context, CombinerArg_accum->getArgNo() + 1,
1470                                                       llvm::makeArrayRef(Attribute::NoCapture)));
1471
1472    llvm::Argument *CombinerArg_other = &(*CombinerArgIter++);
1473    CombinerArg_other->setName("other");
1474    CombinerArg_other->addAttr(llvm::AttributeSet::get(*Context, CombinerArg_other->getArgNo() + 1,
1475                                                       llvm::makeArrayRef(Attribute::NoCapture)));
1476
1477    llvm::BasicBlock *BB = llvm::BasicBlock::Create(*Context, "BB", FnCombiner);
1478    llvm::IRBuilder<> Builder(BB);
1479
1480    if (AccumulatorArg_in->getType()->isPointerTy()) {
1481      // Types of sufficient size get passed by pointer-to-copy rather
1482      // than passed by value.  An accumulator cannot take a pointer
1483      // at the user level; so if we see a pointer here, we know that
1484      // we have a pass-by-pointer-to-copy case.
1485      llvm::Type *ElementType = AccumulatorArg_in->getType()->getPointerElementType();
1486      llvm::Value *TempMem = Builder.CreateAlloca(ElementType, nullptr, "caller_copy");
1487      Builder.CreateStore(Builder.CreateLoad(CombinerArg_other), TempMem);
1488      Builder.CreateCall(FnAccumulator, { CombinerArg_accum, TempMem });
1489    } else {
1490      llvm::Value *TypeAdjustedOther = CombinerArg_other;
1491      if (AccumulatorArgType->getPointerElementType() != AccumulatorArg_in->getType()) {
1492        // Call lowering by frontend has done some type coercion
1493        TypeAdjustedOther = Builder.CreatePointerCast(CombinerArg_other,
1494                                                      AccumulatorArg_in->getType()->getPointerTo(),
1495                                                      "cast");
1496      }
1497      llvm::Value *DerefOther = Builder.CreateLoad(TypeAdjustedOther);
1498      Builder.CreateCall(FnAccumulator, { CombinerArg_accum, DerefOther });
1499    }
1500    Builder.CreateRetVoid();
1501
1502    return true;
1503  }
1504
1505  /// @brief Checks if pointers to allocation internals are exposed
1506  ///
1507  /// This function verifies if through the parameters passed to the kernel
1508  /// or through calls to the runtime library the script gains access to
1509  /// pointers pointing to data within a RenderScript Allocation.
1510  /// If we know we control all loads from and stores to data within
1511  /// RenderScript allocations and if we know the run-time internal accesses
1512  /// are all annotated with RenderScript TBAA metadata, only then we
1513  /// can safely use TBAA to distinguish between generic and from-allocation
1514  /// pointers.
1515  bool allocPointersExposed(llvm::Module &Module) {
1516    // Old style kernel function can expose pointers to elements within
1517    // allocations.
1518    // TODO: Extend analysis to allow simple cases of old-style kernels.
1519    for (size_t i = 0; i < mExportForEachCount; ++i) {
1520      const char *Name = mExportForEachNameList[i];
1521      uint32_t Signature = mExportForEachSignatureList[i];
1522      if (Module.getFunction(Name) &&
1523          !bcinfo::MetadataExtractor::hasForEachSignatureKernel(Signature)) {
1524        return true;
1525      }
1526    }
1527
1528    // Check for library functions that expose a pointer to an Allocation or
1529    // that are not yet annotated with RenderScript-specific tbaa information.
1530    static const std::vector<const char *> Funcs{
1531      // rsGetElementAt(...)
1532      "_Z14rsGetElementAt13rs_allocationj",
1533      "_Z14rsGetElementAt13rs_allocationjj",
1534      "_Z14rsGetElementAt13rs_allocationjjj",
1535
1536      // rsSetElementAt()
1537      "_Z14rsSetElementAt13rs_allocationPvj",
1538      "_Z14rsSetElementAt13rs_allocationPvjj",
1539      "_Z14rsSetElementAt13rs_allocationPvjjj",
1540
1541      // rsGetElementAtYuv_uchar_Y()
1542      "_Z25rsGetElementAtYuv_uchar_Y13rs_allocationjj",
1543
1544      // rsGetElementAtYuv_uchar_U()
1545      "_Z25rsGetElementAtYuv_uchar_U13rs_allocationjj",
1546
1547      // rsGetElementAtYuv_uchar_V()
1548      "_Z25rsGetElementAtYuv_uchar_V13rs_allocationjj",
1549    };
1550
1551    for (auto FI : Funcs) {
1552      llvm::Function *Function = Module.getFunction(FI);
1553
1554      if (!Function) {
1555        ALOGE("Missing run-time function '%s'", FI);
1556        return true;
1557      }
1558
1559      if (Function->getNumUses() > 0) {
1560        return true;
1561      }
1562    }
1563
1564    return false;
1565  }
1566
1567  /// @brief Connect RenderScript TBAA metadata to C/C++ metadata
1568  ///
1569  /// The TBAA metadata used to annotate loads/stores from RenderScript
1570  /// Allocations is generated in a separate TBAA tree with a
1571  /// "RenderScript Distinct TBAA" root node. LLVM does assume may-alias for
1572  /// all nodes in unrelated alias analysis trees. This function makes the
1573  /// "RenderScript TBAA" node (which is parented by the Distinct TBAA root),
1574  /// a subtree of the normal C/C++ TBAA tree aside of normal C/C++ types. With
1575  /// the connected trees every access to an Allocation is resolved to
1576  /// must-alias if compared to a normal C/C++ access.
1577  void connectRenderScriptTBAAMetadata(llvm::Module &Module) {
1578    llvm::MDBuilder MDHelper(*Context);
1579    llvm::MDNode *TBAARenderScriptDistinct =
1580      MDHelper.createTBAARoot("RenderScript Distinct TBAA");
1581    llvm::MDNode *TBAARenderScript = MDHelper.createTBAANode(
1582        "RenderScript TBAA", TBAARenderScriptDistinct);
1583    llvm::MDNode *TBAARoot     = MDHelper.createTBAARoot("Simple C/C++ TBAA");
1584    TBAARenderScript->replaceOperandWith(1, TBAARoot);
1585  }
1586
1587  virtual bool runOnModule(llvm::Module &Module) {
1588    bool Changed  = false;
1589    this->Module  = &Module;
1590    Context = &Module.getContext();
1591
1592    buildTypes();
1593
1594    bcinfo::MetadataExtractor me(&Module);
1595    if (!me.extract()) {
1596      ALOGE("Could not extract metadata from module!");
1597      return false;
1598    }
1599
1600    // Expand forEach_* style kernels.
1601    mExportForEachCount = me.getExportForEachSignatureCount();
1602    mExportForEachNameList = me.getExportForEachNameList();
1603    mExportForEachSignatureList = me.getExportForEachSignatureList();
1604
1605    for (size_t i = 0; i < mExportForEachCount; ++i) {
1606      const char *name = mExportForEachNameList[i];
1607      uint32_t signature = mExportForEachSignatureList[i];
1608      llvm::Function *kernel = Module.getFunction(name);
1609      if (kernel) {
1610        if (bcinfo::MetadataExtractor::hasForEachSignatureKernel(signature)) {
1611          Changed |= ExpandForEach(kernel, signature);
1612          kernel->setLinkage(llvm::GlobalValue::InternalLinkage);
1613        } else if (kernel->getReturnType()->isVoidTy()) {
1614          Changed |= ExpandOldStyleForEach(kernel, signature);
1615          kernel->setLinkage(llvm::GlobalValue::InternalLinkage);
1616        } else {
1617          // There are some graphics root functions that are not
1618          // expanded, but that will be called directly. For those
1619          // functions, we can not set the linkage to internal.
1620        }
1621      }
1622    }
1623
1624    // Expand simple reduce_* style kernels.
1625    mExportReduceCount = me.getExportReduceCount();
1626    mExportReduceNameList = me.getExportReduceNameList();
1627
1628    for (size_t i = 0; i < mExportReduceCount; ++i) {
1629      llvm::Function *kernel = Module.getFunction(mExportReduceNameList[i]);
1630      if (kernel) {
1631        Changed |= ExpandReduce(kernel);
1632      }
1633    }
1634
1635    // Process general reduce_* style functions.
1636    const size_t ExportReduceNewCount = me.getExportReduceNewCount();
1637    const bcinfo::MetadataExtractor::ReduceNew *ExportReduceNewList = me.getExportReduceNewList();
1638    //   Note that functions can be shared between kernels
1639    FunctionSet PromotedFunctions, ExpandedAccumulators, AccumulatorsForCombiners;
1640
1641    for (size_t i = 0; i < ExportReduceNewCount; ++i) {
1642      Changed |= PromoteReduceNewFunction(ExportReduceNewList[i].mInitializerName, PromotedFunctions);
1643      Changed |= PromoteReduceNewFunction(ExportReduceNewList[i].mCombinerName, PromotedFunctions);
1644      Changed |= PromoteReduceNewFunction(ExportReduceNewList[i].mOutConverterName, PromotedFunctions);
1645
1646      // Accumulator
1647      llvm::Function *accumulator = Module.getFunction(ExportReduceNewList[i].mAccumulatorName);
1648      bccAssert(accumulator != nullptr);
1649      if (ExpandedAccumulators.insert(accumulator).second)
1650        Changed |= ExpandReduceNewAccumulator(accumulator,
1651                                              ExportReduceNewList[i].mSignature,
1652                                              ExportReduceNewList[i].mInputCount);
1653      if (!ExportReduceNewList[i].mCombinerName) {
1654        if (AccumulatorsForCombiners.insert(accumulator).second)
1655          Changed |= CreateReduceNewCombinerFromAccumulator(accumulator);
1656      }
1657    }
1658
1659    if (gEnableRsTbaa && !allocPointersExposed(Module)) {
1660      connectRenderScriptTBAAMetadata(Module);
1661    }
1662
1663    return Changed;
1664  }
1665
1666  virtual const char *getPassName() const {
1667    return "forEach_* and reduce_* function expansion";
1668  }
1669
1670}; // end RSKernelExpandPass
1671
1672} // end anonymous namespace
1673
1674char RSKernelExpandPass::ID = 0;
1675static llvm::RegisterPass<RSKernelExpandPass> X("kernelexp", "Kernel Expand Pass");
1676
1677namespace bcc {
1678
1679const char BCC_INDEX_VAR_NAME[] = "rsIndex";
1680
1681llvm::ModulePass *
1682createRSKernelExpandPass(bool pEnableStepOpt) {
1683  return new RSKernelExpandPass(pEnableStepOpt);
1684}
1685
1686} // end namespace bcc
1687