blob: 27da775659f938b2d9ba42e3b24985951427cf31 [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
Loganc4395232010-11-27 18:54:17 +080017#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080018
Logan35849002011-01-15 07:30:43 +080019#include "Config.h"
20
Loganeb3d12b2010-12-16 06:20:18 +080021#include "ContextManager.h"
Logan4dcd6792011-02-28 05:12:00 +080022#include "DebugHelper.h"
Shih-wei Liao6c0c7b02011-05-21 21:47:14 -070023#include "FileHandle.h"
Logan2a6dc822011-01-06 04:05:20 +080024#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080025#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080026
Logandf23afa2010-11-27 11:04:54 +080027#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080028
Logandf23afa2010-11-27 11:04:54 +080029#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080030
Logan1f028c02010-11-27 01:02:48 +080031#include "llvm/Bitcode/ReaderWriter.h"
32
Logan1f028c02010-11-27 01:02:48 +080033#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080034#include "llvm/CodeGen/RegAllocRegistry.h"
35#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080036
Logandf23afa2010-11-27 11:04:54 +080037#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/Scalar.h"
39
40#include "llvm/Target/SubtargetFeature.h"
41#include "llvm/Target/TargetData.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetOptions.h"
44#include "llvm/Target/TargetRegistry.h"
45#include "llvm/Target/TargetSelect.h"
46
47#include "llvm/Support/ErrorHandling.h"
Shih-wei Liao898c5a92011-05-18 07:02:39 -070048#include "llvm/Support/FormattedStream.h"
Logandf23afa2010-11-27 11:04:54 +080049#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
Stephen Hines071288a2011-01-27 14:38:26 -080087// Name of metadata node where pragma info resides (should be synced with
Logan1f028c02010-11-27 01:02:48 +080088// slang.cpp)
89const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
90
Stephen Hines071288a2011-01-27 14:38:26 -080091// Name of metadata node where exported variable names reside (should be
Logan1f028c02010-11-27 01:02:48 +080092// synced with slang_rs_metadata.h)
93const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
94
Stephen Hines071288a2011-01-27 14:38:26 -080095// Name of metadata node where exported function names reside (should be
Logan1f028c02010-11-27 01:02:48 +080096// synced with slang_rs_metadata.h)
97const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
98
Stephen Hines071288a2011-01-27 14:38:26 -080099// Name of metadata node where RS object slot info resides (should be
100// synced with slang_rs_metadata.h)
101const llvm::StringRef Compiler::ObjectSlotMetadataName = "#rs_object_slots";
Logan1f028c02010-11-27 01:02:48 +0800102
103//////////////////////////////////////////////////////////////////////////////
104// Compiler
105//////////////////////////////////////////////////////////////////////////////
106
107void Compiler::GlobalInitialization() {
108 if (GlobalInitialized)
109 return;
110
Logane1323992011-01-12 04:47:13 +0800111 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800112
Logan1f028c02010-11-27 01:02:48 +0800113 // if (!llvm::llvm_is_multithreaded())
114 // llvm::llvm_start_multithreaded();
115
116 // Set Triple, CPU and Features here
117 Triple = TARGET_TRIPLE_STRING;
118
Logan1f028c02010-11-27 01:02:48 +0800119 Features.push_back("+vfp3");
120 Features.push_back("+d16");
121
Logan4fe966f2011-02-27 08:26:40 +0800122 // NOTE: Currently, we have to turn off the support for NEON explicitly.
123 // Since the ARMCodeEmitter.cpp is not ready for JITing NEON
124 // instructions.
125 Features.push_back("-neon"); // TODO(sliao): NEON for JIT
126 Features.push_back("-neonfp");
127 Features.push_back("-vmlx");
128
Logan1f028c02010-11-27 01:02:48 +0800129#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
130 LLVMInitializeARMTargetInfo();
131 LLVMInitializeARMTarget();
Logan35849002011-01-15 07:30:43 +0800132#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800133 LLVMInitializeARMDisassembler();
134 LLVMInitializeARMAsmPrinter();
135#endif
136#endif
137
138#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
139 LLVMInitializeX86TargetInfo();
140 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800141#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800142 LLVMInitializeX86Disassembler();
143 LLVMInitializeX86AsmPrinter();
144#endif
145#endif
146
147#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
148 LLVMInitializeX86TargetInfo();
149 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800150#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800151 LLVMInitializeX86Disassembler();
152 LLVMInitializeX86AsmPrinter();
153#endif
154#endif
155
156 // -O0: llvm::CodeGenOpt::None
157 // -O1: llvm::CodeGenOpt::Less
158 // -O2: llvm::CodeGenOpt::Default
159 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800160 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800161
162 // Below are the global settings to LLVM
163
164 // Disable frame pointer elimination optimization
165 llvm::NoFramePointerElim = false;
166
167 // Use hardfloat ABI
168 //
169 // TODO(all): Need to detect the CPU capability and decide whether to use
170 // softfp. To use softfp, change following 2 lines to
171 //
172 // llvm::FloatABIType = llvm::FloatABI::Soft;
173 // llvm::UseSoftFloat = true;
174 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800175 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800176 llvm::UseSoftFloat = false;
177
178 // BCC needs all unknown symbols resolved at JIT/compilation time.
179 // So we don't need any dynamic relocation model.
180 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
181
182#if defined(DEFAULT_X64_CODEGEN)
183 // Data address in X86_64 architecture may reside in a far-away place
184 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
185#else
186 // This is set for the linker (specify how large of the virtual addresses
187 // we can access for all unknown symbols.)
188 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
189#endif
190
191 // Register the scheduler
192 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
193
194 // Register allocation policy:
195 // createFastRegisterAllocator: fast but bad quality
196 // createLinearScanRegisterAllocator: not so fast but good quality
197 llvm::RegisterRegAlloc::setDefault
198 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
199 llvm::createFastRegisterAllocator :
200 llvm::createLinearScanRegisterAllocator);
201
Logan35849002011-01-15 07:30:43 +0800202#if USE_CACHE
Logan75cc8a52011-01-07 06:06:52 +0800203 // Calculate the SHA1 checksum of libbcc and libRS.
Logan35849002011-01-15 07:30:43 +0800204#if USE_LIBBCC_SHA1SUM
Logan75cc8a52011-01-07 06:06:52 +0800205 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800206#endif
Logan75cc8a52011-01-07 06:06:52 +0800207 calcFileSHA1(sha1LibRS, pathLibRS);
Logan35849002011-01-15 07:30:43 +0800208#endif
Logan75cc8a52011-01-07 06:06:52 +0800209
Logan1f028c02010-11-27 01:02:48 +0800210 GlobalInitialized = true;
211}
212
213
214void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
215 std::string *Error = static_cast<std::string*>(UserData);
216 Error->assign(Message);
217 LOGE("%s", Message.c_str());
218 exit(1);
219}
220
221
222CodeMemoryManager *Compiler::createCodeMemoryManager() {
223 mCodeMemMgr.reset(new CodeMemoryManager());
224 return mCodeMemMgr.get();
225}
226
227
228CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800229 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800230 return mCodeEmitter.get();
231}
232
233
Logan2a6dc822011-01-06 04:05:20 +0800234Compiler::Compiler(ScriptCompiled *result)
235 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800236 mpSymbolLookupFn(NULL),
237 mpSymbolLookupContext(NULL),
238 mContext(NULL),
239 mModule(NULL),
240 mHasLinked(false) /* Turn off linker */ {
241 llvm::remove_fatal_error_handler();
242 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
243 mContext = new llvm::LLVMContext();
244 return;
245}
246
Logan1f028c02010-11-27 01:02:48 +0800247
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700248// input objPath: For example,
249// /data/user/0/com.example.android.rs.fountain/cache/
250// @com.example.android.rs.fountain:raw@fountain.oBCC
251// output objPath: /data/user/0/com.example.android.rs.fountain/cache/
252// fountain.o
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700253//
254bool Compiler::getObjPath(std::string &objPath) {
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700255 size_t found0 = objPath.find("@");
256 size_t found1 = objPath.rfind("@");
257
258 if (found0 == found1 ||
259 found0 == string::npos ||
260 found1 == string::npos) {
261 LOGE("Ill formatted resource name '%s'. The name should contain 2 @s",
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700262 objPath.c_str());
263 return false;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700264 }
265
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700266 objPath.replace(found0, found1 - found0 + 1, "", 0);
267 objPath.resize(objPath.length() - 3);
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700268
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700269 LOGV("objPath = %s", objPath.c_str());
270 return true;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700271}
272
273
Logan474cbd22011-01-31 01:47:44 +0800274llvm::Module *Compiler::parseBitcodeFile(llvm::MemoryBuffer *MEM) {
275 llvm::Module *result = llvm::ParseBitcodeFile(MEM, *mContext, &mError);
Logan1f028c02010-11-27 01:02:48 +0800276
Logan474cbd22011-01-31 01:47:44 +0800277 if (!result) {
278 LOGE("Unable to ParseBitcodeFile: %s\n", mError.c_str());
279 return NULL;
Logan1f028c02010-11-27 01:02:48 +0800280 }
281
Logan474cbd22011-01-31 01:47:44 +0800282 return result;
Logan1f028c02010-11-27 01:02:48 +0800283}
284
285
Logan474cbd22011-01-31 01:47:44 +0800286int Compiler::linkModule(llvm::Module *moduleWith) {
287 if (llvm::Linker::LinkModules(mModule, moduleWith, &mError) != 0) {
Logan1f028c02010-11-27 01:02:48 +0800288 return hasError();
289 }
290
Logan1f028c02010-11-27 01:02:48 +0800291 // Everything for linking should be settled down here with no error occurs
292 mHasLinked = true;
293 return hasError();
294}
295
296
Logan1f028c02010-11-27 01:02:48 +0800297int Compiler::compile() {
298 llvm::TargetData *TD = NULL;
299
300 llvm::TargetMachine *TM = NULL;
301 const llvm::Target *Target;
302 std::string FeaturesStr;
303
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700304#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800305 llvm::FunctionPassManager *CodeGenPasses = NULL;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700306#endif
307
308#if MC_ASSEMBLER
309 bool RelaxAll = true;
310 llvm::PassManager MCCodeGenPasses;
311
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700312 std::string objPath(mCachePath);
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700313
314 if (!getObjPath(objPath)) {
315 LOGE("Fail to create objPath");
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700316 return 1;
317 }
318
319 int Fd = -1;
Shih-wei Liao6c0c7b02011-05-21 21:47:14 -0700320 FileHandle file;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700321
Shih-wei Liao6c0c7b02011-05-21 21:47:14 -0700322 Fd = file.open(objPath.c_str(), OpenMode::Write);
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700323 if (Fd < 0) {
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700324 LOGE("Fail to open file '%s'", objPath.c_str());
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700325 return 1;
326 }
327
328 llvm::raw_fd_ostream OutFdOS(Fd, /* shouldClose= */ false);
329 OutFdOS.seek(0);
330 llvm::formatted_raw_ostream OutFOS(OutFdOS);
331#endif
Logan1f028c02010-11-27 01:02:48 +0800332
333 const llvm::NamedMDNode *PragmaMetadata;
334 const llvm::NamedMDNode *ExportVarMetadata;
335 const llvm::NamedMDNode *ExportFuncMetadata;
Stephen Hines071288a2011-01-27 14:38:26 -0800336 const llvm::NamedMDNode *ObjectSlotMetadata;
Logan1f028c02010-11-27 01:02:48 +0800337
338 if (mModule == NULL) // No module was loaded
339 return 0;
340
341 // Create TargetMachine
342 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
343 if (hasError())
344 goto on_bcc_compile_error;
345
346 if (!CPU.empty() || !Features.empty()) {
347 llvm::SubtargetFeatures F;
348 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800349
350 for (std::vector<std::string>::const_iterator
351 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800352 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800353 }
354
Logan1f028c02010-11-27 01:02:48 +0800355 FeaturesStr = F.getString();
356 }
357
358 TM = Target->createTargetMachine(Triple, FeaturesStr);
359 if (TM == NULL) {
360 setError("Failed to create target machine implementation for the"
361 " specified triple '" + Triple + "'");
362 goto on_bcc_compile_error;
363 }
364
365 // Create memory manager for creation of code emitter later.
366 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
367 setError("Failed to startup memory management for further compilation");
368 goto on_bcc_compile_error;
369 }
Logan02286cb2011-01-07 00:30:47 +0800370
371 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800372
373 // Create code emitter
374 if (!mCodeEmitter.get()) {
375 if (!createCodeEmitter()) {
376 setError("Failed to create machine code emitter to complete"
377 " the compilation");
378 goto on_bcc_compile_error;
379 }
380 } else {
381 // Reuse the code emitter
382 mCodeEmitter->reset();
383 }
384
385 mCodeEmitter->setTargetMachine(*TM);
386 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
387 mpSymbolLookupContext);
388
389 // Get target data from Module
390 TD = new llvm::TargetData(mModule);
391
392 // Load named metadata
393 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
394 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
395 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
Stephen Hines071288a2011-01-27 14:38:26 -0800396 ObjectSlotMetadata = mModule->getNamedMetadata(ObjectSlotMetadataName);
Logan1f028c02010-11-27 01:02:48 +0800397
Shih-wei Liao644fcf22011-01-16 21:56:26 -0800398#if 0
399 mHasLinked = false;
400#endif
401
Logan1f028c02010-11-27 01:02:48 +0800402 // Create LTO passes and run them on the mModule
403 if (mHasLinked) {
404 llvm::TimePassesIsEnabled = true; // TODO(all)
405 llvm::PassManager LTOPasses;
406 LTOPasses.add(new llvm::TargetData(*TD));
407
408 std::vector<const char*> ExportSymbols;
409
410 // A workaround for getting export variable and function name. Will refine
411 // it soon.
412 if (ExportVarMetadata) {
413 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
414 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
415 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
416 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
417 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
418 llvm::StringRef ExportVarName =
419 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
420 ExportSymbols.push_back(ExportVarName.data());
421 }
422 }
423 }
424 }
425
426 if (ExportFuncMetadata) {
427 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
428 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
429 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
430 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
431 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
432 llvm::StringRef ExportFuncName =
433 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
434 ExportSymbols.push_back(ExportFuncName.data());
435 }
436 }
437 }
438 }
439 // root() and init() are born to be exported
440 ExportSymbols.push_back("root");
441 ExportSymbols.push_back("init");
442
443 // We now create passes list performing LTO. These are copied from
444 // (including comments) llvm::createStandardLTOPasses().
445
446 // Internalize all other symbols not listed in ExportSymbols
447 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
448
449 // Propagate constants at call sites into the functions they call. This
450 // opens opportunities for globalopt (and inlining) by substituting
451 // function pointers passed as arguments to direct uses of functions.
452 LTOPasses.add(llvm::createIPSCCPPass());
453
454 // Now that we internalized some globals, see if we can hack on them!
455 LTOPasses.add(llvm::createGlobalOptimizerPass());
456
457 // Linking modules together can lead to duplicated global constants, only
458 // keep one copy of each constant...
459 LTOPasses.add(llvm::createConstantMergePass());
460
461 // Remove unused arguments from functions...
462 LTOPasses.add(llvm::createDeadArgEliminationPass());
463
464 // Reduce the code after globalopt and ipsccp. Both can open up
465 // significant simplification opportunities, and both can propagate
466 // functions through function pointers. When this happens, we often have
467 // to resolve varargs calls, etc, so let instcombine do this.
468 LTOPasses.add(llvm::createInstructionCombiningPass());
469
470 // Inline small functions
471 LTOPasses.add(llvm::createFunctionInliningPass());
472
473 // Remove dead EH info.
474 LTOPasses.add(llvm::createPruneEHPass());
475
476 // Internalize the globals again after inlining
477 LTOPasses.add(llvm::createGlobalOptimizerPass());
478
479 // Remove dead functions.
480 LTOPasses.add(llvm::createGlobalDCEPass());
481
482 // If we didn't decide to inline a function, check to see if we can
483 // transform it to pass arguments by value instead of by reference.
484 LTOPasses.add(llvm::createArgumentPromotionPass());
485
486 // The IPO passes may leave cruft around. Clean up after them.
487 LTOPasses.add(llvm::createInstructionCombiningPass());
488 LTOPasses.add(llvm::createJumpThreadingPass());
489
490 // Break up allocas
491 LTOPasses.add(llvm::createScalarReplAggregatesPass());
492
493 // Run a few AA driven optimizations here and now, to cleanup the code.
494 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
495 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
496
497 // Hoist loop invariants.
498 LTOPasses.add(llvm::createLICMPass());
499
500 // Remove redundancies.
501 LTOPasses.add(llvm::createGVNPass());
502
503 // Remove dead memcpys.
504 LTOPasses.add(llvm::createMemCpyOptPass());
505
506 // Nuke dead stores.
507 LTOPasses.add(llvm::createDeadStoreEliminationPass());
508
509 // Cleanup and simplify the code after the scalar optimizations.
510 LTOPasses.add(llvm::createInstructionCombiningPass());
511
512 LTOPasses.add(llvm::createJumpThreadingPass());
513
514 // Delete basic blocks, which optimization passes may have killed.
515 LTOPasses.add(llvm::createCFGSimplificationPass());
516
517 // Now that we have optimized the program, discard unreachable functions.
518 LTOPasses.add(llvm::createGlobalDCEPass());
519
520 LTOPasses.run(*mModule);
521 }
522
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700523#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800524 // Create code-gen pass to run the code emitter
525 CodeGenPasses = new llvm::FunctionPassManager(mModule);
526 CodeGenPasses->add(TD); // Will take the ownership of TD
527
528 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
529 *mCodeEmitter,
530 CodeGenOptLevel)) {
531 setError("The machine code emission is not supported by BCC on target '"
532 + Triple + "'");
533 goto on_bcc_compile_error;
534 }
535
536 // Run the pass (the code emitter) on every non-declaration function in the
537 // module
538 CodeGenPasses->doInitialization();
539 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
540 I != E; I++) {
541 if (!I->isDeclaration()) {
542 CodeGenPasses->run(*I);
543 }
544 }
545
546 CodeGenPasses->doFinalization();
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700547#endif
Logan1f028c02010-11-27 01:02:48 +0800548
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700549#if MC_ASSEMBLER
550 TM->setMCRelaxAll(RelaxAll);
551
552 MCCodeGenPasses.add(new llvm::TargetData(*TD));
553
554 if (TM->addPassesToEmitFile(MCCodeGenPasses, OutFOS,
555 llvm::TargetMachine::CGFT_ObjectFile,
556 CodeGenOptLevel)) {
557 setError("Fail to add passes to emit file");
558 goto on_bcc_compile_error;
559 }
560
561 MCCodeGenPasses.run(*mModule);
562#endif
Logan1f028c02010-11-27 01:02:48 +0800563 // Copy the global address mapping from code emitter and remapping
564 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800565 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
566
Logan1f028c02010-11-27 01:02:48 +0800567 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
568 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
569 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
570 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
571 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
572 llvm::StringRef ExportVarName =
573 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
574
575 CodeEmitter::global_addresses_const_iterator I, E;
576 for (I = mCodeEmitter->global_address_begin(),
577 E = mCodeEmitter->global_address_end();
578 I != E; I++) {
579 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
580 continue;
581 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800582 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800583 break;
584 }
585 }
586 if (I != mCodeEmitter->global_address_end())
587 continue; // found
588 }
589 }
590 // if reaching here, we know the global variable record in metadata is
591 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800592 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800593 }
Logan2a6dc822011-01-06 04:05:20 +0800594
Stephen Hinesbbcef8a2011-05-04 19:40:10 -0700595 bccAssert((varList.size() == ExportVarMetadata->getNumOperands()) &&
596 "Number of slots doesn't match the number of export variables!");
Logan1f028c02010-11-27 01:02:48 +0800597 }
598
599 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800600 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
601
Logan1f028c02010-11-27 01:02:48 +0800602 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
603 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
604 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
605 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
606 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
607 llvm::StringRef ExportFuncName =
608 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800609 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800610 }
611 }
612 }
613 }
614
615 // Tell code emitter now can release the memory using during the JIT since
616 // we have done the code emission
617 mCodeEmitter->releaseUnnecessary();
618
619 // Finally, read pragma information from the metadata node of the @Module if
620 // any.
Logan2a6dc822011-01-06 04:05:20 +0800621 if (PragmaMetadata) {
622 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
623
Logan1f028c02010-11-27 01:02:48 +0800624 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
625 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
626 if (Pragma != NULL &&
627 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
628 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
629 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
630
631 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
632 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
633 llvm::StringRef PragmaName =
634 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
635 llvm::StringRef PragmaValue =
636 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
637
Logan2a6dc822011-01-06 04:05:20 +0800638 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800639 std::make_pair(std::string(PragmaName.data(),
640 PragmaName.size()),
641 std::string(PragmaValue.data(),
642 PragmaValue.size())));
643 }
644 }
645 }
Logan2a6dc822011-01-06 04:05:20 +0800646 }
Logan1f028c02010-11-27 01:02:48 +0800647
Stephen Hines071288a2011-01-27 14:38:26 -0800648 if (ObjectSlotMetadata) {
649 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
650
651 for (int i = 0, e = ObjectSlotMetadata->getNumOperands(); i != e; i++) {
652 llvm::MDNode *ObjectSlot = ObjectSlotMetadata->getOperand(i);
653 if (ObjectSlot != NULL &&
654 ObjectSlot->getNumOperands() == 1) {
655 llvm::Value *SlotMDS = ObjectSlot->getOperand(0);
656 if (SlotMDS->getValueID() == llvm::Value::MDStringVal) {
657 llvm::StringRef Slot =
658 static_cast<llvm::MDString*>(SlotMDS)->getString();
659 uint32_t USlot = 0;
660 if (Slot.getAsInteger(10, USlot)) {
661 setError("Non-integer object slot value '" + Slot.str() + "'");
662 goto on_bcc_compile_error;
663 }
664 objectSlotList.push_back(USlot);
665 }
666 }
667 }
668 }
669
Logan1f028c02010-11-27 01:02:48 +0800670on_bcc_compile_error:
671 // LOGE("on_bcc_compiler_error");
672 if (CodeGenPasses) {
673 delete CodeGenPasses;
674 } else if (TD) {
675 delete TD;
676 }
677 if (TM)
678 delete TM;
679
680 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800681 return 0;
Logan1f028c02010-11-27 01:02:48 +0800682 }
683
684 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800685 return 1;
Logan1f028c02010-11-27 01:02:48 +0800686}
687
688
Logan1f028c02010-11-27 01:02:48 +0800689Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800690 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800691 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800692
693 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800694}
695
Logan1f028c02010-11-27 01:02:48 +0800696} // namespace bcc