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/Source.h"
18 
19 #include "Log.h"
20 #include "bcc/BCCContext.h"
21 
22 #include <new>
23 
24 #include <llvm/ADT/STLExtras.h>
25 #include <llvm/ADT/StringExtras.h>
26 #include <llvm/Bitcode/ReaderWriter.h>
27 #include <llvm/IR/LLVMContext.h>
28 #include <llvm/IR/Module.h>
29 #include <llvm/IR/Verifier.h>
30 #include <llvm/Linker/Linker.h>
31 #include <llvm/Support/MemoryBuffer.h>
32 #include "llvm/Support/raw_ostream.h"
33 
34 #include "Assert.h"
35 #include "bcinfo/BitcodeWrapper.h"
36 #include "bcinfo/MetadataExtractor.h"
37 
38 #include "BCCContextImpl.h"
39 
40 namespace {
41 
42 // Helper function to load the bitcode. This uses "bitcode lazy load" feature to
43 // reduce the startup time. On success, return the LLVM module object created
44 // and take the ownership of input memory buffer (i.e., pInput). On error,
45 // return nullptr and will NOT take the ownership of pInput.
helper_load_bitcode(llvm::LLVMContext & pContext,std::unique_ptr<llvm::MemoryBuffer> && pInput)46 static inline std::unique_ptr<llvm::Module> helper_load_bitcode(llvm::LLVMContext &pContext,
47                                                 std::unique_ptr<llvm::MemoryBuffer> &&pInput) {
48   auto bufferId = pInput->getBufferIdentifier();
49   llvm::ErrorOr<std::unique_ptr<llvm::Module> > moduleOrError
50       = llvm::getLazyBitcodeModule(std::move(pInput), pContext);
51   if (std::error_code ec = moduleOrError.getError()) {
52     ALOGE("Unable to parse the given bitcode file `%s'! (%s)",
53           bufferId, ec.message().c_str());
54   }
55 
56   return std::move(moduleOrError.get());
57 }
58 
helper_get_module_metadata_from_bitcode_wrapper(uint32_t * compilerVersion,uint32_t * optimizationLevel,const bcinfo::BitcodeWrapper & wrapper)59 static void helper_get_module_metadata_from_bitcode_wrapper(
60     uint32_t *compilerVersion, uint32_t *optimizationLevel,
61     const bcinfo::BitcodeWrapper &wrapper) {
62   *compilerVersion = wrapper.getCompilerVersion();
63   *optimizationLevel = wrapper.getOptimizationLevel();
64 }
65 
helper_set_module_metadata_from_bitcode_wrapper(llvm::Module & module,const uint32_t compilerVersion,const uint32_t optimizationLevel)66 static void helper_set_module_metadata_from_bitcode_wrapper(llvm::Module &module,
67                                                             const uint32_t compilerVersion,
68                                                             const uint32_t optimizationLevel) {
69   llvm::LLVMContext &llvmContext = module.getContext();
70 
71   llvm::NamedMDNode *const wrapperMDNode =
72       module.getOrInsertNamedMetadata(bcinfo::MetadataExtractor::kWrapperMetadataName);
73   bccAssert(wrapperMDNode->getNumOperands() == 0);  // expect to have just now created this node
74 
75   llvm::SmallVector<llvm::Metadata *, 2> wrapperInfo = {
76     llvm::MDString::get(llvmContext, llvm::utostr(compilerVersion)),
77     llvm::MDString::get(llvmContext, llvm::utostr(optimizationLevel))
78   };
79 
80   wrapperMDNode->addOperand(llvm::MDTuple::get(llvmContext, wrapperInfo));
81 }
82 
83 } // end anonymous namespace
84 
85 namespace bcc {
86 
getCompilerVersion() const87 unsigned Source::getCompilerVersion() const {
88   return bcinfo::MetadataExtractor(&getModule()).getCompilerVersion();
89 }
90 
getWrapperInformation(unsigned * compilerVersion,unsigned * optimizationLevel) const91 void Source::getWrapperInformation(unsigned *compilerVersion,
92                                    unsigned *optimizationLevel) const {
93   const bcinfo::MetadataExtractor &me = bcinfo::MetadataExtractor(&getModule());
94   *compilerVersion = me.getCompilerVersion();
95   *optimizationLevel = me.getOptimizationLevel();
96 }
97 
setModule(llvm::Module * pModule)98 void Source::setModule(llvm::Module *pModule) {
99   if (!mNoDelete && (mModule != pModule)) delete mModule;
100   mModule = pModule;
101 }
102 
CreateFromBuffer(BCCContext & pContext,const char * pName,const char * pBitcode,size_t pBitcodeSize)103 Source *Source::CreateFromBuffer(BCCContext &pContext,
104                                  const char *pName,
105                                  const char *pBitcode,
106                                  size_t pBitcodeSize) {
107   llvm::StringRef input_data(pBitcode, pBitcodeSize);
108   std::unique_ptr<llvm::MemoryBuffer> input_memory =
109       llvm::MemoryBuffer::getMemBuffer(input_data, "", false);
110 
111   if (input_memory == nullptr) {
112     ALOGE("Unable to load bitcode `%s' from buffer!", pName);
113     return nullptr;
114   }
115 
116   auto managedModule = helper_load_bitcode(pContext.mImpl->mLLVMContext,
117                                            std::move(input_memory));
118 
119   // Release the managed llvm::Module* since this object gets deleted either in
120   // the error check below or in ~Source() (since pNoDelete is false).
121   llvm::Module *module = managedModule.release();
122   if (module == nullptr) {
123     return nullptr;
124   }
125 
126   uint32_t compilerVersion, optimizationLevel;
127   helper_get_module_metadata_from_bitcode_wrapper(&compilerVersion, &optimizationLevel,
128                                                   bcinfo::BitcodeWrapper(pBitcode, pBitcodeSize));
129   Source *result = CreateFromModule(pContext, pName, *module,
130                                     compilerVersion, optimizationLevel,
131                                     /* pNoDelete */false);
132   if (result == nullptr) {
133     delete module;
134   }
135 
136   return result;
137 }
138 
CreateFromFile(BCCContext & pContext,const std::string & pPath)139 Source *Source::CreateFromFile(BCCContext &pContext, const std::string &pPath) {
140 
141   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> mb_or_error =
142       llvm::MemoryBuffer::getFile(pPath);
143   if (mb_or_error.getError()) {
144     ALOGE("Failed to load bitcode from path %s! (%s)", pPath.c_str(),
145           mb_or_error.getError().message().c_str());
146     return nullptr;
147   }
148   std::unique_ptr<llvm::MemoryBuffer> input_data = std::move(mb_or_error.get());
149 
150   uint32_t compilerVersion, optimizationLevel;
151   helper_get_module_metadata_from_bitcode_wrapper(&compilerVersion, &optimizationLevel,
152                                                   bcinfo::BitcodeWrapper(input_data->getBufferStart(),
153                                                                          input_data->getBufferSize()));
154 
155   std::unique_ptr<llvm::MemoryBuffer> input_memory(input_data.release());
156   auto managedModule = helper_load_bitcode(pContext.mImpl->mLLVMContext,
157                                            std::move(input_memory));
158 
159   // Release the managed llvm::Module* since this object gets deleted either in
160   // the error check below or in ~Source() (since pNoDelete is false).
161   llvm::Module *module = managedModule.release();
162   if (module == nullptr) {
163     return nullptr;
164   }
165 
166   Source *result = CreateFromModule(pContext, pPath.c_str(), *module,
167                                     compilerVersion, optimizationLevel,
168                                     /* pNoDelete */false);
169   if (result == nullptr) {
170     delete module;
171   }
172 
173   return result;
174 }
175 
CreateFromModule(BCCContext & pContext,const char * name,llvm::Module & pModule,const uint32_t compilerVersion,const uint32_t optimizationLevel,bool pNoDelete)176 Source *Source::CreateFromModule(BCCContext &pContext, const char* name, llvm::Module &pModule,
177                                  const uint32_t compilerVersion,
178                                  const uint32_t optimizationLevel,
179                                  bool pNoDelete) {
180   std::string ErrorInfo;
181   llvm::raw_string_ostream ErrorStream(ErrorInfo);
182   pModule.materializeAll();
183   if (llvm::verifyModule(pModule, &ErrorStream)) {
184     ALOGE("Bitcode of RenderScript module does not pass verification: `%s'!",
185           ErrorStream.str().c_str());
186     return nullptr;
187   }
188 
189   Source *result = new (std::nothrow) Source(name, pContext, pModule, pNoDelete);
190   if (result == nullptr) {
191     ALOGE("Out of memory during Source object allocation for `%s'!",
192           pModule.getModuleIdentifier().c_str());
193   }
194   helper_set_module_metadata_from_bitcode_wrapper(pModule, compilerVersion, optimizationLevel);
195   return result;
196 }
197 
Source(const char * name,BCCContext & pContext,llvm::Module & pModule,bool pNoDelete)198 Source::Source(const char* name, BCCContext &pContext, llvm::Module &pModule,
199                bool pNoDelete)
200     : mName(name), mContext(pContext), mModule(&pModule), mMetadata(nullptr),
201       mNoDelete(pNoDelete), mIsModuleDestroyed(false) {
202     pContext.addSource(*this);
203 }
204 
~Source()205 Source::~Source() {
206   mContext.removeSource(*this);
207   if (!mNoDelete && !mIsModuleDestroyed)
208     delete mModule;
209   delete mMetadata;
210 }
211 
merge(Source & pSource)212 bool Source::merge(Source &pSource) {
213   // TODO(srhines): Add back logging of actual diagnostics from linking.
214   if (llvm::Linker::linkModules(*mModule, std::unique_ptr<llvm::Module>(&pSource.getModule())) != 0) {
215     ALOGE("Failed to link source `%s' with `%s'!",
216           getIdentifier().c_str(), pSource.getIdentifier().c_str());
217     return false;
218   }
219   // pSource.getModule() is destroyed after linking.
220   pSource.markModuleDestroyed();
221 
222   return true;
223 }
224 
getIdentifier() const225 const std::string &Source::getIdentifier() const {
226   return mModule->getModuleIdentifier();
227 }
228 
addBuildChecksumMetadata(const char * buildChecksum) const229 void Source::addBuildChecksumMetadata(const char *buildChecksum) const {
230     llvm::LLVMContext &context = mContext.mImpl->mLLVMContext;
231     llvm::MDString *val = llvm::MDString::get(context, buildChecksum);
232     llvm::NamedMDNode *node =
233         mModule->getOrInsertNamedMetadata("#rs_build_checksum");
234     node->addOperand(llvm::MDNode::get(context, val));
235 }
236 
getDebugInfoEnabled() const237 bool Source::getDebugInfoEnabled() const {
238   return mModule->getNamedMetadata("llvm.dbg.cu") != nullptr;
239 }
240 
extractMetadata()241 bool Source::extractMetadata() {
242   mMetadata = new bcinfo::MetadataExtractor(mModule);
243   return mMetadata->extract();
244 }
245 
246 } // namespace bcc
247