blob: a9460abd7511cacbac1d9482d52f95d840c36681 [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
Logan1f028c02010-11-27 01:02:48 +080020#if defined(__arm__)
21# define DEFAULT_ARM_CODEGEN
22# define PROVIDE_ARM_CODEGEN
23#elif defined(__i386__)
24# define DEFAULT_X86_CODEGEN
25# define PROVIDE_X86_CODEGEN
26#elif defined(__x86_64__)
27# define DEFAULT_X64_CODEGEN
28# define PROVIDE_X64_CODEGEN
29#endif
30
31#if defined(FORCE_ARM_CODEGEN)
32# define DEFAULT_ARM_CODEGEN
33# undef DEFAULT_X86_CODEGEN
34# undef DEFAULT_X64_CODEGEN
35# define PROVIDE_ARM_CODEGEN
36# undef PROVIDE_X86_CODEGEN
37# undef PROVIDE_X64_CODEGEN
38#elif defined(FORCE_X86_CODEGEN)
39# undef DEFAULT_ARM_CODEGEN
40# define DEFAULT_X86_CODEGEN
41# undef DEFAULT_X64_CODEGEN
42# undef PROVIDE_ARM_CODEGEN
43# define PROVIDE_X86_CODEGEN
44# undef PROVIDE_X64_CODEGEN
45#elif defined(FORCE_X64_CODEGEN)
46# undef DEFAULT_ARM_CODEGEN
47# undef DEFAULT_X86_CODEGEN
48# define DEFAULT_X64_CODEGEN
49# undef PROVIDE_ARM_CODEGEN
50# undef PROVIDE_X86_CODEGEN
51# define PROVIDE_X64_CODEGEN
52#endif
53
54#if defined(DEFAULT_ARM_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080055# define TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
Logan1f028c02010-11-27 01:02:48 +080056#elif defined(DEFAULT_X86_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080057# define TARGET_TRIPLE_STRING "i686-unknown-linux"
Logan1f028c02010-11-27 01:02:48 +080058#elif defined(DEFAULT_X64_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080059# define TARGET_TRIPLE_STRING "x86_64-unknown-linux"
Logan1f028c02010-11-27 01:02:48 +080060#endif
61
62#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
63# define ARM_USE_VFP
64#endif
65
Loganc4395232010-11-27 18:54:17 +080066#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080067
Loganeb3d12b2010-12-16 06:20:18 +080068#include "ContextManager.h"
Logan2a6dc822011-01-06 04:05:20 +080069#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080070#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080071
Logandf23afa2010-11-27 11:04:54 +080072#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080073
Logandf23afa2010-11-27 11:04:54 +080074#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080075
Logan1f028c02010-11-27 01:02:48 +080076#include "llvm/Bitcode/ReaderWriter.h"
77
Logan1f028c02010-11-27 01:02:48 +080078#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080079#include "llvm/CodeGen/RegAllocRegistry.h"
80#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080081
Logandf23afa2010-11-27 11:04:54 +080082#include "llvm/Transforms/IPO.h"
83#include "llvm/Transforms/Scalar.h"
84
85#include "llvm/Target/SubtargetFeature.h"
86#include "llvm/Target/TargetData.h"
87#include "llvm/Target/TargetMachine.h"
88#include "llvm/Target/TargetOptions.h"
89#include "llvm/Target/TargetRegistry.h"
90#include "llvm/Target/TargetSelect.h"
91
92#include "llvm/Support/ErrorHandling.h"
93#include "llvm/Support/MemoryBuffer.h"
94
95#include "llvm/GlobalValue.h"
96#include "llvm/Linker.h"
97#include "llvm/LLVMContext.h"
98#include "llvm/Metadata.h"
99#include "llvm/Module.h"
100#include "llvm/PassManager.h"
101#include "llvm/Value.h"
102
103#include <errno.h>
104#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +0800105#include <sys/stat.h>
106#include <sys/types.h>
107#include <unistd.h>
108
Logan75cc8a52011-01-07 06:06:52 +0800109#include <string.h>
Logan8b77a772010-12-21 09:11:01 +0800110
Logandf23afa2010-11-27 11:04:54 +0800111#include <string>
112#include <vector>
Logan1f028c02010-11-27 01:02:48 +0800113
Logan1f028c02010-11-27 01:02:48 +0800114namespace bcc {
115
116//////////////////////////////////////////////////////////////////////////////
117// BCC Compiler Static Variables
118//////////////////////////////////////////////////////////////////////////////
119
120bool Compiler::GlobalInitialized = false;
121
Logan1f028c02010-11-27 01:02:48 +0800122// Code generation optimization level for the compiler
123llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
124
125std::string Compiler::Triple;
126
127std::string Compiler::CPU;
128
129std::vector<std::string> Compiler::Features;
130
131// The named of metadata node that pragma resides (should be synced with
132// slang.cpp)
133const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
134
135// The named of metadata node that export variable name resides (should be
136// synced with slang_rs_metadata.h)
137const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
138
139// The named of metadata node that export function name resides (should be
140// synced with slang_rs_metadata.h)
141const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
142
143
144//////////////////////////////////////////////////////////////////////////////
145// Compiler
146//////////////////////////////////////////////////////////////////////////////
147
148void Compiler::GlobalInitialization() {
149 if (GlobalInitialized)
150 return;
151
Logane1323992011-01-12 04:47:13 +0800152 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800153
Logan1f028c02010-11-27 01:02:48 +0800154 // if (!llvm::llvm_is_multithreaded())
155 // llvm::llvm_start_multithreaded();
156
157 // Set Triple, CPU and Features here
158 Triple = TARGET_TRIPLE_STRING;
159
160 // TODO(sliao): NEON for JIT
161 // Features.push_back("+neon");
162 // Features.push_back("+vmlx");
163 // Features.push_back("+neonfp");
164 Features.push_back("+vfp3");
165 Features.push_back("+d16");
166
167#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
168 LLVMInitializeARMTargetInfo();
169 LLVMInitializeARMTarget();
170#if defined(USE_DISASSEMBLER)
171 LLVMInitializeARMDisassembler();
172 LLVMInitializeARMAsmPrinter();
173#endif
174#endif
175
176#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
177 LLVMInitializeX86TargetInfo();
178 LLVMInitializeX86Target();
179#if defined(USE_DISASSEMBLER)
180 LLVMInitializeX86Disassembler();
181 LLVMInitializeX86AsmPrinter();
182#endif
183#endif
184
185#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
186 LLVMInitializeX86TargetInfo();
187 LLVMInitializeX86Target();
188#if defined(USE_DISASSEMBLER)
189 LLVMInitializeX86Disassembler();
190 LLVMInitializeX86AsmPrinter();
191#endif
192#endif
193
194 // -O0: llvm::CodeGenOpt::None
195 // -O1: llvm::CodeGenOpt::Less
196 // -O2: llvm::CodeGenOpt::Default
197 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800198 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800199
200 // Below are the global settings to LLVM
201
202 // Disable frame pointer elimination optimization
203 llvm::NoFramePointerElim = false;
204
205 // Use hardfloat ABI
206 //
207 // TODO(all): Need to detect the CPU capability and decide whether to use
208 // softfp. To use softfp, change following 2 lines to
209 //
210 // llvm::FloatABIType = llvm::FloatABI::Soft;
211 // llvm::UseSoftFloat = true;
212 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800213 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800214 llvm::UseSoftFloat = false;
215
216 // BCC needs all unknown symbols resolved at JIT/compilation time.
217 // So we don't need any dynamic relocation model.
218 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
219
220#if defined(DEFAULT_X64_CODEGEN)
221 // Data address in X86_64 architecture may reside in a far-away place
222 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
223#else
224 // This is set for the linker (specify how large of the virtual addresses
225 // we can access for all unknown symbols.)
226 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
227#endif
228
229 // Register the scheduler
230 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
231
232 // Register allocation policy:
233 // createFastRegisterAllocator: fast but bad quality
234 // createLinearScanRegisterAllocator: not so fast but good quality
235 llvm::RegisterRegAlloc::setDefault
236 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
237 llvm::createFastRegisterAllocator :
238 llvm::createLinearScanRegisterAllocator);
239
Logan75cc8a52011-01-07 06:06:52 +0800240 // Calculate the SHA1 checksum of libbcc and libRS.
Logane1323992011-01-12 04:47:13 +0800241#if defined(USE_LIBBCC_SHA1SUM)
Logan75cc8a52011-01-07 06:06:52 +0800242 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800243#endif
Logan75cc8a52011-01-07 06:06:52 +0800244 calcFileSHA1(sha1LibRS, pathLibRS);
245
Logan1f028c02010-11-27 01:02:48 +0800246 GlobalInitialized = true;
247}
248
249
250void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
251 std::string *Error = static_cast<std::string*>(UserData);
252 Error->assign(Message);
253 LOGE("%s", Message.c_str());
254 exit(1);
255}
256
257
258CodeMemoryManager *Compiler::createCodeMemoryManager() {
259 mCodeMemMgr.reset(new CodeMemoryManager());
260 return mCodeMemMgr.get();
261}
262
263
264CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800265 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800266 return mCodeEmitter.get();
267}
268
269
Logan2a6dc822011-01-06 04:05:20 +0800270Compiler::Compiler(ScriptCompiled *result)
271 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800272 mpSymbolLookupFn(NULL),
273 mpSymbolLookupContext(NULL),
274 mContext(NULL),
275 mModule(NULL),
276 mHasLinked(false) /* Turn off linker */ {
277 llvm::remove_fatal_error_handler();
278 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
279 mContext = new llvm::LLVMContext();
280 return;
281}
282
Shih-wei Liaod1613092010-12-23 22:59:15 +0800283// Compiler::readBC
284// Parameters:
Shih-wei Liaod1613092010-12-23 22:59:15 +0800285//
Logan1f028c02010-11-27 01:02:48 +0800286int Compiler::readBC(const char *bitcode,
287 size_t bitcodeSize,
Shih-wei Liao25e7da42011-01-07 23:55:33 -0800288 const BCCchar *resName /* Deprecated */,
289 const BCCchar *cacheDir /* Deprecated */) {
Logan1f028c02010-11-27 01:02:48 +0800290 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
291
292 if (bitcode == NULL || bitcodeSize <= 0)
293 return 0;
294
295 // Package input to object MemoryBuffer
296 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
297 llvm::StringRef(bitcode, bitcodeSize)));
298
299 if (MEM.get() == NULL) {
300 setError("Error reading input program bitcode into memory");
301 return hasError();
302 }
303
304 // Read the input Bitcode as a Module
305 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
306 MEM.reset();
307 return hasError();
308}
309
310
311int Compiler::linkBC(const char *bitcode, size_t bitcodeSize) {
312 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
313
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800314 if (bitcode == NULL || bitcodeSize <= 0) {
315 LOGE("Invalid bitcode for linkBC: bitcode=%p, size=%lu.\n", bitcode, (unsigned long)bitcodeSize);
316 return 1;
317 }
Logan1f028c02010-11-27 01:02:48 +0800318
319 if (mModule == NULL) {
320 setError("No module presents for linking");
321 return hasError();
322 }
323
324 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
325 llvm::StringRef(bitcode, bitcodeSize)));
326
327 if (MEM.get() == NULL) {
328 setError("Error reading input library bitcode into memory");
329 return hasError();
330 }
331
332 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
333 *mContext,
334 &mError));
335 if (Lib.get() == NULL)
336 return hasError();
337
338 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
339 return hasError();
340
341 // Everything for linking should be settled down here with no error occurs
342 mHasLinked = true;
343 return hasError();
344}
345
346
Logan1f028c02010-11-27 01:02:48 +0800347int Compiler::compile() {
348 llvm::TargetData *TD = NULL;
349
350 llvm::TargetMachine *TM = NULL;
351 const llvm::Target *Target;
352 std::string FeaturesStr;
353
354 llvm::FunctionPassManager *CodeGenPasses = NULL;
355
356 const llvm::NamedMDNode *PragmaMetadata;
357 const llvm::NamedMDNode *ExportVarMetadata;
358 const llvm::NamedMDNode *ExportFuncMetadata;
359
360 if (mModule == NULL) // No module was loaded
361 return 0;
362
363 // Create TargetMachine
364 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
365 if (hasError())
366 goto on_bcc_compile_error;
367
368 if (!CPU.empty() || !Features.empty()) {
369 llvm::SubtargetFeatures F;
370 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800371
372 for (std::vector<std::string>::const_iterator
373 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800374 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800375 }
376
Logan1f028c02010-11-27 01:02:48 +0800377 FeaturesStr = F.getString();
378 }
379
380 TM = Target->createTargetMachine(Triple, FeaturesStr);
381 if (TM == NULL) {
382 setError("Failed to create target machine implementation for the"
383 " specified triple '" + Triple + "'");
384 goto on_bcc_compile_error;
385 }
386
387 // Create memory manager for creation of code emitter later.
388 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
389 setError("Failed to startup memory management for further compilation");
390 goto on_bcc_compile_error;
391 }
Logan02286cb2011-01-07 00:30:47 +0800392
393 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800394
395 // Create code emitter
396 if (!mCodeEmitter.get()) {
397 if (!createCodeEmitter()) {
398 setError("Failed to create machine code emitter to complete"
399 " the compilation");
400 goto on_bcc_compile_error;
401 }
402 } else {
403 // Reuse the code emitter
404 mCodeEmitter->reset();
405 }
406
407 mCodeEmitter->setTargetMachine(*TM);
408 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
409 mpSymbolLookupContext);
410
411 // Get target data from Module
412 TD = new llvm::TargetData(mModule);
413
414 // Load named metadata
415 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
416 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
417 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
418
419 // Create LTO passes and run them on the mModule
420 if (mHasLinked) {
421 llvm::TimePassesIsEnabled = true; // TODO(all)
422 llvm::PassManager LTOPasses;
423 LTOPasses.add(new llvm::TargetData(*TD));
424
425 std::vector<const char*> ExportSymbols;
426
427 // A workaround for getting export variable and function name. Will refine
428 // it soon.
429 if (ExportVarMetadata) {
430 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
431 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
432 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
433 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
434 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
435 llvm::StringRef ExportVarName =
436 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
437 ExportSymbols.push_back(ExportVarName.data());
438 }
439 }
440 }
441 }
442
443 if (ExportFuncMetadata) {
444 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
445 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
446 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
447 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
448 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
449 llvm::StringRef ExportFuncName =
450 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
451 ExportSymbols.push_back(ExportFuncName.data());
452 }
453 }
454 }
455 }
456 // root() and init() are born to be exported
457 ExportSymbols.push_back("root");
458 ExportSymbols.push_back("init");
459
460 // We now create passes list performing LTO. These are copied from
461 // (including comments) llvm::createStandardLTOPasses().
462
463 // Internalize all other symbols not listed in ExportSymbols
464 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
465
466 // Propagate constants at call sites into the functions they call. This
467 // opens opportunities for globalopt (and inlining) by substituting
468 // function pointers passed as arguments to direct uses of functions.
469 LTOPasses.add(llvm::createIPSCCPPass());
470
471 // Now that we internalized some globals, see if we can hack on them!
472 LTOPasses.add(llvm::createGlobalOptimizerPass());
473
474 // Linking modules together can lead to duplicated global constants, only
475 // keep one copy of each constant...
476 LTOPasses.add(llvm::createConstantMergePass());
477
478 // Remove unused arguments from functions...
479 LTOPasses.add(llvm::createDeadArgEliminationPass());
480
481 // Reduce the code after globalopt and ipsccp. Both can open up
482 // significant simplification opportunities, and both can propagate
483 // functions through function pointers. When this happens, we often have
484 // to resolve varargs calls, etc, so let instcombine do this.
485 LTOPasses.add(llvm::createInstructionCombiningPass());
486
487 // Inline small functions
488 LTOPasses.add(llvm::createFunctionInliningPass());
489
490 // Remove dead EH info.
491 LTOPasses.add(llvm::createPruneEHPass());
492
493 // Internalize the globals again after inlining
494 LTOPasses.add(llvm::createGlobalOptimizerPass());
495
496 // Remove dead functions.
497 LTOPasses.add(llvm::createGlobalDCEPass());
498
499 // If we didn't decide to inline a function, check to see if we can
500 // transform it to pass arguments by value instead of by reference.
501 LTOPasses.add(llvm::createArgumentPromotionPass());
502
503 // The IPO passes may leave cruft around. Clean up after them.
504 LTOPasses.add(llvm::createInstructionCombiningPass());
505 LTOPasses.add(llvm::createJumpThreadingPass());
506
507 // Break up allocas
508 LTOPasses.add(llvm::createScalarReplAggregatesPass());
509
510 // Run a few AA driven optimizations here and now, to cleanup the code.
511 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
512 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
513
514 // Hoist loop invariants.
515 LTOPasses.add(llvm::createLICMPass());
516
517 // Remove redundancies.
518 LTOPasses.add(llvm::createGVNPass());
519
520 // Remove dead memcpys.
521 LTOPasses.add(llvm::createMemCpyOptPass());
522
523 // Nuke dead stores.
524 LTOPasses.add(llvm::createDeadStoreEliminationPass());
525
526 // Cleanup and simplify the code after the scalar optimizations.
527 LTOPasses.add(llvm::createInstructionCombiningPass());
528
529 LTOPasses.add(llvm::createJumpThreadingPass());
530
531 // Delete basic blocks, which optimization passes may have killed.
532 LTOPasses.add(llvm::createCFGSimplificationPass());
533
534 // Now that we have optimized the program, discard unreachable functions.
535 LTOPasses.add(llvm::createGlobalDCEPass());
536
537 LTOPasses.run(*mModule);
538 }
539
540 // Create code-gen pass to run the code emitter
541 CodeGenPasses = new llvm::FunctionPassManager(mModule);
542 CodeGenPasses->add(TD); // Will take the ownership of TD
543
544 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
545 *mCodeEmitter,
546 CodeGenOptLevel)) {
547 setError("The machine code emission is not supported by BCC on target '"
548 + Triple + "'");
549 goto on_bcc_compile_error;
550 }
551
552 // Run the pass (the code emitter) on every non-declaration function in the
553 // module
554 CodeGenPasses->doInitialization();
555 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
556 I != E; I++) {
557 if (!I->isDeclaration()) {
558 CodeGenPasses->run(*I);
559 }
560 }
561
562 CodeGenPasses->doFinalization();
563
564 // Copy the global address mapping from code emitter and remapping
565 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800566 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
567
Logan1f028c02010-11-27 01:02:48 +0800568 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
569 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
570 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
571 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
572 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
573 llvm::StringRef ExportVarName =
574 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
575
576 CodeEmitter::global_addresses_const_iterator I, E;
577 for (I = mCodeEmitter->global_address_begin(),
578 E = mCodeEmitter->global_address_end();
579 I != E; I++) {
580 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
581 continue;
582 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800583 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800584 break;
585 }
586 }
587 if (I != mCodeEmitter->global_address_end())
588 continue; // found
589 }
590 }
591 // if reaching here, we know the global variable record in metadata is
592 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800593 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800594 }
Logan2a6dc822011-01-06 04:05:20 +0800595
596 assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
Logan1f028c02010-11-27 01:02:48 +0800597 "Number of slots doesn't match the number of export variables!");
598 }
599
600 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800601 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
602
Logan1f028c02010-11-27 01:02:48 +0800603 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
604 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
605 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
606 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
607 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
608 llvm::StringRef ExportFuncName =
609 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800610 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800611 }
612 }
613 }
614 }
615
616 // Tell code emitter now can release the memory using during the JIT since
617 // we have done the code emission
618 mCodeEmitter->releaseUnnecessary();
619
620 // Finally, read pragma information from the metadata node of the @Module if
621 // any.
Logan2a6dc822011-01-06 04:05:20 +0800622 if (PragmaMetadata) {
623 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
624
Logan1f028c02010-11-27 01:02:48 +0800625 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
626 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
627 if (Pragma != NULL &&
628 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
629 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
630 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
631
632 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
633 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
634 llvm::StringRef PragmaName =
635 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
636 llvm::StringRef PragmaValue =
637 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
638
Logan2a6dc822011-01-06 04:05:20 +0800639 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800640 std::make_pair(std::string(PragmaName.data(),
641 PragmaName.size()),
642 std::string(PragmaValue.data(),
643 PragmaValue.size())));
644 }
645 }
646 }
Logan2a6dc822011-01-06 04:05:20 +0800647 }
Logan1f028c02010-11-27 01:02:48 +0800648
649on_bcc_compile_error:
650 // LOGE("on_bcc_compiler_error");
651 if (CodeGenPasses) {
652 delete CodeGenPasses;
653 } else if (TD) {
654 delete TD;
655 }
656 if (TM)
657 delete TM;
658
659 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800660 return 0;
Logan1f028c02010-11-27 01:02:48 +0800661 }
662
663 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800664 return 1;
Logan1f028c02010-11-27 01:02:48 +0800665}
666
667
Logan1f028c02010-11-27 01:02:48 +0800668Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800669 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800670 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800671
672 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800673}
674
Logan1f028c02010-11-27 01:02:48 +0800675} // namespace bcc