Merge changes from topics 'USAGE_IO_INPUT', 'USAGE_IO_OUTPUT'

* changes:
  Update C++ API (libRSCpp.so) with the corresponding AllocationGetSurface driver implementation change
  Implement USAGE_IO_INPUT related functions on top of NDK.
  Implement USAGE_IO_OUTPUT related methods on top of NDK.
diff --git a/rsov/compiler/Android.mk b/rsov/compiler/Android.mk
index 0b03c45..d78adfe 100644
--- a/rsov/compiler/Android.mk
+++ b/rsov/compiler/Android.mk
@@ -29,7 +29,6 @@
   GlobalAllocSPIRITPass.cpp \
   GlobalMergePass.cpp \
   InlinePreparationPass.cpp \
-  KernelSignature.cpp \
   RemoveNonkernelsPass.cpp \
   RSAllocationUtils.cpp \
   RSSPIRVWriter.cpp \
diff --git a/rsov/compiler/GlobalAllocPass.cpp b/rsov/compiler/GlobalAllocPass.cpp
index 0a7a3a3..ef0b020 100644
--- a/rsov/compiler/GlobalAllocPass.cpp
+++ b/rsov/compiler/GlobalAllocPass.cpp
@@ -16,18 +16,13 @@
 
 #include "GlobalAllocPass.h"
 
-#include "RSAllocationUtils.h"
-
-#include "llvm/IR/Attributes.h"
-#include "llvm/IR/Constants.h"
-#include "llvm/IR/DataLayout.h"
 #include "llvm/IR/GlobalVariable.h"
-#include "llvm/IR/Instructions.h"
 #include "llvm/IR/Module.h"
-#include "llvm/IR/PassManager.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/Debug.h"
 
+#include "RSAllocationUtils.h"
+
 #define DEBUG_TYPE "rs2spirv-global-alloc"
 
 using namespace llvm;
@@ -35,6 +30,19 @@
 namespace rs2spirv {
 
 namespace {
+bool collectGlobalAllocs(Module &M,
+                         SmallVectorImpl<GlobalVariable *> &GlobalAllocs) {
+  for (auto &GV : M.globals()) {
+    if (!isRSAllocation(GV))
+      continue;
+
+    DEBUG(GV.dump());
+    GlobalAllocs.push_back(&GV);
+  }
+
+  return !GlobalAllocs.empty();
+}
+
 //
 // This pass would enumerate used global rs_allocations (TBD) and
 // lowers calls to accessors of the following type:
@@ -79,25 +87,43 @@
     DEBUG(dbgs() << "RS2SPIRVGlobalAllocPass end\n");
     return true;
   }
+};
 
-private:
-  bool collectGlobalAllocs(Module &M,
-                           SmallVectorImpl<GlobalVariable *> &GlobalAllocs) {
-    for (auto &GV : M.globals()) {
-      if (!isRSAllocation(GV))
-        continue;
+// A simple pass to remove all global allocations forcibly
+class RemoveAllGlobalAllocPass : public ModulePass {
+public:
+  static char ID;
+  RemoveAllGlobalAllocPass() : ModulePass(ID) {}
+  const char *getPassName() const override {
+    return "RemoveAllGlobalAllocPass";
+  }
 
-      DEBUG(GV.dump());
-      GlobalAllocs.push_back(&GV);
+  bool runOnModule(Module &M) override {
+    DEBUG(dbgs() << "RemoveAllGlobalAllocPass\n");
+    DEBUG(M.dump());
+
+    SmallVector<GlobalVariable *, 8> GlobalAllocs;
+    const bool CollectRes = collectGlobalAllocs(M, GlobalAllocs);
+    if (!CollectRes)
+      return false; // Module not modified.
+    // Remove global allocations
+    for (auto *G : GlobalAllocs) {
+      G->eraseFromParent();
     }
-
-    return !GlobalAllocs.empty();
+    DEBUG(dbgs() << "RemoveAllGlobalAllocPass end\n");
+    DEBUG(M.dump());
+    // Return true, as the pass modifies module.
+    return true;
   }
 };
+
 } // namespace
-
 char GlobalAllocPass::ID = 0;
+char RemoveAllGlobalAllocPass::ID = 0;
 
+ModulePass *createRemoveAllGlobalAllocPass() {
+  return new RemoveAllGlobalAllocPass();
+}
 ModulePass *createGlobalAllocPass() { return new GlobalAllocPass(); }
 
 } // namespace rs2spirv
diff --git a/rsov/compiler/GlobalAllocPass.h b/rsov/compiler/GlobalAllocPass.h
index dc39f13..9312c21 100644
--- a/rsov/compiler/GlobalAllocPass.h
+++ b/rsov/compiler/GlobalAllocPass.h
@@ -24,6 +24,7 @@
 namespace rs2spirv {
 
 llvm::ModulePass *createGlobalAllocPass();
+llvm::ModulePass *createRemoveAllGlobalAllocPass();
 
 } // namespace rs2spirv
 
diff --git a/rsov/compiler/GlobalMergePass.cpp b/rsov/compiler/GlobalMergePass.cpp
index 1570dbc..599fb95 100644
--- a/rsov/compiler/GlobalMergePass.cpp
+++ b/rsov/compiler/GlobalMergePass.cpp
@@ -16,16 +16,16 @@
 
 #include "GlobalMergePass.h"
 
-#include "RSAllocationUtils.h"
-#include "llvm/IR/Attributes.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/Module.h"
-#include "llvm/IR/PassManager.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "RSAllocationUtils.h"
 
 #define DEBUG_TYPE "rs2spirv-global-merge"
 
diff --git a/rsov/compiler/InlinePreparationPass.cpp b/rsov/compiler/InlinePreparationPass.cpp
index 70ff659..5b0fa6d 100644
--- a/rsov/compiler/InlinePreparationPass.cpp
+++ b/rsov/compiler/InlinePreparationPass.cpp
@@ -16,14 +16,13 @@
 
 #include "InlinePreparationPass.h"
 
-#include "bcinfo/MetadataExtractor.h"
-
 #include "llvm/ADT/StringSet.h"
-#include "llvm/IR/Attributes.h"
 #include "llvm/IR/Module.h"
-#include "llvm/IR/PassManager.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "bcinfo/MetadataExtractor.h"
 
 #define DEBUG_TYPE "rs2spirv-inline"
 
diff --git a/rsov/compiler/KernelSignature.cpp b/rsov/compiler/KernelSignature.cpp
deleted file mode 100644
index 6367ed4..0000000
--- a/rsov/compiler/KernelSignature.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 2017, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "KernelSignature.h"
-
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-
-using namespace llvm;
-
-namespace {
-std::string TypeToString(const Type *Ty) {
-  assert(Ty);
-  if (Ty->isVoidTy())
-    return "void";
-
-  if (auto *IT = dyn_cast<IntegerType>(Ty)) {
-    if (IT->getBitWidth() == 32)
-      return "int";
-    else if (IT->getBitWidth() == 8)
-      return "uchar";
-  }
-
-  if (Ty->isFloatTy())
-    return "float";
-
-  if (auto *VT = dyn_cast<VectorType>(Ty)) {
-    auto *ET = VT->getElementType();
-    if (auto *IT = dyn_cast<IntegerType>(ET)) {
-      if (IT->getBitWidth() == 32)
-        return "int4";
-      else if (IT->getBitWidth() == 8)
-        return "uchar4";
-    }
-    if (ET->isFloatTy())
-      return "float4";
-  }
-
-  std::string badNameString;
-  raw_string_ostream badNameStream(badNameString);
-  badNameStream << '[';
-  Ty->print(badNameStream);
-  badNameStream << ']';
-  return badNameStream.str();
-}
-} // namespace
-
-namespace rs2spirv {
-
-const std::string KernelSignature::wrapperPrefix = "%__rsov_";
-
-KernelSignature::KernelSignature(const FunctionType *FT,
-                                 const std::string Fname, Coords CK)
-    : returnType(TypeToString(FT->getReturnType())), name(Fname),
-      coordsKind(CK) {
-  for (const auto *ArgT : FT->params()) {
-    argumentTypes.push_back(TypeToString(ArgT));
-  }
-  // Drop special arguments
-  // TODO: handle all special argument cases.
-  argumentTypes.resize(argumentTypes.size()-size_t(CK));
-}
-
-void KernelSignature::dump() const {
-  dbgs() << returnType << ' ' << name << '(' << argumentTypes[0];
-  const auto CoordsNum = size_t(coordsKind);
-  for (size_t i = 0; i != CoordsNum; ++i)
-    dbgs() << ", " << CoordsNames[i];
-
-  dbgs() << ")\n";
-}
-
-} // namespace rs2spirv
diff --git a/rsov/compiler/KernelSignature.h b/rsov/compiler/KernelSignature.h
deleted file mode 100644
index 32adcf5..0000000
--- a/rsov/compiler/KernelSignature.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2016, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef RS_KERNEL_SIGNATURE_H
-#define RS_KERNEL_SIGNATURE_H
-
-#include "llvm/ADT/StringRef.h"
-#include "llvm/IR/DerivedTypes.h"
-
-#include <string>
-#include <vector>
-
-namespace rs2spirv {
-
-static const llvm::StringRef CoordsNames[] = {"x", "y", "z"};
-
-// Numeric value corresponds to the number of components.
-enum class Coords : size_t { None = 0, X, XY, XYZ, Last = XYZ };
-
-struct KernelSignature {
-  typedef std::vector<std::string> ArgumentTypes;
-  std::string returnType;
-  std::string name;
-  ArgumentTypes argumentTypes;
-  Coords coordsKind;
-
-  KernelSignature(const llvm::FunctionType *FT, const std::string Fname,
-                  Coords CK);
-
-  void dump() const;
-
-  inline std::string getWrapperName(void) const {
-    return wrapperPrefix + "entry_" + name;
-  }
-
-  inline std::string getTempName(const std::string suffix) const {
-    return wrapperPrefix + name + "_" + suffix;
-  }
-
-  static bool isWrapper(const llvm::StringRef &id) {
-    return id.startswith(wrapperPrefix);
-  }
-
-private:
-  static const std::string wrapperPrefix;
-};
-
-} // namespace rs2spirv
-
-#endif
diff --git a/rsov/compiler/RSAllocationUtils.cpp b/rsov/compiler/RSAllocationUtils.cpp
index 9bb27f4..b9d016b 100644
--- a/rsov/compiler/RSAllocationUtils.cpp
+++ b/rsov/compiler/RSAllocationUtils.cpp
@@ -16,16 +16,16 @@
 
 #include "RSAllocationUtils.h"
 
-#include "cxxabi.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Transforms/Utils/Cloning.h"
 
-#include <algorithm>
+#include "cxxabi.h"
+
 #include <sstream>
 #include <unordered_map>
 
@@ -107,9 +107,23 @@
         if (auto *F = FCall->getCalledFunction()) {
           const auto FName = F->getName();
           DEBUG(dbgs() << "Discovered function call to : " << FName << '\n');
+          // Treat memcpy as moves for the purpose of this analysis
+          if (FName.startswith("llvm.memcpy")) {
+            assert(FCall->getNumArgOperands() > 0);
+            Value *CopyDest = FCall->getArgOperand(0);
+            // We are interested in the users of the dest operand of
+            // memcpy here
+            Value *LocalCopy = CopyDest->stripPointerCasts();
+            User *NewU = dyn_cast<User>(LocalCopy);
+            assert(NewU);
+            WorkList.push_back(NewU);
+            continue;
+          }
 
           char *demangled = __cxxabiv1::__cxa_demangle(
               FName.str().c_str(), nullptr, nullptr, nullptr);
+          if (!demangled)
+            continue;
           const StringRef DemangledNameRef(demangled);
           DEBUG(dbgs() << "Demangled name: " << DemangledNameRef << '\n');
 
@@ -187,9 +201,7 @@
     FName = "rsAllocationGetDimX";
   else
     FName = Fun->getName();
-#if 0
-  StringRef GVName = CallInfo.RSAlloc.VarName;
-#endif
+
   std::ostringstream OSS;
   OSS << "__rsov_" << FName.str();
   // Make up uint32_t F(uint32_t)
diff --git a/rsov/compiler/RSAllocationUtils.h b/rsov/compiler/RSAllocationUtils.h
index 23884d1..a3c22d1 100644
--- a/rsov/compiler/RSAllocationUtils.h
+++ b/rsov/compiler/RSAllocationUtils.h
@@ -19,7 +19,8 @@
 
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringRef.h"
+
+#include <string>
 
 namespace llvm {
 class CallInst;
@@ -46,7 +47,6 @@
 };
 
 bool isRSAllocation(const llvm::GlobalVariable &GV);
-llvm::Optional<llvm::StringRef> getRSTypeName(const llvm::GlobalVariable &GV);
 bool getRSAllocationInfo(llvm::Module &M,
                          llvm::SmallVectorImpl<RSAllocationInfo> &Allocs);
 bool getRSAllocAccesses(llvm::SmallVectorImpl<RSAllocationInfo> &Allocs,
diff --git a/rsov/compiler/RSSPIRVWriter.cpp b/rsov/compiler/RSSPIRVWriter.cpp
index 541f5bc..200c388 100644
--- a/rsov/compiler/RSSPIRVWriter.cpp
+++ b/rsov/compiler/RSSPIRVWriter.cpp
@@ -16,10 +16,6 @@
 
 #include "RSSPIRVWriter.h"
 
-#include "SPIRVModule.h"
-#include "bcinfo/MetadataExtractor.h"
-
-#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
@@ -36,27 +32,18 @@
 #include "GlobalMergePass.h"
 #include "InlinePreparationPass.h"
 #include "RemoveNonkernelsPass.h"
+#include "SPIRVModule.h"
 #include "Wrapper.h"
+#include "bcinfo/MetadataExtractor.h"
 #include "pass_queue.h"
 
-#include <fstream>
-#include <sstream>
-
 #define DEBUG_TYPE "rs2spirv-writer"
 
 using namespace llvm;
 using namespace SPIRV;
 
-namespace llvm {
-FunctionPass *createPromoteMemoryToRegisterPass();
-} // namespace llvm
-
 namespace rs2spirv {
 
-static cl::opt<std::string> WrapperOutputFile("wo",
-                                              cl::desc("Wrapper output file"),
-                                              cl::value_desc("filename.spt"));
-
 static void HandleTargetTriple(llvm::Module &M) {
   Triple TT(M.getTargetTriple());
   auto Arch = TT.getArch();
@@ -95,10 +82,11 @@
   PassMgr.add(createGlobalMergePass());
   // Transform global allocations and accessors (rs[GS]etElementAt)
   PassMgr.add(createGlobalAllocPass());
+  // Removed dead MemCpys in 64-bit targets after global alloc pass
+  PassMgr.add(createDeadStoreEliminationPass());
   PassMgr.add(createAggressiveDCEPass());
-  // Delete unreachable globals.
-  PassMgr.add(createGlobalDCEPass());
-  // Remove global allocations
+  // Delete unreachable globals (after removing global allocations)
+  PassMgr.add(createRemoveAllGlobalAllocPass());
   PassMgr.add(createPromoteMemoryToRegisterPass());
   PassMgr.add(createTransOCLMD());
   // TODO: investigate removal of OCLTypeToSPIRV pass.
diff --git a/rsov/compiler/RemoveNonkernelsPass.cpp b/rsov/compiler/RemoveNonkernelsPass.cpp
index 1ffe9f1..09cf1ae 100644
--- a/rsov/compiler/RemoveNonkernelsPass.cpp
+++ b/rsov/compiler/RemoveNonkernelsPass.cpp
@@ -16,15 +16,14 @@
 
 #include "RemoveNonkernelsPass.h"
 
-#include "bcinfo/MetadataExtractor.h"
-
 #include "llvm/ADT/StringSet.h"
-#include "llvm/IR/Attributes.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Module.h"
-#include "llvm/IR/PassManager.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "bcinfo/MetadataExtractor.h"
 
 #define DEBUG_TYPE "rs2spirv-remove"
 
diff --git a/rsov/compiler/rs2spirv.cpp b/rsov/compiler/rs2spirv.cpp
index 0d9ed28..69d75a5 100644
--- a/rsov/compiler/rs2spirv.cpp
+++ b/rsov/compiler/rs2spirv.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#include "RSSPIRVWriter.h"
-#include "unit_tests/TestRunner.h"
 #include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
@@ -24,13 +22,11 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/PrettyStackTrace.h"
-#include "llvm/Support/SPIRV.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/ToolOutputFile.h"
 #include "llvm/Support/raw_ostream.h"
 
-#include <fstream>
-#include <iterator>
+#include "RSSPIRVWriter.h"
 
 #define DEBUG_TYPE "rs2spirv"
 
@@ -47,24 +43,6 @@
                                        cl::desc("Override output filename"),
                                        cl::value_desc("filename"));
 
-static cl::opt<bool> IsPrintAsWords(
-    "print-as-words",
-    cl::desc("Print an input .spv file as a brace-init-list of words"),
-    cl::init(false));
-
-static cl::opt<bool>
-    IsRegularization("s",
-                     cl::desc("Regularize LLVM to be representable by SPIR-V"));
-
-#ifdef RS2SPIRV_DEBUG
-static cl::opt<bool> RunTests("run-tests", cl::desc("Run unit tests"),
-                              cl::init(false));
-#endif
-
-namespace SPIRV {
-extern bool SPIRVUseTextFormat;
-} // namespace SPIRV
-
 static std::string removeExt(const std::string &FileName) {
   size_t Pos = FileName.find_last_of(".");
   if (Pos != std::string::npos)
@@ -115,43 +93,6 @@
   return 0;
 }
 
-static int printAsWords() {
-  std::ifstream IFS(InputFile, std::ios::binary);
-  if (!IFS.good()) {
-    errs() << "Could not open input file\n";
-    return -1;
-  }
-
-  uint64_t FSize;
-  const auto EC = llvm::sys::fs::file_size(InputFile, FSize);
-  if (EC) {
-    errs() << "Fails to open input file: " << EC.message() << '\n';
-    return -1;
-  }
-
-  if (FSize % 4 != 0) {
-    errs() << "Input file is not a stream of words. Size mismatch.\n";
-    return -1;
-  }
-
-  std::istreambuf_iterator<char> It(IFS);
-  const std::istreambuf_iterator<char> End;
-
-  outs() << '{';
-
-  while (It != End) {
-    uint32_t val = 0;
-    // Mask the sign-extended values to prevent higher bits pollution.
-    val += uint32_t(*(It++)) & 0x000000FF;
-    val += (uint32_t(*(It++)) << 8) & 0x0000FF00;
-    val += (uint32_t(*(It++)) << 16) & 0x00FF0000;
-    val += (uint32_t(*(It++)) << 24) & 0xFF000000;
-    outs() << val << (It != End ? ", " : "};\n");
-  }
-
-  return 0;
-}
-
 int main(int ac, char **av) {
   EnablePrettyStackTrace();
   sys::PrintStackTraceOnErrorSignal(av[0]);
@@ -159,13 +100,5 @@
 
   cl::ParseCommandLineOptions(ac, av, "RenderScript to SPIRV translator");
 
-#ifdef RS2SPIRV_DEBUG
-  if (RunTests)
-    return rs2spirv::TestRunnerContext::runTests();
-#endif
-
-  if (IsPrintAsWords)
-    return printAsWords();
-
   return convertLLVMToSPIRV();
 }
diff --git a/rsov/compiler/spirit/builder_test.cpp b/rsov/compiler/spirit/builder_test.cpp
index 48030ae..bb935b6 100644
--- a/rsov/compiler/spirit/builder_test.cpp
+++ b/rsov/compiler/spirit/builder_test.cpp
@@ -44,6 +44,7 @@
   m->addSourceExtension("GL_ARB_shading_language_420pack");
   m->addSourceExtension("GL_GOOGLE_cpp_style_line_directive");
   m->addSourceExtension("GL_GOOGLE_include_directive");
+  m->addString("Foo Bar Baz");
 
   auto FloatTy = m->getFloatType(32);
   auto VF4Ty = m->getVectorType(FloatTy, 4);
@@ -178,6 +179,7 @@
   EXPECT_EQ(2, countEntity<TypeRuntimeArrayInst>(m));
   EXPECT_EQ(2, countEntity<TypeStructInst>(m));
   EXPECT_EQ(5, countEntity<TypePointerInst>(m));
+  EXPECT_EQ(1, countEntity<StringInst>(m));
 
   m->consolidateAnnotations();
 
diff --git a/rsov/compiler/spirit/module.cpp b/rsov/compiler/spirit/module.cpp
index 9800112..9880f78 100644
--- a/rsov/compiler/spirit/module.cpp
+++ b/rsov/compiler/spirit/module.cpp
@@ -214,6 +214,14 @@
   return this;
 }
 
+Module *Module::addString(const char *str) {
+  if (!mDebugInfo) {
+    mDebugInfo.reset(mBuilder->MakeDebugInfoSection());
+  }
+  mDebugInfo->addString(str);
+  return this;
+}
+
 Module *Module::addEntryPoint(EntryPointDefinition *entry) {
   mEntryPoints.push_back(entry);
   auto newModes = entry->getExecutionModes();
@@ -515,6 +523,12 @@
   return this;
 }
 
+DebugInfoSection *DebugInfoSection::addString(const char *str) {
+  StringInst *source = mBuilder->MakeString(str);
+  mSources.push_back(source);
+  return this;
+}
+
 Instruction *DebugInfoSection::lookupByName(const char *name) const {
   for (auto inst : mNames) {
     if (inst->getOpCode() == OpName) {
diff --git a/rsov/compiler/spirit/module.h b/rsov/compiler/spirit/module.h
index a69d255..3301160 100644
--- a/rsov/compiler/spirit/module.h
+++ b/rsov/compiler/spirit/module.h
@@ -124,6 +124,7 @@
   Module *addExtInstImport(const char *extName);
   Module *addSource(SourceLanguage lang, int version);
   Module *addSourceExtension(const char *ext);
+  Module *addString(const char *ext);
   Module *addEntryPoint(EntryPointDefinition *entry);
 
   ExtInstImportInst *getGLExt() const { return mGLExt; }
@@ -312,6 +313,7 @@
 
   DebugInfoSection *addSource(SourceLanguage lang, int version);
   DebugInfoSection *addSourceExtension(const char *ext);
+  DebugInfoSection *addString(const char *str);
 
   Instruction *lookupByName(const char *name) const;
   const char *lookupNameByInstruction(const Instruction *) const;
diff --git a/rsov/compiler/tests/globals/getdimx.ll b/rsov/compiler/tests/rs_allocation/getdimx.ll
similarity index 100%
rename from rsov/compiler/tests/globals/getdimx.ll
rename to rsov/compiler/tests/rs_allocation/getdimx.ll
diff --git a/rsov/compiler/tests/rs_allocation/getdimx_64.ll b/rsov/compiler/tests/rs_allocation/getdimx_64.ll
new file mode 100644
index 0000000..f5976fb
--- /dev/null
+++ b/rsov/compiler/tests/rs_allocation/getdimx_64.ll
@@ -0,0 +1,75 @@
+; RUN: rs2spirv_lit_driver.sh %s | FileCheck %s
+; Source:
+; rs_allocation g;
+; int32_t RS_KERNEL getDim(int32_t dummy) {
+;    return rsAllocationGetDimX(g);
+; }
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "aarch64-none-linux-gnueabi"
+
+; CHECK: OpMemberDecorate [[MetadataS:%[a-zA-Z_0-9]*]] 0 Offset 4
+; CHECK: OpMemberDecorate [[MetadataS]] 1 Offset 8
+; CHECK: OpMemberDecorate [[MetadataS]] 2 Offset 12
+; CHECK: OpMemberDecorate [[MetadataS]] 3 Offset 16
+; CHECK: OpDecorate [[RuntimeArrS:%[a-zA-Z_0-9]*]] ArrayStride {{[0-9]*}}
+; CHECK: OpDecorate [[MetadataSSBO:%[a-zA-Z_0-9]*]] BufferBlock
+; CHECK: OpDecorate [[Metadata:%[a-zA-Z_0-9]*]] DescriptorSet 0
+; CHECK: OpDecorate [[Metadata]] Binding 0
+
+%struct.rs_allocation.1 = type { i64*, i64*, i64*, i64* }
+
+@g = common global %struct.rs_allocation.1 zeroinitializer, align 8
+; CHECK-NOT: %g = OpVariable %{{.*}} Uniform
+; CHECK-NOT: OpCopyMemorySized
+; CHECK-NOT: OpFunctionCall %uint %__rsov_rsAllocationGetDimX
+; CHECK: [[DimX:%[a-zA-Z_0-9]*]] = OpAccessChain %_ptr_Uniform_uint [[Metadata]]
+; CHECK: [[Res:%[a-zA-Z_0-9]*]] = OpLoad %uint [[DimX]]
+; CHECK: OpReturnValue [[Res]]
+
+; Function Attrs: nounwind
+define i32 @getDim(i32 %dummy) unnamed_addr #0 {
+entry:
+  %tmp = alloca %struct.rs_allocation.1, align 8
+  %0 = bitcast %struct.rs_allocation.1* %tmp to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* %0, i8* bitcast (%struct.rs_allocation.1* @g to i8*), i64 32, i32 8, i1 false), !tbaa.struct !8
+  %call = call i32 @_Z19rsAllocationGetDimX13rs_allocation(%struct.rs_allocation.1* %tmp) #0
+  ret i32 %call
+}
+
+declare i32 @_Z19rsAllocationGetDimX13rs_allocation(%struct.rs_allocation.1*) unnamed_addr
+
+; Function Attrs: argmemonly nounwind
+declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1
+
+; Function Attrs: nounwind
+define void @.rs.dtor() unnamed_addr #0 {
+entry:
+  tail call void @_Z13rsClearObjectP13rs_allocation(%struct.rs_allocation.1* @g) #0
+  ret void
+}
+
+declare void @_Z13rsClearObjectP13rs_allocation(%struct.rs_allocation.1*) unnamed_addr
+
+attributes #0 = { nounwind }
+attributes #1 = { argmemonly nounwind }
+
+!llvm.ident = !{!0}
+!\23pragma = !{!1, !2}
+!\23rs_export_var = !{!3}
+!\23rs_object_slots = !{!4}
+!\23rs_export_foreach_name = !{!5, !6}
+!\23rs_export_foreach = !{!4, !7}
+
+!0 = !{!"Android clang version 3.8.275480  (based on LLVM 3.8.275480)"}
+!1 = !{!"version", !"1"}
+!2 = !{!"java_package_name", !"com.android.rs.rsov.test"}
+!3 = !{!"g", !"20"}
+!4 = !{!"0"}
+!5 = !{!"root"}
+!6 = !{!"getDim"}
+!7 = !{!"35"}
+!8 = !{i64 0, i64 8, !9, i64 8, i64 8, !9, i64 16, i64 8, !9, i64 24, i64 8, !9}
+!9 = !{!10, !10, i64 0}
+!10 = !{!"any pointer", !11, i64 0}
+!11 = !{!"omnipotent char", !12, i64 0}
+!12 = !{!"Simple C/C++ TBAA"}
diff --git a/rsov/compiler/tests/globals/rewrite_getdim.ll b/rsov/compiler/tests/rs_allocation/rewrite_getdim.ll
similarity index 98%
rename from rsov/compiler/tests/globals/rewrite_getdim.ll
rename to rsov/compiler/tests/rs_allocation/rewrite_getdim.ll
index 7133e40..9d252f2 100644
--- a/rsov/compiler/tests/globals/rewrite_getdim.ll
+++ b/rsov/compiler/tests/rs_allocation/rewrite_getdim.ll
@@ -21,6 +21,7 @@
 
 @g = common global %struct.rs_allocation zeroinitializer, align 4
 
+; CHECK-NOT: %g = OpVariable %{{.*}} Uniform
 ; CHECK-NOT: OpFunctionCall %uint %__rsov_rsAllocationGetDimX
 ; CHECK: [[DimX:%[a-zA-Z_0-9]*]] = OpAccessChain %_ptr_Uniform_uint [[Metadata]]
 ; CHECK: [[Res:%[a-zA-Z_0-9]*]] = OpLoad %uint [[DimX]]
diff --git a/script_api/GenerateHeaderFiles.cpp b/script_api/GenerateHeaderFiles.cpp
index ce778b3..1ea5e11 100644
--- a/script_api/GenerateHeaderFiles.cpp
+++ b/script_api/GenerateHeaderFiles.cpp
@@ -120,7 +120,8 @@
     const Constant* constant = spec.getConstant();
     VersionInfo info = spec.getVersionInfo();
     writeVersionGuardStart(file, info, constant->getFinalVersion());
-    *file << "#define " << constant->getName() << " " << spec.getValue() << "\n\n";
+    *file << "static const " << spec.getType() << " " << constant->getName()
+          << " = " << spec.getValue() << ";\n\n";
     writeVersionGuardEnd(file, info);
 }
 
diff --git a/script_api/GenerateTestFiles.cpp b/script_api/GenerateTestFiles.cpp
index 3c28801..d907d37 100644
--- a/script_api/GenerateTestFiles.cpp
+++ b/script_api/GenerateTestFiles.cpp
@@ -303,6 +303,13 @@
     writeJavaCallToRs(false, generateCallToVerifier);
     writeJavaCallToRs(true, generateCallToVerifier);
 
+    // Generate code to destroy input Allocations.
+    for (auto p : mAllInputsAndOutputs) {
+        if (!p->isOutParameter) {
+            mJava->indent() << p->javaAllocName << ".destroy();\n";
+        }
+    }
+
     mJava->endBlock();
     *mJava << "\n";
 }
@@ -860,6 +867,14 @@
         }
         *mJava << ");\n";
     }
+
+    // Generate code to destroy output Allocations.
+    for (auto p : mAllInputsAndOutputs) {
+        if (p->isOutParameter) {
+            mJava->indent() << p->javaAllocName << ".destroy();\n";
+        }
+    }
+
     mJava->decreaseIndent();
     mJava->indent() << "} catch (Exception e) {\n";
     mJava->increaseIndent();
@@ -1028,6 +1043,18 @@
 
     file->endBlock();
     *file << "\n";
+
+    file->indent() << "@Override\n";
+    file->indent() << "protected void tearDown() throws Exception";
+    file->startBlock();
+
+    file->indent() << "script.destroy();\n";
+    file->indent() << "scriptRelaxed.destroy();\n";
+    file->indent() << "super.tearDown();\n";
+
+    file->endBlock();
+    *file << "\n";
+
     return true;
 }
 
diff --git a/script_api/Generator.cpp b/script_api/Generator.cpp
index 456f214..f67e473 100644
--- a/script_api/Generator.cpp
+++ b/script_api/Generator.cpp
@@ -62,6 +62,7 @@
  * [version: ({Starting API level} [ {Last API level that supports this.}] | UNRELEASED)
  * [size: {32 or 64.  Used if this is available only for 32 or 64 bit code.}]
  * value: {The value of the constant.}
+ * type: {The type of the constant.}
  * [hidden:]   ...If present, don't document the constant.  Omit the following two fields.
  * [deprecated: [{Deprecation message.}]   ... This is deprecated.  Compiler will issue a wrning.
  * summary: {A one line string describing this section.}
diff --git a/script_api/Specification.cpp b/script_api/Specification.cpp
index c103dc1..f7d139e 100644
--- a/script_api/Specification.cpp
+++ b/script_api/Specification.cpp
@@ -382,6 +382,9 @@
     if (scanner->findTag("value:")) {
         spec->mValue = scanner->getValue();
     }
+    if (scanner->findTag("type:")) {
+        spec->mType = scanner->getValue();
+    }
     constant->scanDocumentationTags(scanner, created, specFile);
 
     scanner->findTag("end:");
diff --git a/script_api/Specification.h b/script_api/Specification.h
index bcd5737..9e1b2ee 100644
--- a/script_api/Specification.h
+++ b/script_api/Specification.h
@@ -258,7 +258,7 @@
     VersionInfo getVersionInfo() const { return mVersionInfo; }
 };
 
-/* Defines one of the many variations of a constant.  There's a one to one correspondance between
+/* Defines one of the many variations of a constant.  There's a one to one correspondence between
  * ConstantSpecification objects and entries in the spec file.
  */
 class ConstantSpecification : public Specification {
@@ -266,11 +266,13 @@
     Constant* mConstant;  // Not owned
 
     std::string mValue;  // E.g. "3.1415"
+    std::string mType;   // E.g. "float"
 public:
     ConstantSpecification(Constant* constant) : mConstant(constant) {}
 
     Constant* getConstant() const { return mConstant; }
     std::string getValue() const { return mValue; }
+    std::string getType() const { return mType; }
 
     // Parse a constant specification and add it to specFile.
     static void scanConstantSpecification(Scanner* scanner, SpecFile* specFile, unsigned int maxApiLevel);
@@ -283,7 +285,7 @@
     ENUM,
 };
 
-/* Defines one of the many variations of a type.  There's a one to one correspondance between
+/* Defines one of the many variations of a type.  There's a one to one correspondence between
  * TypeSpecification objects and entries in the spec file.
  */
 class TypeSpecification : public Specification {
@@ -326,7 +328,7 @@
 // Maximum number of placeholders (like #1, #2) in function specifications.
 const int MAX_REPLACEABLES = 4;
 
-/* Defines one of the many variations of the function.  There's a one to one correspondance between
+/* Defines one of the many variations of the function.  There's a one to one correspondence between
  * FunctionSpecification objects and entries in the spec file.  Some of the strings that are parts
  * of a FunctionSpecification can include placeholders, which are "#1", "#2", "#3", and "#4".  We'll
  * replace these by values before generating the files.
diff --git a/script_api/generate.sh b/script_api/generate.sh
index fbcde0c..c7d105c 100755
--- a/script_api/generate.sh
+++ b/script_api/generate.sh
@@ -17,6 +17,8 @@
 
 CLANG=$ANDROID_BUILD_TOP/prebuilts/clang/host/linux-x86/clang-stable/bin/clang++
 
+cd `dirname $0`
+
 set -e
 $CLANG Generator.cpp Specification.cpp GenerateDocumentation.cpp GenerateHeaderFiles.cpp GenerateTestFiles.cpp Scanner.cpp Utilities.cpp GenerateStubsWhiteList.cpp -g -std=c++11 -Wall -o generator
 
@@ -51,6 +53,6 @@
 done
 rm -rf slangtest
 
-mv RSStubsWhiteList.cpp ../../compile/libbcc/lib/Renderscript/
+mv RSStubsWhiteList.cpp ../../compile/libbcc/lib/
 
 echo "Be sure to update platform/frameworks/base/docs/html/guide/guide_toc.cs if needed."
diff --git a/script_api/include/rs_math.rsh b/script_api/include/rs_math.rsh
index 3d034d0..a5a7569 100644
--- a/script_api/include/rs_math.rsh
+++ b/script_api/include/rs_math.rsh
@@ -58,14 +58,14 @@
  *
  * The inverse of pi, as a 32 bit float.
  */
-#define M_1_PI 0.318309886183790671537767526745028724f
+static const float M_1_PI = 0.318309886183790671537767526745028724f;
 
 /*
  * M_2_PI: 2 / pi, as a 32 bit float
  *
  * 2 divided by pi, as a 32 bit float.
  */
-#define M_2_PI 0.636619772367581343075535053490057448f
+static const float M_2_PI = 0.636619772367581343075535053490057448f;
 
 /*
  * M_2_PIl: 2 / pi, as a 32 bit float
@@ -74,84 +74,84 @@
  *
  * 2 divided by pi, as a 32 bit float.
  */
-#define M_2_PIl 0.636619772367581343075535053490057448f
+static const float M_2_PIl = 0.636619772367581343075535053490057448f;
 
 /*
  * M_2_SQRTPI: 2 / sqrt(pi), as a 32 bit float
  *
  * 2 divided by the square root of pi, as a 32 bit float.
  */
-#define M_2_SQRTPI 1.128379167095512573896158903121545172f
+static const float M_2_SQRTPI = 1.128379167095512573896158903121545172f;
 
 /*
  * M_E: e, as a 32 bit float
  *
  * The number e, the base of the natural logarithm, as a 32 bit float.
  */
-#define M_E 2.718281828459045235360287471352662498f
+static const float M_E = 2.718281828459045235360287471352662498f;
 
 /*
  * M_LN10: log_e(10), as a 32 bit float
  *
  * The natural logarithm of 10, as a 32 bit float.
  */
-#define M_LN10 2.302585092994045684017991454684364208f
+static const float M_LN10 = 2.302585092994045684017991454684364208f;
 
 /*
  * M_LN2: log_e(2), as a 32 bit float
  *
  * The natural logarithm of 2, as a 32 bit float.
  */
-#define M_LN2 0.693147180559945309417232121458176568f
+static const float M_LN2 = 0.693147180559945309417232121458176568f;
 
 /*
  * M_LOG10E: log_10(e), as a 32 bit float
  *
  * The logarithm base 10 of e, as a 32 bit float.
  */
-#define M_LOG10E 0.434294481903251827651128918916605082f
+static const float M_LOG10E = 0.434294481903251827651128918916605082f;
 
 /*
  * M_LOG2E: log_2(e), as a 32 bit float
  *
  * The logarithm base 2 of e, as a 32 bit float.
  */
-#define M_LOG2E 1.442695040888963407359924681001892137f
+static const float M_LOG2E = 1.442695040888963407359924681001892137f;
 
 /*
  * M_PI: pi, as a 32 bit float
  *
  * The constant pi, as a 32 bit float.
  */
-#define M_PI 3.141592653589793238462643383279502884f
+static const float M_PI = 3.141592653589793238462643383279502884f;
 
 /*
  * M_PI_2: pi / 2, as a 32 bit float
  *
  * Pi divided by 2, as a 32 bit float.
  */
-#define M_PI_2 1.570796326794896619231321691639751442f
+static const float M_PI_2 = 1.570796326794896619231321691639751442f;
 
 /*
  * M_PI_4: pi / 4, as a 32 bit float
  *
  * Pi divided by 4, as a 32 bit float.
  */
-#define M_PI_4 0.785398163397448309615660845819875721f
+static const float M_PI_4 = 0.785398163397448309615660845819875721f;
 
 /*
  * M_SQRT1_2: 1 / sqrt(2), as a 32 bit float
  *
  * The inverse of the square root of 2, as a 32 bit float.
  */
-#define M_SQRT1_2 0.707106781186547524400844362104849039f
+static const float M_SQRT1_2 = 0.707106781186547524400844362104849039f;
 
 /*
  * M_SQRT2: sqrt(2), as a 32 bit float
  *
  * The square root of 2, as a 32 bit float.
  */
-#define M_SQRT2 1.414213562373095048801688724209698079f
+static const float M_SQRT2 = 1.414213562373095048801688724209698079f;
 
 /*
  * abs: Absolute value of an integer
diff --git a/script_api/rs_math.spec b/script_api/rs_math.spec
index b4093e8..15378ad 100644
--- a/script_api/rs_math.spec
+++ b/script_api/rs_math.spec
@@ -51,6 +51,7 @@
 # TODO Add f16 versions of these constants.
 constant: M_1_PI
 value: 0.318309886183790671537767526745028724f
+type: float
 summary: 1 / pi, as a 32 bit float
 description:
  The inverse of pi, as a 32 bit float.
@@ -58,6 +59,7 @@
 
 constant: M_2_PI
 value: 0.636619772367581343075535053490057448f
+type: float
 summary: 2 / pi, as a 32 bit float
 description:
  2 divided by pi, as a 32 bit float.
@@ -65,6 +67,7 @@
 
 constant: M_2_PIl
 value: 0.636619772367581343075535053490057448f
+type: float
 hidden:
 deprecated: 22, Use M_2_PI instead.
 summary: 2 / pi, as a 32 bit float
@@ -74,6 +77,7 @@
 
 constant: M_2_SQRTPI
 value: 1.128379167095512573896158903121545172f
+type: float
 summary:  2 / sqrt(pi), as a 32 bit float
 description:
  2 divided by the square root of pi, as a 32 bit float.
@@ -81,6 +85,7 @@
 
 constant: M_E
 value: 2.718281828459045235360287471352662498f
+type: float
 summary: e, as a 32 bit float
 description:
  The number e, the base of the natural logarithm, as a 32 bit float.
@@ -88,6 +93,7 @@
 
 constant: M_LN10
 value: 2.302585092994045684017991454684364208f
+type: float
 summary: log_e(10), as a 32 bit float
 description:
  The natural logarithm of 10, as a 32 bit float.
@@ -95,6 +101,7 @@
 
 constant: M_LN2
 value: 0.693147180559945309417232121458176568f
+type: float
 summary: log_e(2), as a 32 bit float
 description:
  The natural logarithm of 2, as a 32 bit float.
@@ -102,6 +109,7 @@
 
 constant: M_LOG10E
 value: 0.434294481903251827651128918916605082f
+type: float
 summary: log_10(e), as a 32 bit float
 description:
  The logarithm base 10 of e, as a 32 bit float.
@@ -109,6 +117,7 @@
 
 constant: M_LOG2E
 value: 1.442695040888963407359924681001892137f
+type: float
 summary: log_2(e), as a 32 bit float
 description:
  The logarithm base 2 of e, as a 32 bit float.
@@ -116,6 +125,7 @@
 
 constant: M_PI
 value: 3.141592653589793238462643383279502884f
+type: float
 summary: pi, as a 32 bit float
 description:
  The constant pi, as a 32 bit float.
@@ -123,6 +133,7 @@
 
 constant: M_PI_2
 value: 1.570796326794896619231321691639751442f
+type: float
 summary: pi / 2, as a 32 bit float
 description:
  Pi divided by 2, as a 32 bit float.
@@ -130,6 +141,7 @@
 
 constant: M_PI_4
 value: 0.785398163397448309615660845819875721f
+type: float
 summary: pi / 4, as a 32 bit float
 description:
  Pi divided by 4, as a 32 bit float.
@@ -137,6 +149,7 @@
 
 constant: M_SQRT1_2
 value: 0.707106781186547524400844362104849039f
+type: float
 summary: 1 / sqrt(2), as a 32 bit float
 description:
  The inverse of the square root of 2, as a 32 bit float.
@@ -144,6 +157,7 @@
 
 constant: M_SQRT2
 value: 1.414213562373095048801688724209698079f
+type: float
 summary: sqrt(2), as a 32 bit float
 description:
  The square root of 2, as a 32 bit float.
diff --git a/tests/java_api/ImageProcessing/Android.mk b/tests/java_api/ImageProcessing/Android.mk
index a223d67..4e81d39 100644
--- a/tests/java_api/ImageProcessing/Android.mk
+++ b/tests/java_api/ImageProcessing/Android.mk
@@ -21,6 +21,8 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
+LOCAL_STATIC_JAVA_LIBRARIES := legacy-android-test junit
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
                    $(call all-renderscript-files-under, src)
 
diff --git a/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_ref_count.java b/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_ref_count.java
index fe32528..f11b9c8 100644
--- a/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_ref_count.java
+++ b/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_ref_count.java
@@ -37,6 +37,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_script.java b/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_script.java
index 17385c9..6e13b2a 100644
--- a/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_script.java
+++ b/tests/java_api/RSTest_CompatLib/src/com/android/rs/test/UT_single_source_script.java
@@ -53,6 +53,11 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
+        testAllocation1.getType().destroy();
+        testAllocation1.destroy();
+        testAllocation2.getType().destroy();
+        testAllocation2.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/RSTest.java b/tests/java_api/RsTest/src/com/android/rs/test/RSTest.java
index 2c2d6a2..9eb35ad 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/RSTest.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/RSTest.java
@@ -19,6 +19,11 @@
 import android.app.ListActivity;
 import android.os.Bundle;
 import android.renderscript.RenderScript;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.StrictMode;
+import android.provider.Settings.System;
 import android.util.Log;
 
 public class RSTest extends ListActivity {
@@ -33,6 +38,12 @@
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
+
+        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
+                               .detectLeakedClosableObjects()
+                               .penaltyLog()
+                               .build());
+
         mRS = RenderScript.create(this);
 
         RSTC = new RSTestCore(this);
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_alloc.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_alloc.java
index 179d3c2..47157ed 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_alloc.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_alloc.java
@@ -23,6 +23,13 @@
 import android.renderscript.Type;
 
 public class UT_alloc extends UnitTest {
+    private Type T;
+    private Type mTFaces;
+    private Type mTLOD;
+    private Type mTFacesLOD;
+    private Allocation mAFaces;
+    private Allocation mALOD;
+    private Allocation mAFacesLOD;
 
     protected UT_alloc(RSTestCore rstc, Context ctx) {
         super(rstc, "Alloc", ctx);
@@ -37,20 +44,24 @@
         s.set_dimY(Y);
         s.set_dimZ(Z);
         typeBuilder.setX(X);  // Only build a 1-D version of this
-        Allocation A = Allocation.createTyped(RS, typeBuilder.create());
+        T = typeBuilder.create();
+        Allocation A = Allocation.createTyped(RS, T);
         s.bind_a(A);
         s.set_aRaw(A);
 
         typeBuilder = new Type.Builder(RS, Element.I32(RS));
         typeBuilder.setX(X).setY(Y).setFaces(true);
-        Allocation AFaces = Allocation.createTyped(RS, typeBuilder.create());
-        s.set_aFaces(AFaces);
+        mTFaces = typeBuilder.create();
+        mAFaces = Allocation.createTyped(RS, mTFaces);
+        s.set_aFaces(mAFaces);
         typeBuilder.setFaces(false).setMipmaps(true);
-        Allocation ALOD = Allocation.createTyped(RS, typeBuilder.create());
-        s.set_aLOD(ALOD);
+        mTLOD = typeBuilder.create();
+        mALOD = Allocation.createTyped(RS, mTLOD);
+        s.set_aLOD(mALOD);
         typeBuilder.setFaces(true).setMipmaps(true);
-        Allocation AFacesLOD = Allocation.createTyped(RS, typeBuilder.create());
-        s.set_aFacesLOD(AFacesLOD);
+        mTFacesLOD = typeBuilder.create();
+        mAFacesLOD = Allocation.createTyped(RS, mTFacesLOD);
+        s.set_aFacesLOD(mAFacesLOD);
 
         return;
     }
@@ -64,6 +75,15 @@
         s.invoke_alloc_test();
         pRS.finish();
         waitForMessage();
+        T.destroy();
+        s.get_a().destroy();
+        mAFaces.destroy();
+        mALOD.destroy();
+        mAFacesLOD.destroy();
+        mTFaces.destroy();
+        mTLOD.destroy();
+        mTFacesLOD.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_array_alloc.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_array_alloc.java
index b08abed..8d2d0e4 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_array_alloc.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_array_alloc.java
@@ -46,6 +46,11 @@
         s.invoke_array_alloc_test();
         pRS.finish();
         waitForMessage();
+        for (int i = 0; i < dimX; i++) {
+            Arr[i].destroy();
+        }
+        T.destroy();
+        s.destroy();
         pRS.destroy();
         passTest();
     }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_array_init.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_array_init.java
index 401019f..ab61765 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_array_init.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_array_init.java
@@ -86,6 +86,7 @@
         s.invoke_array_init_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
         passTest();
     }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_atomic.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_atomic.java
index fdde258..131781a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_atomic.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_atomic.java
@@ -32,6 +32,7 @@
         s.invoke_atomic_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_bug_char.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_bug_char.java
index 9eb76eb..0158b80 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_bug_char.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_bug_char.java
@@ -83,6 +83,7 @@
         s.invoke_bug_char_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_check_dims.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_check_dims.java
index cd4b3be..7fbc28a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_check_dims.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_check_dims.java
@@ -25,6 +25,7 @@
 public class UT_check_dims extends UnitTest {
     byte mFailedArr[];
     int mData[];
+    Allocation mAFailed;
     Allocation mA;
     static final int Pattern = 0xA5A5A5A5;
 
@@ -35,12 +36,12 @@
     private void initializeGlobals(RenderScript RS, ScriptC_check_dims s) {
         Type.Builder typeBuilder = new Type.Builder(RS, Element.U8(RS));
         typeBuilder.setX(1);
-        Allocation AFailed = Allocation.createTyped(RS, typeBuilder.create());
-        s.set_aFailed(AFailed);
+        mAFailed = Allocation.createTyped(RS, typeBuilder.create());
+        s.set_aFailed(mAFailed);
 
         mFailedArr = new byte[1];
         mFailedArr[0] = 0;
-        AFailed.copyFrom(mFailedArr);
+        mAFailed.copyFrom(mFailedArr);
 
         typeBuilder = new Type.Builder(RS, Element.I32(RS));
         int X = 5;
@@ -67,6 +68,9 @@
         s.invoke_check_dims_test();
         pRS.finish();
         waitForMessage();
+        mAFailed.destroy();
+        mA.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp.java
index 5e5878e..489f54e 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp.java
@@ -32,6 +32,7 @@
         s.invoke_clamp_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp_relaxed.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp_relaxed.java
index a53b2a5..2ef97b6 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp_relaxed.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_clamp_relaxed.java
@@ -33,6 +33,7 @@
         s.invoke_clamp_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_convert.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_convert.java
index b241d27..6e2b0f1 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_convert.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_convert.java
@@ -32,6 +32,7 @@
         s.invoke_convert_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_convert_relaxed.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_convert_relaxed.java
index 4956c6f..2514271 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_convert_relaxed.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_convert_relaxed.java
@@ -33,6 +33,7 @@
         s.invoke_convert_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_copy_test.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_copy_test.java
index e7e6ff3..da760cf 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_copy_test.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_copy_test.java
@@ -113,6 +113,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_ctxt_default.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_ctxt_default.java
index f6f9f80..fe6a526 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_ctxt_default.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_ctxt_default.java
@@ -23,6 +23,7 @@
 import android.renderscript.Type;
 
 public class UT_ctxt_default extends UnitTest {
+    private Type T;
     private Allocation A;
     private Allocation B;
 
@@ -36,9 +37,10 @@
         s.set_gDimX(X);
         typeBuilder.setX(X);
 
-        A = Allocation.createTyped(RS, typeBuilder.create());
+        T = typeBuilder.create();
+        A = Allocation.createTyped(RS, T);
         s.set_A(A);
-        B = Allocation.createTyped(RS, typeBuilder.create());
+        B = Allocation.createTyped(RS, T);
         s.set_B(B);
         return;
     }
@@ -54,6 +56,10 @@
         s.invoke_kernel_test();
         pRS.finish();
         waitForMessage();
+        T.destroy();
+        A.destroy();
+        B.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_element.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_element.java
index 7ed1965..03d62b4 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_element.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_element.java
@@ -86,6 +86,9 @@
         s.invoke_element_test();
         pRS.finish();
         waitForMessage();
+        s.get_complexStruct().getAllocation().destroy();
+        s.get_complexStruct().getElement().destroy();
+        s.destroy();
     }
 
     private void testJavaSide(RenderScript RS) {
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach.java
index 1afed53..82efdcd 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach.java
@@ -54,6 +54,9 @@
         s.invoke_foreach_test();
         pRS.finish();
         waitForMessage();
+        A.getType().destroy();
+        A.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_bounds.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_bounds.java
index 48e5cdd..6d1b77d 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_bounds.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_bounds.java
@@ -68,6 +68,9 @@
         s.invoke_foreach_bounds_test();
         pRS.finish();
         waitForMessage();
+        A.getType().destroy();
+        A.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_multi.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_multi.java
index cf9be09..b23cde6 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_multi.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_foreach_multi.java
@@ -104,6 +104,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16.java
index 96863a8..9dae23e 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16.java
@@ -26,6 +26,7 @@
     private int dimX = 7;
     private int dimY = 5;
     private int dimZ = 3;
+    private Type type;
     private Allocation alloc;
 
     protected UT_fp16(RSTestCore rstc, Context ctx) {
@@ -45,7 +46,8 @@
                 typeBuilder.setX(dimX).setY(dimY).setZ(dimZ);
                 break;
         }
-        alloc = Allocation.createTyped(RS, typeBuilder.create());
+        type = typeBuilder.create();
+        alloc = Allocation.createTyped(RS, type);
 
         s.set_gDimX(dimX);
         s.set_gDimY(nDims > 1 ? dimY : 0);
@@ -60,10 +62,18 @@
         s.forEach_set_kernel_half(alloc);
         s.invoke_verify_half();
 
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
+
         initializeGlobals(RS, s, Element.F16(RS), nDims);
         // rsSetElementAt in invoke and verify in kernel
         s.invoke_set_half();
         s.forEach_verify_kernel_half(alloc);
+
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
     }
 
     private void TestHalf2(RenderScript RS, ScriptC_fp16 s, int nDims) {
@@ -73,10 +83,18 @@
         s.forEach_set_kernel_half2(alloc);
         s.invoke_verify_half2();
 
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
+
         initializeGlobals(RS, s, Element.F16_2(RS), nDims);
         // rsSetElementAt in invoke and verify in kernel
         s.invoke_set_half2();
         s.forEach_verify_kernel_half2(alloc);
+
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
     }
 
     private void TestHalf3(RenderScript RS, ScriptC_fp16 s, int nDims) {
@@ -86,10 +104,18 @@
         s.forEach_set_kernel_half3(alloc);
         s.invoke_verify_half3();
 
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
+
         initializeGlobals(RS, s, Element.F16_3(RS), nDims);
         // rsSetElementAt in invoke and verify in kernel
         s.invoke_set_half3();
         s.forEach_verify_kernel_half3(alloc);
+
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
     }
 
     private void TestHalf4(RenderScript RS, ScriptC_fp16 s, int nDims) {
@@ -99,10 +125,18 @@
         s.forEach_set_kernel_half4(alloc);
         s.invoke_verify_half4();
 
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
+
         initializeGlobals(RS, s, Element.F16_4(RS), nDims);
         // rsSetElementAt in invoke and verify in kernel
         s.invoke_set_half4();
         s.forEach_verify_kernel_half4(alloc);
+
+        RS.finish();
+        alloc.destroy();
+        type.destroy();
     }
 
     public void run() {
@@ -121,6 +155,7 @@
         s.invoke_fp16_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16_globals.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16_globals.java
index 5a2fd5c..c08f2b3 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16_globals.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp16_globals.java
@@ -54,6 +54,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp_mad.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp_mad.java
index 88a1c83..f6c486c 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_fp_mad.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_fp_mad.java
@@ -32,6 +32,7 @@
         s.invoke_fp_mad_test(0, 0);
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_int4.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_int4.java
index e003cdb..103c111 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_int4.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_int4.java
@@ -32,6 +32,7 @@
         s.invoke_int4_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel.java
index b4196de..47ad14a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel.java
@@ -23,6 +23,8 @@
 import android.renderscript.Type;
 
 public class UT_kernel extends UnitTest {
+    private Type TA;
+    private Type TB;
     private Allocation A;
     private Allocation B;
 
@@ -35,9 +37,11 @@
         int X = 5;
         s.set_dimX(X);
         typeBuilder.setX(X);
-        A = Allocation.createTyped(RS, typeBuilder.create());
+        TA = typeBuilder.create();
+        A = Allocation.createTyped(RS, TA);
         s.bind_ain(A);
-        B = Allocation.createTyped(RS, typeBuilder.create());
+        TB = typeBuilder.create();
+        B = Allocation.createTyped(RS, TB);
         s.bind_aout(B);
 
         return;
@@ -54,6 +58,11 @@
         s.invoke_kernel_test();
         pRS.finish();
         waitForMessage();
+        A.destroy();
+        B.destroy();
+        TA.destroy();
+        TB.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d.java
index 89e1424..e82c754 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d.java
@@ -23,6 +23,7 @@
 import android.renderscript.Type;
 
 public class UT_kernel2d extends UnitTest {
+    private Type T;
     private Allocation A;
     private Allocation B;
 
@@ -39,9 +40,10 @@
         s.set_gDimY(Y);
         typeBuilder.setY(Y);
 
-        A = Allocation.createTyped(RS, typeBuilder.create());
+        T = typeBuilder.create();
+        A = Allocation.createTyped(RS, T);
         s.set_A(A);
-        B = Allocation.createTyped(RS, typeBuilder.create());
+        B = Allocation.createTyped(RS, T);
         s.set_B(B);
         return;
     }
@@ -57,6 +59,10 @@
         s.invoke_kernel_test();
         pRS.finish();
         waitForMessage();
+        T.destroy();
+        A.destroy();
+        B.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d_oldstyle.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d_oldstyle.java
index 285d810..a1efc29 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d_oldstyle.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel2d_oldstyle.java
@@ -23,6 +23,7 @@
 import android.renderscript.Type;
 
 public class UT_kernel2d_oldstyle extends UnitTest {
+    private Type T;
     private Allocation A;
     private Allocation B;
 
@@ -39,9 +40,10 @@
         s.set_gDimY(Y);
         typeBuilder.setY(Y);
 
-        A = Allocation.createTyped(RS, typeBuilder.create());
+        T = typeBuilder.create();
+        A = Allocation.createTyped(RS, T);
         s.set_A(A);
-        B = Allocation.createTyped(RS, typeBuilder.create());
+        B = Allocation.createTyped(RS, T);
         s.set_B(B);
         return;
     }
@@ -57,6 +59,10 @@
         s.invoke_kernel_test();
         pRS.finish();
         waitForMessage();
+        T.destroy();
+        A.destroy();
+        B.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel3d.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel3d.java
index effd9f9..ab63526 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel3d.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel3d.java
@@ -23,6 +23,7 @@
 import android.renderscript.Type;
 
 public class UT_kernel3d extends UnitTest {
+    private Type T;
     private Allocation A;
     private Allocation B;
 
@@ -42,9 +43,10 @@
         s.set_gDimZ(Z);
         typeBuilder.setZ(Z);
 
-        A = Allocation.createTyped(RS, typeBuilder.create());
+        T = typeBuilder.create();
+        A = Allocation.createTyped(RS, T);
         s.set_A(A);
-        B = Allocation.createTyped(RS, typeBuilder.create());
+        B = Allocation.createTyped(RS, T);
         s.set_B(B);
         return;
     }
@@ -60,6 +62,10 @@
         s.invoke_kernel_test();
         pRS.finish();
         waitForMessage();
+        T.destroy();
+        A.destroy();
+        B.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel_struct.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel_struct.java
index 7fcec26..4573678 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel_struct.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_kernel_struct.java
@@ -53,6 +53,11 @@
         s.invoke_kernel_struct_test();
         pRS.finish();
         waitForMessage();
+        A.destroy();
+        B.destroy();
+        s.get_ain().getElement().destroy();
+        s.get_aout().getElement().destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_math.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_math.java
index 7d89e3e..9ece867 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_math.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_math.java
@@ -32,6 +32,7 @@
         s.invoke_math_test(0, 0);
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_agree.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_agree.java
index d5089ea..1e06d17 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_agree.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_agree.java
@@ -576,6 +576,7 @@
         s.invoke_math_agree_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_conformance.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_conformance.java
index a94069c..cbf4521 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_conformance.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_conformance.java
@@ -33,6 +33,7 @@
         s.invoke_math_conformance_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
         passTest();
     }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_fp16.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_fp16.java
index f76f994..f589a71 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_math_fp16.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_math_fp16.java
@@ -37,6 +37,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_min.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_min.java
index ef008c7..951c46a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_min.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_min.java
@@ -32,6 +32,7 @@
         s.invoke_min_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_noroot.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_noroot.java
index 744684d..9846109 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_noroot.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_noroot.java
@@ -52,6 +52,9 @@
         s.invoke_noroot_test();
         pRS.finish();
         waitForMessage();
+        A.getType().destroy();
+        A.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_primitives.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_primitives.java
index 71f3782..eb69c3a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_primitives.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_primitives.java
@@ -95,6 +95,7 @@
             pRS.finish();
             waitForMessage();
         }
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_reduce.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_reduce.java
index 3e1e286..02ca8ab 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_reduce.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_reduce.java
@@ -848,6 +848,7 @@
         inputAllocation.destroy();
         outputAllocation.destroy();
 
+        scriptHsg.destroy();
         return outputArray;
     }
 
@@ -1487,6 +1488,7 @@
         // pass &= runPerformanceQuick(pRS, s);
 
         pRS.finish();
+        s.destroy();
         pRS.destroy();
 
         Log.i(TAG, pass ? "PASSED" : "FAILED");
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_refcount.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_refcount.java
index 432a8fb..8c19a1d 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_refcount.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_refcount.java
@@ -23,6 +23,8 @@
 import android.renderscript.Type;
 
 public class UT_refcount extends UnitTest {
+    private Type mT;
+    private Allocation mA;
 
     protected UT_refcount(RSTestCore rstc, Context ctx) {
         super(rstc, "Refcount", ctx);
@@ -33,8 +35,9 @@
         int X = 500;
         int Y = 700;
         typeBuilder.setX(X).setY(Y);
-        Allocation A = Allocation.createTyped(RS, typeBuilder.create());
-        s.set_globalA(A);
+        mT = typeBuilder.create();
+        mA = Allocation.createTyped(RS, mT);
+        s.set_globalA(mA);
     }
 
     public void run() {
@@ -45,6 +48,9 @@
         s.invoke_refcount_test();
         pRS.finish();
         waitForMessage();
+        mA.destroy();
+        mT.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_rsdebug.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_rsdebug.java
index 639dc97..86b0577 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_rsdebug.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_rsdebug.java
@@ -32,6 +32,7 @@
         s.invoke_test_rsdebug(0, 0);
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_rstime.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_rstime.java
index 23d2a65..6c5e711 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_rstime.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_rstime.java
@@ -33,6 +33,7 @@
         s.invoke_test_rstime(0, 0);
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_rstypes.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_rstypes.java
index 39b11be..c0b56aa 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_rstypes.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_rstypes.java
@@ -32,6 +32,7 @@
         s.invoke_test_rstypes(0, 0);
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_sampler.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_sampler.java
index 5361677..bba3bc4 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_sampler.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_sampler.java
@@ -76,6 +76,7 @@
         s.invoke_sampler_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
     }
 
     private void testJavaSide(RenderScript RS) {
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_float.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_float.java
index 7f34822..20f3be3 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_float.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_float.java
@@ -53,22 +53,22 @@
         final float floatVal = 3.14f;
         final double doubleVal = 1.23456789;
         final long longVal = 0x100000000L;
+        final Type T = Type.createX(pRS, Element.F64(pRS), ARRAY_SIZE);
         ScriptGroup.Closure c0 =
                 builder.addKernel(s_float.getKernelID_foo(),
-                        Type.createX(pRS, Element.F64(pRS), ARRAY_SIZE),
-                        unbound,
-                        new ScriptGroup.Binding(s_float.getFieldID_floatVal(),
-                                floatVal),
-                        new ScriptGroup.Binding(s_float.getFieldID_val(),
-                                doubleVal));
+                                  T,
+                                  unbound,
+                                  new ScriptGroup.Binding(s_float.getFieldID_floatVal(),
+                                                          floatVal),
+                                  new ScriptGroup.Binding(s_float.getFieldID_val(),
+                                                          doubleVal));
 
         ScriptGroup.Closure c1 =
                 builder.addKernel(s_float.getKernelID_goo(),
-                        Type.createX(pRS, Element.F64(pRS), ARRAY_SIZE),
-                        c0.getReturn(),
-                        new ScriptGroup.Binding(s_float.getFieldID_valLong(),
-                                longVal));
-
+                                  T,
+                                  c0.getReturn(),
+                                  new ScriptGroup.Binding(s_float.getFieldID_valLong(),
+                                                          longVal));
 
         ScriptGroup group = builder.create("TestFloatAnd64bit", c1.getReturn());
 
@@ -76,6 +76,10 @@
         ((Allocation) group.execute(input)[0]).copyTo(a);
 
         pRS.finish();
+        T.destroy();
+        group.destroy();
+        input.destroy();
+        s_float.destroy();
         pRS.destroy();
 
         boolean failed = false;
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_gatherscatter.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_gatherscatter.java
index 17c41bd..c99c81a 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_gatherscatter.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_gatherscatter.java
@@ -99,6 +99,10 @@
         ((Allocation) group.execute(input)[0]).copyTo(a);
 
         pRS.finish();
+
+        group.destroy();
+        input.destroy();
+        s.destroy();
         pRS.destroy();
 
         boolean failed = false;
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_nochain.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_nochain.java
index 01906eb..59f23c4 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_nochain.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_nochain.java
@@ -51,21 +51,23 @@
 
         ScriptGroup.Input unbound = builder.addInput();
 
+        Type T = Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE);
+
         ScriptGroup.Closure c0 =
                 builder.addKernel(s_inc.getKernelID_increment(),
-                        Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE),
-                        unbound);
+                                  T,
+                                  unbound);
 
         ScriptGroup.Closure c1 =
                 builder.addKernel(s_inc2.getKernelID_increment2(),
-                        Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE),
-                        unbound,
-                        new ScriptGroup.Binding(s_inc2.getFieldID_a(), unbound));
+                                  T,
+                                  unbound,
+                                  new ScriptGroup.Binding(s_inc2.getFieldID_a(), unbound));
 
         ScriptGroup.Closure c2 =
                 builder.addKernel(s_double.getKernelID_doubleKernel(),
-                        Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE),
-                        unbound);
+                                  T,
+                                  unbound);
 
         ScriptGroup group = builder.create("AddDouble2", c2.getReturn());
 
@@ -73,6 +75,12 @@
         ((Allocation) group.execute(input)[0]).copyTo(a);
 
         pRS.finish();
+        group.destroy();
+        T.destroy();
+        input.destroy();
+        s_inc.destroy();
+        s_inc2.destroy();
+        s_double.destroy();
         pRS.destroy();
 
         boolean failed = false;
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_pointwise.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_pointwise.java
index 29d584c..dd029f1 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_pointwise.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_script_group2_pointwise.java
@@ -50,15 +50,17 @@
 
         ScriptGroup.Input unbound = builder.addInput();
 
+        Type T = Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE);
+
         ScriptGroup.Closure c0 =
                 builder.addKernel(s_inc.getKernelID_increment(),
-                        Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE),
-                        unbound);
+                                  T,
+                                  unbound);
 
         ScriptGroup.Closure c1 =
                 builder.addKernel(s_double.getKernelID_doubleKernel(),
-                        Type.createX(pRS, Element.I32_4(pRS), ARRAY_SIZE),
-                        c0.getReturn());
+                                  T,
+                                  c0.getReturn());
 
         ScriptGroup group = builder.create("AddDouble", c1.getReturn());
 
@@ -66,6 +68,11 @@
         ((Allocation) group.execute(input)[0]).copyTo(a);
 
         pRS.finish();
+        group.destroy();
+        T.destroy();
+        input.destroy();
+        s_double.destroy();
+        s_inc.destroy();
         pRS.destroy();
 
         boolean failed = false;
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_alloc.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_alloc.java
index 67a1e33..514b0c1 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_alloc.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_alloc.java
@@ -65,6 +65,7 @@
         s.invoke_single_source_alloc_test();
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_ref_count.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_ref_count.java
index c4138cc..a70c9de 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_ref_count.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_ref_count.java
@@ -34,6 +34,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_script.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_script.java
index 176fca9..6adf6f3 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_script.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_single_source_script.java
@@ -53,6 +53,7 @@
 
         pRS.finish();
         waitForMessage();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_static_globals.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_static_globals.java
index 2ff0485..6138395 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_static_globals.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_static_globals.java
@@ -33,11 +33,15 @@
         ScriptC_static_globals s = new ScriptC_static_globals(pRS);
         pRS.setMessageHandler(mRsMessage);
         Type.Builder typeBuilder = new Type.Builder(pRS, Element.I32(pRS));
-        Allocation A = Allocation.createTyped(pRS, typeBuilder.setX(1).create());
+        Type t = typeBuilder.setX(1).create();
+        Allocation A = Allocation.createTyped(pRS, t);
         s.forEach_root(A);
         s.invoke_static_globals_test();
         pRS.finish();
         waitForMessage();
+        A.destroy();
+        t.destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_struct.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_struct.java
index b721e23..242929b 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_struct.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_struct.java
@@ -47,6 +47,9 @@
         s.invoke_struct_test(val);
         pRS.finish();
         waitForMessage();
+        p.getAllocation().destroy();
+        p.getElement().destroy();
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_unsigned.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_unsigned.java
index 5e9f0f0..0fe6037 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_unsigned.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_unsigned.java
@@ -52,6 +52,7 @@
             pRS.finish();
             waitForMessage();
         }
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/java_api/RsTest/src/com/android/rs/test/UT_vector.java b/tests/java_api/RsTest/src/com/android/rs/test/UT_vector.java
index cb3fdc3..4ed3097 100644
--- a/tests/java_api/RsTest/src/com/android/rs/test/UT_vector.java
+++ b/tests/java_api/RsTest/src/com/android/rs/test/UT_vector.java
@@ -328,6 +328,7 @@
             pRS.finish();
             waitForMessage();
         }
+        s.destroy();
         pRS.destroy();
     }
 }
diff --git a/tests/lldb/cpp/KernelVariables/simple.rs b/tests/lldb/cpp/KernelVariables/simple.rs
index 58a6842..bad675e 100644
--- a/tests/lldb/cpp/KernelVariables/simple.rs
+++ b/tests/lldb/cpp/KernelVariables/simple.rs
@@ -174,3 +174,24 @@
     uchar4 result = {1,2,3,4};
     return result;
 }
+
+float use_constants_global;
+
+void setup(void)
+{
+  use_constants_global =
+      M_1_PI +
+      M_2_PI +
+      M_2_PIl +
+      M_2_SQRTPI +
+      M_E +
+      M_LN10 +
+      M_LN2 +
+      M_LOG10E +
+      M_LOG2E +
+      M_PI +
+      M_PI_2 +
+      M_PI_4 +
+      M_SQRT1_2 +
+      M_SQRT2;
+}
diff --git a/tests/lldb/java/KernelVariables/src/rs/simple.rs b/tests/lldb/java/KernelVariables/src/rs/simple.rs
index 7eee425..26b6aff 100644
--- a/tests/lldb/java/KernelVariables/src/rs/simple.rs
+++ b/tests/lldb/java/KernelVariables/src/rs/simple.rs
@@ -174,3 +174,24 @@
     uchar4 result = {1,2,3,4};
     return result;
 }
+
+float use_constants_global;
+
+void setup(void)
+{
+  use_constants_global =
+      M_1_PI +
+      M_2_PI +
+      M_2_PIl +
+      M_2_SQRTPI +
+      M_E +
+      M_LN10 +
+      M_LN2 +
+      M_LOG10E +
+      M_LOG2E +
+      M_PI +
+      M_PI_2 +
+      M_PI_4 +
+      M_SQRT1_2 +
+      M_SQRT2;
+}
diff --git a/tests/lldb/jni/KernelVariables/jnikernelvariables/simple.rs b/tests/lldb/jni/KernelVariables/jnikernelvariables/simple.rs
index 9d6eee2..30feb00 100644
--- a/tests/lldb/jni/KernelVariables/jnikernelvariables/simple.rs
+++ b/tests/lldb/jni/KernelVariables/jnikernelvariables/simple.rs
@@ -174,3 +174,24 @@
     uchar4 result = {1,2,3,4};
     return result;
 }
+
+float use_constants_global;
+
+void setup(void)
+{
+  use_constants_global =
+      M_1_PI +
+      M_2_PI +
+      M_2_PIl +
+      M_2_SQRTPI +
+      M_E +
+      M_LN10 +
+      M_LN2 +
+      M_LOG10E +
+      M_LOG2E +
+      M_PI +
+      M_PI_2 +
+      M_PI_4 +
+      M_SQRT1_2 +
+      M_SQRT2;
+}