blob: e13d98959c35dcdb097b0a083688bea42ea3af09 [file] [log] [blame]
Logan1f028c02010-11-27 01:02:48 +08001/*
2 * Copyright 2010, 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#define LOG_TAG "bcc"
18#include <cutils/log.h>
19
Loganc4395232010-11-27 18:54:17 +080020#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080021
Logan35849002011-01-15 07:30:43 +080022#include "Config.h"
23
Loganeb3d12b2010-12-16 06:20:18 +080024#include "ContextManager.h"
Logan2a6dc822011-01-06 04:05:20 +080025#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080026#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080027
Logandf23afa2010-11-27 11:04:54 +080028#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080029
Logandf23afa2010-11-27 11:04:54 +080030#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080031
Logan1f028c02010-11-27 01:02:48 +080032#include "llvm/Bitcode/ReaderWriter.h"
33
Logan1f028c02010-11-27 01:02:48 +080034#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080035#include "llvm/CodeGen/RegAllocRegistry.h"
36#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080037
Logandf23afa2010-11-27 11:04:54 +080038#include "llvm/Transforms/IPO.h"
39#include "llvm/Transforms/Scalar.h"
40
41#include "llvm/Target/SubtargetFeature.h"
42#include "llvm/Target/TargetData.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include "llvm/Target/TargetRegistry.h"
46#include "llvm/Target/TargetSelect.h"
47
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MemoryBuffer.h"
50
51#include "llvm/GlobalValue.h"
52#include "llvm/Linker.h"
53#include "llvm/LLVMContext.h"
54#include "llvm/Metadata.h"
55#include "llvm/Module.h"
56#include "llvm/PassManager.h"
57#include "llvm/Value.h"
58
59#include <errno.h>
60#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +080061#include <sys/stat.h>
62#include <sys/types.h>
63#include <unistd.h>
64
Logan75cc8a52011-01-07 06:06:52 +080065#include <string.h>
Logan8b77a772010-12-21 09:11:01 +080066
Logandf23afa2010-11-27 11:04:54 +080067#include <string>
68#include <vector>
Logan1f028c02010-11-27 01:02:48 +080069
Logan1f028c02010-11-27 01:02:48 +080070namespace bcc {
71
72//////////////////////////////////////////////////////////////////////////////
73// BCC Compiler Static Variables
74//////////////////////////////////////////////////////////////////////////////
75
76bool Compiler::GlobalInitialized = false;
77
Logan1f028c02010-11-27 01:02:48 +080078// Code generation optimization level for the compiler
79llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
80
81std::string Compiler::Triple;
82
83std::string Compiler::CPU;
84
85std::vector<std::string> Compiler::Features;
86
87// The named of metadata node that pragma resides (should be synced with
88// slang.cpp)
89const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
90
91// The named of metadata node that export variable name resides (should be
92// synced with slang_rs_metadata.h)
93const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
94
95// The named of metadata node that export function name resides (should be
96// synced with slang_rs_metadata.h)
97const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
98
99
100//////////////////////////////////////////////////////////////////////////////
101// Compiler
102//////////////////////////////////////////////////////////////////////////////
103
104void Compiler::GlobalInitialization() {
105 if (GlobalInitialized)
106 return;
107
Logane1323992011-01-12 04:47:13 +0800108 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800109
Logan1f028c02010-11-27 01:02:48 +0800110 // if (!llvm::llvm_is_multithreaded())
111 // llvm::llvm_start_multithreaded();
112
113 // Set Triple, CPU and Features here
114 Triple = TARGET_TRIPLE_STRING;
115
116 // TODO(sliao): NEON for JIT
117 // Features.push_back("+neon");
118 // Features.push_back("+vmlx");
119 // Features.push_back("+neonfp");
120 Features.push_back("+vfp3");
121 Features.push_back("+d16");
122
123#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
124 LLVMInitializeARMTargetInfo();
125 LLVMInitializeARMTarget();
Logan35849002011-01-15 07:30:43 +0800126#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800127 LLVMInitializeARMDisassembler();
128 LLVMInitializeARMAsmPrinter();
129#endif
130#endif
131
132#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
133 LLVMInitializeX86TargetInfo();
134 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800135#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800136 LLVMInitializeX86Disassembler();
137 LLVMInitializeX86AsmPrinter();
138#endif
139#endif
140
141#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
142 LLVMInitializeX86TargetInfo();
143 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800144#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800145 LLVMInitializeX86Disassembler();
146 LLVMInitializeX86AsmPrinter();
147#endif
148#endif
149
150 // -O0: llvm::CodeGenOpt::None
151 // -O1: llvm::CodeGenOpt::Less
152 // -O2: llvm::CodeGenOpt::Default
153 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800154 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800155
156 // Below are the global settings to LLVM
157
158 // Disable frame pointer elimination optimization
159 llvm::NoFramePointerElim = false;
160
161 // Use hardfloat ABI
162 //
163 // TODO(all): Need to detect the CPU capability and decide whether to use
164 // softfp. To use softfp, change following 2 lines to
165 //
166 // llvm::FloatABIType = llvm::FloatABI::Soft;
167 // llvm::UseSoftFloat = true;
168 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800169 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800170 llvm::UseSoftFloat = false;
171
172 // BCC needs all unknown symbols resolved at JIT/compilation time.
173 // So we don't need any dynamic relocation model.
174 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
175
176#if defined(DEFAULT_X64_CODEGEN)
177 // Data address in X86_64 architecture may reside in a far-away place
178 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
179#else
180 // This is set for the linker (specify how large of the virtual addresses
181 // we can access for all unknown symbols.)
182 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
183#endif
184
185 // Register the scheduler
186 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
187
188 // Register allocation policy:
189 // createFastRegisterAllocator: fast but bad quality
190 // createLinearScanRegisterAllocator: not so fast but good quality
191 llvm::RegisterRegAlloc::setDefault
192 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
193 llvm::createFastRegisterAllocator :
194 llvm::createLinearScanRegisterAllocator);
195
Logan35849002011-01-15 07:30:43 +0800196#if USE_CACHE
Logan75cc8a52011-01-07 06:06:52 +0800197 // Calculate the SHA1 checksum of libbcc and libRS.
Logan35849002011-01-15 07:30:43 +0800198#if USE_LIBBCC_SHA1SUM
Logan75cc8a52011-01-07 06:06:52 +0800199 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800200#endif
Logan75cc8a52011-01-07 06:06:52 +0800201 calcFileSHA1(sha1LibRS, pathLibRS);
Logan35849002011-01-15 07:30:43 +0800202#endif
Logan75cc8a52011-01-07 06:06:52 +0800203
Logan1f028c02010-11-27 01:02:48 +0800204 GlobalInitialized = true;
205}
206
207
208void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
209 std::string *Error = static_cast<std::string*>(UserData);
210 Error->assign(Message);
211 LOGE("%s", Message.c_str());
212 exit(1);
213}
214
215
216CodeMemoryManager *Compiler::createCodeMemoryManager() {
217 mCodeMemMgr.reset(new CodeMemoryManager());
218 return mCodeMemMgr.get();
219}
220
221
222CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800223 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800224 return mCodeEmitter.get();
225}
226
227
Logan2a6dc822011-01-06 04:05:20 +0800228Compiler::Compiler(ScriptCompiled *result)
229 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800230 mpSymbolLookupFn(NULL),
231 mpSymbolLookupContext(NULL),
232 mContext(NULL),
233 mModule(NULL),
234 mHasLinked(false) /* Turn off linker */ {
235 llvm::remove_fatal_error_handler();
236 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
237 mContext = new llvm::LLVMContext();
238 return;
239}
240
Shih-wei Liaod1613092010-12-23 22:59:15 +0800241// Compiler::readBC
242// Parameters:
Shih-wei Liaod1613092010-12-23 22:59:15 +0800243//
Loganf340bf72011-01-14 17:51:40 +0800244int Compiler::readBC(const char *bitcode, size_t bitcodeSize) {
Logan1f028c02010-11-27 01:02:48 +0800245 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
246
247 if (bitcode == NULL || bitcodeSize <= 0)
Loganf340bf72011-01-14 17:51:40 +0800248 return 1;
Logan1f028c02010-11-27 01:02:48 +0800249
250 // Package input to object MemoryBuffer
251 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
252 llvm::StringRef(bitcode, bitcodeSize)));
253
254 if (MEM.get() == NULL) {
255 setError("Error reading input program bitcode into memory");
256 return hasError();
257 }
258
259 // Read the input Bitcode as a Module
260 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
261 MEM.reset();
262 return hasError();
263}
264
265
266int Compiler::linkBC(const char *bitcode, size_t bitcodeSize) {
267 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
268
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800269 if (bitcode == NULL || bitcodeSize <= 0) {
Loganf340bf72011-01-14 17:51:40 +0800270 LOGE("Invalid bitcode for linkBC\n");
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800271 return 1;
272 }
Logan1f028c02010-11-27 01:02:48 +0800273
274 if (mModule == NULL) {
275 setError("No module presents for linking");
276 return hasError();
277 }
278
Shih-wei Liao847181c2011-01-16 03:36:07 -0800279#if 1
Shih-wei Liao8b67c072011-01-13 01:51:57 -0800280 MEM.reset(llvm::MemoryBuffer::getFile("/system/lib/rslib.bc"));
Shih-wei Liao8b67c072011-01-13 01:51:57 -0800281
Shih-wei Liao847181c2011-01-16 03:36:07 -0800282#else
Logan1f028c02010-11-27 01:02:48 +0800283 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
284 llvm::StringRef(bitcode, bitcodeSize)));
Shih-wei Liao847181c2011-01-16 03:36:07 -0800285#endif
Logan1f028c02010-11-27 01:02:48 +0800286
287 if (MEM.get() == NULL) {
288 setError("Error reading input library bitcode into memory");
289 return hasError();
290 }
291
292 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
293 *mContext,
294 &mError));
295 if (Lib.get() == NULL)
296 return hasError();
297
298 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
299 return hasError();
300
301 // Everything for linking should be settled down here with no error occurs
302 mHasLinked = true;
303 return hasError();
304}
305
306
Logan1f028c02010-11-27 01:02:48 +0800307int Compiler::compile() {
308 llvm::TargetData *TD = NULL;
309
310 llvm::TargetMachine *TM = NULL;
311 const llvm::Target *Target;
312 std::string FeaturesStr;
313
314 llvm::FunctionPassManager *CodeGenPasses = NULL;
315
316 const llvm::NamedMDNode *PragmaMetadata;
317 const llvm::NamedMDNode *ExportVarMetadata;
318 const llvm::NamedMDNode *ExportFuncMetadata;
319
320 if (mModule == NULL) // No module was loaded
321 return 0;
322
323 // Create TargetMachine
324 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
325 if (hasError())
326 goto on_bcc_compile_error;
327
328 if (!CPU.empty() || !Features.empty()) {
329 llvm::SubtargetFeatures F;
330 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800331
332 for (std::vector<std::string>::const_iterator
333 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800334 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800335 }
336
Logan1f028c02010-11-27 01:02:48 +0800337 FeaturesStr = F.getString();
338 }
339
340 TM = Target->createTargetMachine(Triple, FeaturesStr);
341 if (TM == NULL) {
342 setError("Failed to create target machine implementation for the"
343 " specified triple '" + Triple + "'");
344 goto on_bcc_compile_error;
345 }
346
347 // Create memory manager for creation of code emitter later.
348 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
349 setError("Failed to startup memory management for further compilation");
350 goto on_bcc_compile_error;
351 }
Logan02286cb2011-01-07 00:30:47 +0800352
353 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800354
355 // Create code emitter
356 if (!mCodeEmitter.get()) {
357 if (!createCodeEmitter()) {
358 setError("Failed to create machine code emitter to complete"
359 " the compilation");
360 goto on_bcc_compile_error;
361 }
362 } else {
363 // Reuse the code emitter
364 mCodeEmitter->reset();
365 }
366
367 mCodeEmitter->setTargetMachine(*TM);
368 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
369 mpSymbolLookupContext);
370
371 // Get target data from Module
372 TD = new llvm::TargetData(mModule);
373
374 // Load named metadata
375 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
376 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
377 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
378
379 // Create LTO passes and run them on the mModule
380 if (mHasLinked) {
381 llvm::TimePassesIsEnabled = true; // TODO(all)
382 llvm::PassManager LTOPasses;
383 LTOPasses.add(new llvm::TargetData(*TD));
384
385 std::vector<const char*> ExportSymbols;
386
387 // A workaround for getting export variable and function name. Will refine
388 // it soon.
389 if (ExportVarMetadata) {
390 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
391 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
392 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
393 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
394 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
395 llvm::StringRef ExportVarName =
396 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
397 ExportSymbols.push_back(ExportVarName.data());
398 }
399 }
400 }
401 }
402
403 if (ExportFuncMetadata) {
404 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
405 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
406 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
407 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
408 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
409 llvm::StringRef ExportFuncName =
410 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
411 ExportSymbols.push_back(ExportFuncName.data());
412 }
413 }
414 }
415 }
416 // root() and init() are born to be exported
417 ExportSymbols.push_back("root");
418 ExportSymbols.push_back("init");
419
420 // We now create passes list performing LTO. These are copied from
421 // (including comments) llvm::createStandardLTOPasses().
422
423 // Internalize all other symbols not listed in ExportSymbols
424 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
425
426 // Propagate constants at call sites into the functions they call. This
427 // opens opportunities for globalopt (and inlining) by substituting
428 // function pointers passed as arguments to direct uses of functions.
429 LTOPasses.add(llvm::createIPSCCPPass());
430
431 // Now that we internalized some globals, see if we can hack on them!
432 LTOPasses.add(llvm::createGlobalOptimizerPass());
433
434 // Linking modules together can lead to duplicated global constants, only
435 // keep one copy of each constant...
436 LTOPasses.add(llvm::createConstantMergePass());
437
438 // Remove unused arguments from functions...
439 LTOPasses.add(llvm::createDeadArgEliminationPass());
440
441 // Reduce the code after globalopt and ipsccp. Both can open up
442 // significant simplification opportunities, and both can propagate
443 // functions through function pointers. When this happens, we often have
444 // to resolve varargs calls, etc, so let instcombine do this.
445 LTOPasses.add(llvm::createInstructionCombiningPass());
446
447 // Inline small functions
448 LTOPasses.add(llvm::createFunctionInliningPass());
449
450 // Remove dead EH info.
451 LTOPasses.add(llvm::createPruneEHPass());
452
453 // Internalize the globals again after inlining
454 LTOPasses.add(llvm::createGlobalOptimizerPass());
455
456 // Remove dead functions.
457 LTOPasses.add(llvm::createGlobalDCEPass());
458
459 // If we didn't decide to inline a function, check to see if we can
460 // transform it to pass arguments by value instead of by reference.
461 LTOPasses.add(llvm::createArgumentPromotionPass());
462
463 // The IPO passes may leave cruft around. Clean up after them.
464 LTOPasses.add(llvm::createInstructionCombiningPass());
465 LTOPasses.add(llvm::createJumpThreadingPass());
466
467 // Break up allocas
468 LTOPasses.add(llvm::createScalarReplAggregatesPass());
469
470 // Run a few AA driven optimizations here and now, to cleanup the code.
471 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
472 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
473
474 // Hoist loop invariants.
475 LTOPasses.add(llvm::createLICMPass());
476
477 // Remove redundancies.
478 LTOPasses.add(llvm::createGVNPass());
479
480 // Remove dead memcpys.
481 LTOPasses.add(llvm::createMemCpyOptPass());
482
483 // Nuke dead stores.
484 LTOPasses.add(llvm::createDeadStoreEliminationPass());
485
486 // Cleanup and simplify the code after the scalar optimizations.
487 LTOPasses.add(llvm::createInstructionCombiningPass());
488
489 LTOPasses.add(llvm::createJumpThreadingPass());
490
491 // Delete basic blocks, which optimization passes may have killed.
492 LTOPasses.add(llvm::createCFGSimplificationPass());
493
494 // Now that we have optimized the program, discard unreachable functions.
495 LTOPasses.add(llvm::createGlobalDCEPass());
496
497 LTOPasses.run(*mModule);
498 }
499
500 // Create code-gen pass to run the code emitter
501 CodeGenPasses = new llvm::FunctionPassManager(mModule);
502 CodeGenPasses->add(TD); // Will take the ownership of TD
503
504 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
505 *mCodeEmitter,
506 CodeGenOptLevel)) {
507 setError("The machine code emission is not supported by BCC on target '"
508 + Triple + "'");
509 goto on_bcc_compile_error;
510 }
511
512 // Run the pass (the code emitter) on every non-declaration function in the
513 // module
514 CodeGenPasses->doInitialization();
515 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
516 I != E; I++) {
517 if (!I->isDeclaration()) {
518 CodeGenPasses->run(*I);
519 }
520 }
521
522 CodeGenPasses->doFinalization();
523
524 // Copy the global address mapping from code emitter and remapping
525 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800526 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
527
Logan1f028c02010-11-27 01:02:48 +0800528 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
529 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
530 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
531 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
532 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
533 llvm::StringRef ExportVarName =
534 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
535
536 CodeEmitter::global_addresses_const_iterator I, E;
537 for (I = mCodeEmitter->global_address_begin(),
538 E = mCodeEmitter->global_address_end();
539 I != E; I++) {
540 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
541 continue;
542 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800543 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800544 break;
545 }
546 }
547 if (I != mCodeEmitter->global_address_end())
548 continue; // found
549 }
550 }
551 // if reaching here, we know the global variable record in metadata is
552 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800553 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800554 }
Logan2a6dc822011-01-06 04:05:20 +0800555
556 assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
Logan1f028c02010-11-27 01:02:48 +0800557 "Number of slots doesn't match the number of export variables!");
558 }
559
560 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800561 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
562
Logan1f028c02010-11-27 01:02:48 +0800563 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
564 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
565 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
566 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
567 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
568 llvm::StringRef ExportFuncName =
569 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800570 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800571 }
572 }
573 }
574 }
575
576 // Tell code emitter now can release the memory using during the JIT since
577 // we have done the code emission
578 mCodeEmitter->releaseUnnecessary();
579
580 // Finally, read pragma information from the metadata node of the @Module if
581 // any.
Logan2a6dc822011-01-06 04:05:20 +0800582 if (PragmaMetadata) {
583 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
584
Logan1f028c02010-11-27 01:02:48 +0800585 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
586 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
587 if (Pragma != NULL &&
588 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
589 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
590 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
591
592 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
593 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
594 llvm::StringRef PragmaName =
595 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
596 llvm::StringRef PragmaValue =
597 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
598
Logan2a6dc822011-01-06 04:05:20 +0800599 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800600 std::make_pair(std::string(PragmaName.data(),
601 PragmaName.size()),
602 std::string(PragmaValue.data(),
603 PragmaValue.size())));
604 }
605 }
606 }
Logan2a6dc822011-01-06 04:05:20 +0800607 }
Logan1f028c02010-11-27 01:02:48 +0800608
609on_bcc_compile_error:
610 // LOGE("on_bcc_compiler_error");
611 if (CodeGenPasses) {
612 delete CodeGenPasses;
613 } else if (TD) {
614 delete TD;
615 }
616 if (TM)
617 delete TM;
618
619 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800620 return 0;
Logan1f028c02010-11-27 01:02:48 +0800621 }
622
623 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800624 return 1;
Logan1f028c02010-11-27 01:02:48 +0800625}
626
627
Logan1f028c02010-11-27 01:02:48 +0800628Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800629 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800630 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800631
632 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800633}
634
Logan1f028c02010-11-27 01:02:48 +0800635} // namespace bcc