blob: c3ed9b524964c7f166938f9b268f19295190c451 [file] [log] [blame]
Logan1f028c02010-11-27 01:02:48 +08001/*
Stephen Hinesdb169182012-01-05 18:46:36 -08002 * Copyright 2010-2012, The Android Open Source Project
Logan1f028c02010-11-27 01:02:48 +08003 *
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"
Stephen Hines569986d2012-03-09 19:58:45 -080020#include <bcinfo/MetadataExtractor.h>
Logan35849002011-01-15 07:30:43 +080021
Logan Chien4885cf82011-07-20 10:18:05 +080022#if USE_DISASSEMBLER
23#include "Disassembler/Disassembler.h"
24#endif
25
Logan4dcd6792011-02-28 05:12:00 +080026#include "DebugHelper.h"
Shih-wei Liao6c0c7b02011-05-21 21:47:14 -070027#include "FileHandle.h"
Logan Chienda5e0c32011-06-13 03:47:21 +080028#include "Runtime.h"
Logan2a6dc822011-01-06 04:05:20 +080029#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080030#include "Sha1Helper.h"
Zonr Chang2fcbd022012-01-06 21:04:31 +080031#include "CompilerOption.h"
Loganeb3d12b2010-12-16 06:20:18 +080032
Logan Chienda5e0c32011-06-13 03:47:21 +080033#include "librsloader.h"
34
Stephen Hinesdb169182012-01-05 18:46:36 -080035#include "Transforms/BCCTransforms.h"
36
Logandf23afa2010-11-27 11:04:54 +080037#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080038
Logandf23afa2010-11-27 11:04:54 +080039#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080040
Logan1f028c02010-11-27 01:02:48 +080041#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080042#include "llvm/CodeGen/RegAllocRegistry.h"
43#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080044
Daniel Malea094881f2011-12-14 17:39:16 -050045#include "llvm/MC/MCContext.h"
Logan Chien9347e0b2011-07-07 19:51:47 +080046#include "llvm/MC/SubtargetFeature.h"
47
Logandf23afa2010-11-27 11:04:54 +080048#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/Scalar.h"
50
Logandf23afa2010-11-27 11:04:54 +080051#include "llvm/Target/TargetData.h"
52#include "llvm/Target/TargetMachine.h"
Logandf23afa2010-11-27 11:04:54 +080053
54#include "llvm/Support/ErrorHandling.h"
Shih-wei Liao898c5a92011-05-18 07:02:39 -070055#include "llvm/Support/FormattedStream.h"
Logan Chienbc9eb8f2011-10-21 15:17:45 +080056#include "llvm/Support/TargetRegistry.h"
57#include "llvm/Support/TargetSelect.h"
Daniel Malea094881f2011-12-14 17:39:16 -050058#include "llvm/Support/raw_ostream.h"
Logandf23afa2010-11-27 11:04:54 +080059
Daniel Malea094881f2011-12-14 17:39:16 -050060#include "llvm/Constants.h"
Logandf23afa2010-11-27 11:04:54 +080061#include "llvm/GlobalValue.h"
62#include "llvm/Linker.h"
63#include "llvm/LLVMContext.h"
Logandf23afa2010-11-27 11:04:54 +080064#include "llvm/Module.h"
65#include "llvm/PassManager.h"
Daniel Malea094881f2011-12-14 17:39:16 -050066#include "llvm/Type.h"
Logandf23afa2010-11-27 11:04:54 +080067#include "llvm/Value.h"
68
69#include <errno.h>
70#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +080071#include <sys/stat.h>
72#include <sys/types.h>
73#include <unistd.h>
74
Logan75cc8a52011-01-07 06:06:52 +080075#include <string.h>
Logan8b77a772010-12-21 09:11:01 +080076
Logan Chien7890d432011-08-03 14:55:17 +080077#include <algorithm>
78#include <iterator>
Logandf23afa2010-11-27 11:04:54 +080079#include <string>
80#include <vector>
Logan1f028c02010-11-27 01:02:48 +080081
Daniel Malea094881f2011-12-14 17:39:16 -050082extern char* gDebugDumpDirectory;
83
Logan1f028c02010-11-27 01:02:48 +080084namespace bcc {
85
86//////////////////////////////////////////////////////////////////////////////
87// BCC Compiler Static Variables
88//////////////////////////////////////////////////////////////////////////////
89
90bool Compiler::GlobalInitialized = false;
91
Andrew Hsieh998ec832011-11-21 02:36:11 -080092
93#if !defined(__HOST__)
94 #define TARGET_TRIPLE_STRING DEFAULT_TARGET_TRIPLE_STRING
95#else
96// In host TARGET_TRIPLE_STRING is a variable to allow cross-compilation.
97 #if defined(__cplusplus)
98 extern "C" {
99 #endif
100 char *TARGET_TRIPLE_STRING = (char*)DEFAULT_TARGET_TRIPLE_STRING;
101 #if defined(__cplusplus)
102 };
103 #endif
104#endif
105
Logan1f028c02010-11-27 01:02:48 +0800106// Code generation optimization level for the compiler
107llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
108
109std::string Compiler::Triple;
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800110llvm::Triple::ArchType Compiler::ArchType;
Logan1f028c02010-11-27 01:02:48 +0800111
112std::string Compiler::CPU;
113
114std::vector<std::string> Compiler::Features;
115
Daniel Malea094881f2011-12-14 17:39:16 -0500116
Logan1f028c02010-11-27 01:02:48 +0800117//////////////////////////////////////////////////////////////////////////////
118// Compiler
119//////////////////////////////////////////////////////////////////////////////
120
121void Compiler::GlobalInitialization() {
Shih-wei Liao40bcd662011-10-22 17:51:01 -0700122 if (GlobalInitialized) {
Logan1f028c02010-11-27 01:02:48 +0800123 return;
Shih-wei Liao40bcd662011-10-22 17:51:01 -0700124 }
125
Shih-wei Liao22705912012-03-06 19:13:26 -0800126#if defined(PROVIDE_ARM_CODEGEN)
127 LLVMInitializeARMAsmPrinter();
128 LLVMInitializeARMTargetMC();
129 LLVMInitializeARMTargetInfo();
130 LLVMInitializeARMTarget();
131#endif
132
133#if defined(PROVIDE_MIPS_CODEGEN)
134 LLVMInitializeMipsAsmPrinter();
135 LLVMInitializeMipsTargetMC();
136 LLVMInitializeMipsTargetInfo();
137 LLVMInitializeMipsTarget();
138#endif
139
140#if defined(PROVIDE_X86_CODEGEN)
141 LLVMInitializeX86AsmPrinter();
142 LLVMInitializeX86TargetMC();
143 LLVMInitializeX86TargetInfo();
144 LLVMInitializeX86Target();
145#endif
146
147#if USE_DISASSEMBLER
148 InitializeDisassembler();
149#endif
150
Logan1f028c02010-11-27 01:02:48 +0800151 // if (!llvm::llvm_is_multithreaded())
152 // llvm::llvm_start_multithreaded();
153
154 // Set Triple, CPU and Features here
155 Triple = TARGET_TRIPLE_STRING;
156
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800157 // Determine ArchType
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800158#if defined(__HOST__)
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800159 {
160 std::string Err;
161 llvm::Target const *Target = llvm::TargetRegistry::lookupTarget(Triple, Err);
Stephen Hinescc366e52012-02-21 17:22:04 -0800162 if (Target != NULL) {
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800163 ArchType = llvm::Triple::getArchTypeForLLVMName(Target->getName());
164 } else {
165 ArchType = llvm::Triple::UnknownArch;
166 ALOGE("%s", Err.c_str());
167 }
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800168 }
169#elif defined(DEFAULT_ARM_CODEGEN)
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800170 ArchType = llvm::Triple::arm;
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800171#elif defined(DEFAULT_MIPS_CODEGEN)
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800172 ArchType = llvm::Triple::mipsel;
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800173#elif defined(DEFAULT_X86_CODEGEN)
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800174 ArchType = llvm::Triple::x86;
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800175#elif defined(DEFAULT_X86_64_CODEGEN)
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800176 ArchType = llvm::Triple::x86_64;
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800177#else
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800178 ArchType = llvm::Triple::UnknownArch;
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800179#endif
Logan Chien3bb77072011-09-17 16:53:53 +0800180
Shih-wei Liao4deffde2012-01-17 20:38:17 +0800181 if ((ArchType == llvm::Triple::arm) || (ArchType == llvm::Triple::thumb)) {
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800182# if defined(ARCH_ARM_HAVE_VFP)
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800183 Features.push_back("+vfp3");
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800184# if !defined(ARCH_ARM_HAVE_VFP_D32)
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800185 Features.push_back("+d16");
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800186# endif
187# endif
Stephen Hinesa12d2f32011-09-07 15:30:06 -0700188
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800189# if defined(ARCH_ARM_HAVE_NEON)
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800190 Features.push_back("+neon");
191 Features.push_back("+neonfp");
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800192# else
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800193 Features.push_back("-neon");
194 Features.push_back("-neonfp");
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800195# endif
Shih-wei Liao40bcd662011-10-22 17:51:01 -0700196
Stephen Hinesf6b202b2012-03-06 17:45:41 -0800197// FIXME(all): Turn NEON back on after debugging the rebase.
198# if 1 || defined(DISABLE_ARCH_ARM_HAVE_NEON)
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800199 Features.push_back("-neon");
200 Features.push_back("-neonfp");
Shih-wei Liaofbeb9b62012-01-14 02:14:31 -0800201# endif
Andrew Hsiehc0554e22012-01-13 22:34:34 -0800202 }
Joseph Wen51001b82011-06-23 18:56:45 -0700203
Logan1f028c02010-11-27 01:02:48 +0800204 // Register the scheduler
205 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
206
Logan35849002011-01-15 07:30:43 +0800207#if USE_CACHE
Ying Wang26fea102011-07-05 15:12:25 -0700208 // Read in SHA1 checksum of libbcc and libRS.
209 readSHA1(sha1LibBCC_SHA1, sizeof(sha1LibBCC_SHA1), pathLibBCC_SHA1);
Joseph Wen76919072011-07-07 23:06:15 -0700210
211 calcFileSHA1(sha1LibRS, pathLibRS);
Logan35849002011-01-15 07:30:43 +0800212#endif
Logan75cc8a52011-01-07 06:06:52 +0800213
Logan1f028c02010-11-27 01:02:48 +0800214 GlobalInitialized = true;
215}
216
217
218void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
219 std::string *Error = static_cast<std::string*>(UserData);
220 Error->assign(Message);
Steve Block10c14122012-01-08 10:15:06 +0000221 ALOGE("%s", Message.c_str());
Logan1f028c02010-11-27 01:02:48 +0800222 exit(1);
223}
224
225
Logan2a6dc822011-01-06 04:05:20 +0800226Compiler::Compiler(ScriptCompiled *result)
227 : mpResult(result),
Logan Chienda5e0c32011-06-13 03:47:21 +0800228 mRSExecutable(NULL),
Logan1f028c02010-11-27 01:02:48 +0800229 mpSymbolLookupFn(NULL),
230 mpSymbolLookupContext(NULL),
Logan1f028c02010-11-27 01:02:48 +0800231 mModule(NULL),
232 mHasLinked(false) /* Turn off linker */ {
233 llvm::remove_fatal_error_handler();
234 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
Logan1f028c02010-11-27 01:02:48 +0800235 return;
236}
237
Logan1f028c02010-11-27 01:02:48 +0800238
Logan474cbd22011-01-31 01:47:44 +0800239int Compiler::linkModule(llvm::Module *moduleWith) {
Logan Chienbc9eb8f2011-10-21 15:17:45 +0800240 if (llvm::Linker::LinkModules(mModule, moduleWith,
Shih-wei Liaod88c0d12012-01-17 20:32:58 -0800241 llvm::Linker::PreserveSource,
Logan Chienbc9eb8f2011-10-21 15:17:45 +0800242 &mError) != 0) {
Logan1f028c02010-11-27 01:02:48 +0800243 return hasError();
244 }
245
Logan1f028c02010-11-27 01:02:48 +0800246 // Everything for linking should be settled down here with no error occurs
247 mHasLinked = true;
248 return hasError();
249}
250
251
Shih-wei Liao9e81e372012-01-17 16:38:40 -0800252int Compiler::compile(const CompilerOption &option) {
Logan Chienda5e0c32011-06-13 03:47:21 +0800253 llvm::Target const *Target = NULL;
Logan1f028c02010-11-27 01:02:48 +0800254 llvm::TargetData *TD = NULL;
Logan1f028c02010-11-27 01:02:48 +0800255 llvm::TargetMachine *TM = NULL;
Logan Chienda5e0c32011-06-13 03:47:21 +0800256
Logan1f028c02010-11-27 01:02:48 +0800257 std::string FeaturesStr;
258
Daniel Malea094881f2011-12-14 17:39:16 -0500259 if (mModule == NULL) // No module was loaded
260 return 0;
261
Stephen Hines569986d2012-03-09 19:58:45 -0800262 bcinfo::MetadataExtractor ME(mModule);
263 ME.extract();
Logan1f028c02010-11-27 01:02:48 +0800264
Stephen Hines569986d2012-03-09 19:58:45 -0800265 size_t VarCount = ME.getExportVarCount();
266 size_t FuncCount = ME.getExportFuncCount();
267 size_t ForEachSigCount = ME.getExportForEachSignatureCount();
268 size_t ObjectSlotCount = ME.getObjectSlotCount();
269 size_t PragmaCount = ME.getPragmaCount();
270
271 std::vector<std::string> &VarNameList = mpResult->mExportVarsName;
272 std::vector<std::string> &FuncNameList = mpResult->mExportFuncsName;
273 std::vector<std::string> &ForEachExpandList = mpResult->mExportForEachName;
Stephen Hinescc366e52012-02-21 17:22:04 -0800274 std::vector<std::string> ForEachNameList;
Stephen Hines569986d2012-03-09 19:58:45 -0800275 std::vector<uint32_t> ForEachSigList;
276 std::vector<const char*> ExportSymbols;
Stephen Hinescc366e52012-02-21 17:22:04 -0800277
Stephen Hines569986d2012-03-09 19:58:45 -0800278 // Defaults to maximum optimization level from MetadataExtractor.
279 int OptimizationLevel = ME.getOptimizationLevel();
Daniel Malea094881f2011-12-14 17:39:16 -0500280
281 if (OptimizationLevel == 0) {
282 CodeGenOptLevel = llvm::CodeGenOpt::None;
283 } else if (OptimizationLevel == 1) {
284 CodeGenOptLevel = llvm::CodeGenOpt::Less;
285 } else if (OptimizationLevel == 2) {
286 CodeGenOptLevel = llvm::CodeGenOpt::Default;
287 } else if (OptimizationLevel == 3) {
288 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
289 }
290
291 // not the best place for this, but we need to set the register allocation
292 // policy after we read the optimization_level metadata from the bitcode
293
294 // Register allocation policy:
295 // createFastRegisterAllocator: fast but bad quality
296 // createLinearScanRegisterAllocator: not so fast but good quality
297 llvm::RegisterRegAlloc::setDefault
298 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
299 llvm::createFastRegisterAllocator :
Stephen Hinese0918ac2012-03-01 23:28:09 -0800300 llvm::createGreedyRegisterAllocator);
Logan1f028c02010-11-27 01:02:48 +0800301
Logan Chienbe81e102011-12-16 13:31:39 +0800302 // Find LLVM Target
Logan1f028c02010-11-27 01:02:48 +0800303 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
304 if (hasError())
305 goto on_bcc_compile_error;
306
307 if (!CPU.empty() || !Features.empty()) {
308 llvm::SubtargetFeatures F;
Logana4994f52010-11-27 14:06:02 +0800309
310 for (std::vector<std::string>::const_iterator
311 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800312 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800313 }
314
Logan1f028c02010-11-27 01:02:48 +0800315 FeaturesStr = F.getString();
316 }
317
Logan Chienbe81e102011-12-16 13:31:39 +0800318 // Create LLVM Target Machine
Zonr Chang2fcbd022012-01-06 21:04:31 +0800319 TM = Target->createTargetMachine(Triple, CPU, FeaturesStr,
320 option.TargetOpt,
321 option.RelocModelOpt,
322 option.CodeModelOpt);
Logan Chienbe81e102011-12-16 13:31:39 +0800323
Logan1f028c02010-11-27 01:02:48 +0800324 if (TM == NULL) {
325 setError("Failed to create target machine implementation for the"
326 " specified triple '" + Triple + "'");
327 goto on_bcc_compile_error;
328 }
329
Logan Chienda5e0c32011-06-13 03:47:21 +0800330 // Get target data from Module
331 TD = new llvm::TargetData(mModule);
332
Stephen Hines569986d2012-03-09 19:58:45 -0800333 // Read pragma information from MetadataExtractor
334 if (PragmaCount) {
335 ScriptCompiled::PragmaList &PragmaPairs = mpResult->mPragmas;
336 const char **PragmaKeys = ME.getPragmaKeyList();
337 const char **PragmaValues = ME.getPragmaValueList();
338 for (size_t i = 0; i < PragmaCount; i++) {
339 PragmaPairs.push_back(std::make_pair(PragmaKeys[i], PragmaValues[i]));
Stephen Hinescc366e52012-02-21 17:22:04 -0800340 }
341 }
342
Stephen Hines569986d2012-03-09 19:58:45 -0800343 if (VarCount) {
344 const char **VarNames = ME.getExportVarNameList();
345 for (size_t i = 0; i < VarCount; i++) {
346 VarNameList.push_back(VarNames[i]);
347 ExportSymbols.push_back(VarNames[i]);
Stephen Hinescc366e52012-02-21 17:22:04 -0800348 }
349 }
350
Stephen Hines569986d2012-03-09 19:58:45 -0800351 if (FuncCount) {
352 const char **FuncNames = ME.getExportFuncNameList();
353 for (size_t i = 0; i < FuncCount; i++) {
354 FuncNameList.push_back(FuncNames[i]);
355 ExportSymbols.push_back(FuncNames[i]);
356 }
357 }
358
359 if (ForEachSigCount) {
360 const char **ForEachNames = ME.getExportForEachNameList();
361 const uint32_t *ForEachSigs = ME.getExportForEachSignatureList();
362 for (size_t i = 0; i < ForEachSigCount; i++) {
363 std::string Name(ForEachNames[i]);
364 ForEachNameList.push_back(Name);
365 ForEachExpandList.push_back(Name + ".expand");
366 ForEachSigList.push_back(ForEachSigs[i]);
367 }
368
369 // Need to wait until ForEachExpandList is fully populated to fill in
370 // exported symbols.
371 for (size_t i = 0; i < ForEachSigCount; i++) {
372 ExportSymbols.push_back(ForEachExpandList[i].c_str());
373 }
374 }
375
376 if (ObjectSlotCount) {
377 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
378 const uint32_t *ObjectSlots = ME.getObjectSlotList();
379 for (size_t i = 0; i < ObjectSlotCount; i++) {
380 objectSlotList.push_back(ObjectSlots[i]);
381 }
382 }
383
384 runInternalPasses(ForEachNameList, ForEachSigList);
Stephen Hinesdb169182012-01-05 18:46:36 -0800385
Logan Chienda5e0c32011-06-13 03:47:21 +0800386 // Perform link-time optimization if we have multiple modules
387 if (mHasLinked) {
Stephen Hines569986d2012-03-09 19:58:45 -0800388 runLTO(new llvm::TargetData(*TD), ExportSymbols, CodeGenOptLevel);
Logan Chienda5e0c32011-06-13 03:47:21 +0800389 }
390
391 // Perform code generation
Joseph Wen34c600a2011-07-25 17:59:17 -0700392 if (runMCCodeGen(new llvm::TargetData(*TD), TM) != 0) {
Logan Chienda5e0c32011-06-13 03:47:21 +0800393 goto on_bcc_compile_error;
394 }
Logan Chien9347e0b2011-07-07 19:51:47 +0800395
Zonr Chang2fcbd022012-01-06 21:04:31 +0800396 if (!option.LoadAfterCompile)
Joseph Wen34c600a2011-07-25 17:59:17 -0700397 return 0;
398
399 // Load the ELF Object
400 mRSExecutable =
Stephen Hines569986d2012-03-09 19:58:45 -0800401 rsloaderCreateExec((unsigned char *)&*mEmittedELFExecutable.begin(),
402 mEmittedELFExecutable.size(),
403 &resolveSymbolAdapter, this);
Joseph Wen34c600a2011-07-25 17:59:17 -0700404
405 if (!mRSExecutable) {
406 setError("Fail to load emitted ELF relocatable file");
407 goto on_bcc_compile_error;
408 }
409
Daniel Malea094881f2011-12-14 17:39:16 -0500410 rsloaderUpdateSectionHeaders(mRSExecutable,
Stephen Hines569986d2012-03-09 19:58:45 -0800411 (unsigned char*) mEmittedELFExecutable.begin());
Daniel Malea094881f2011-12-14 17:39:16 -0500412
Stephen Hines569986d2012-03-09 19:58:45 -0800413 // Once the ELF object has been loaded, populate the various slots for RS
414 // with the appropriate relocated addresses.
415 if (VarCount) {
416 ScriptCompiled::ExportVarList &VarList = mpResult->mExportVars;
417 for (size_t i = 0; i < VarCount; i++) {
418 VarList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
419 VarNameList[i].c_str()));
Joseph Wen34c600a2011-07-25 17:59:17 -0700420 }
421 }
422
Stephen Hines569986d2012-03-09 19:58:45 -0800423 if (FuncCount) {
424 ScriptCompiled::ExportFuncList &FuncList = mpResult->mExportFuncs;
425 for (size_t i = 0; i < FuncCount; i++) {
426 FuncList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
427 FuncNameList[i].c_str()));
Joseph Wen34c600a2011-07-25 17:59:17 -0700428 }
429 }
430
Stephen Hines569986d2012-03-09 19:58:45 -0800431 if (ForEachSigCount) {
432 ScriptCompiled::ExportForEachList &ForEachList = mpResult->mExportForEach;
433 for (size_t i = 0; i < ForEachSigCount; i++) {
434 ForEachList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
435 ForEachExpandList[i].c_str()));
Stephen Hinescc366e52012-02-21 17:22:04 -0800436 }
437 }
438
Stephen Hines36999622012-03-11 19:15:51 -0700439#if DEBUG_MC_DISASSEMBLER
Shih-wei Liao90cd3d12011-06-20 15:43:34 -0700440 {
Shih-wei Liaod3c551f2011-07-01 04:28:27 -0700441 // Get MC codegen emitted function name list
442 size_t func_list_size = rsloaderGetFuncCount(mRSExecutable);
443 std::vector<char const *> func_list(func_list_size, NULL);
444 rsloaderGetFuncNameList(mRSExecutable, func_list_size, &*func_list.begin());
Shih-wei Liao320b5492011-06-20 22:53:33 -0700445
Shih-wei Liaod3c551f2011-07-01 04:28:27 -0700446 // Disassemble each function
Shih-wei Liao90cd3d12011-06-20 15:43:34 -0700447 for (size_t i = 0; i < func_list_size; ++i) {
448 void *func = rsloaderGetSymbolAddress(mRSExecutable, func_list[i]);
449 if (func) {
450 size_t size = rsloaderGetSymbolSize(mRSExecutable, func_list[i]);
Stephen Hines36999622012-03-11 19:15:51 -0700451 Disassemble(DEBUG_MC_DISASSEMBLER_FILE,
Logan Chien9347e0b2011-07-07 19:51:47 +0800452 Target, TM, func_list[i], (unsigned char const *)func, size);
Shih-wei Liao90cd3d12011-06-20 15:43:34 -0700453 }
454 }
455 }
456#endif
Logan Chienda5e0c32011-06-13 03:47:21 +0800457
Logan Chienda5e0c32011-06-13 03:47:21 +0800458on_bcc_compile_error:
Steve Block10c14122012-01-08 10:15:06 +0000459 // ALOGE("on_bcc_compiler_error");
Logan Chienda5e0c32011-06-13 03:47:21 +0800460 if (TD) {
461 delete TD;
462 }
463
464 if (TM) {
465 delete TM;
466 }
467
468 if (mError.empty()) {
469 return 0;
470 }
471
Steve Block10c14122012-01-08 10:15:06 +0000472 // ALOGE(getErrorMessage());
Logan Chienda5e0c32011-06-13 03:47:21 +0800473 return 1;
474}
475
476
Joseph Wen34c600a2011-07-25 17:59:17 -0700477int Compiler::runMCCodeGen(llvm::TargetData *TD, llvm::TargetMachine *TM) {
Logan Chienda5e0c32011-06-13 03:47:21 +0800478 // Decorate mEmittedELFExecutable with formatted ostream
479 llvm::raw_svector_ostream OutSVOS(mEmittedELFExecutable);
480
481 // Relax all machine instructions
482 TM->setMCRelaxAll(/* RelaxAll= */ true);
483
484 // Create MC code generation pass manager
485 llvm::PassManager MCCodeGenPasses;
486
487 // Add TargetData to MC code generation pass manager
488 MCCodeGenPasses.add(TD);
489
490 // Add MC code generation passes to pass manager
Daniel Malea094881f2011-12-14 17:39:16 -0500491 llvm::MCContext *Ctx = NULL;
Logan Chien4e4485d2011-11-25 18:12:33 +0800492 if (TM->addPassesToEmitMC(MCCodeGenPasses, Ctx, OutSVOS, false)) {
Logan Chienda5e0c32011-06-13 03:47:21 +0800493 setError("Fail to add passes to emit file");
494 return 1;
495 }
496
497 MCCodeGenPasses.run(*mModule);
498 OutSVOS.flush();
Logan Chienda5e0c32011-06-13 03:47:21 +0800499 return 0;
500}
Logan Chienda5e0c32011-06-13 03:47:21 +0800501
Stephen Hinescc366e52012-02-21 17:22:04 -0800502int Compiler::runInternalPasses(std::vector<std::string>& Names,
503 std::vector<uint32_t>& Signatures) {
Stephen Hinesdb169182012-01-05 18:46:36 -0800504 llvm::PassManager BCCPasses;
505
506 // Expand ForEach on CPU path to reduce launch overhead.
Stephen Hinescc366e52012-02-21 17:22:04 -0800507 BCCPasses.add(createForEachExpandPass(Names, Signatures));
Stephen Hinesdb169182012-01-05 18:46:36 -0800508
509 BCCPasses.run(*mModule);
510
511 return 0;
512}
Logan Chienda5e0c32011-06-13 03:47:21 +0800513
514int Compiler::runLTO(llvm::TargetData *TD,
Stephen Hines569986d2012-03-09 19:58:45 -0800515 std::vector<const char*>& ExportSymbols,
Daniel Malea094881f2011-12-14 17:39:16 -0500516 llvm::CodeGenOpt::Level OptimizationLevel) {
Stephen Hines569986d2012-03-09 19:58:45 -0800517 // Note: ExportSymbols is a workaround for getting all exported variable,
518 // function, and kernel names.
Logan Chien4cc00332011-06-12 14:00:46 +0800519 // We should refine it soon.
Stephen Hinescc366e52012-02-21 17:22:04 -0800520
Logan Chien7890d432011-08-03 14:55:17 +0800521 // TODO(logan): Remove this after we have finished the
522 // bccMarkExternalSymbol API.
523
Stephen Hines64160102011-09-01 17:30:26 -0700524 // root(), init(), and .rs.dtor() are born to be exported
Logan Chien4cc00332011-06-12 14:00:46 +0800525 ExportSymbols.push_back("root");
526 ExportSymbols.push_back("init");
Stephen Hines64160102011-09-01 17:30:26 -0700527 ExportSymbols.push_back(".rs.dtor");
Logan Chien4cc00332011-06-12 14:00:46 +0800528
Logan Chien7890d432011-08-03 14:55:17 +0800529 // User-defined exporting symbols
530 std::vector<char const *> const &UserDefinedExternalSymbols =
531 mpResult->getUserDefinedExternalSymbols();
532
533 std::copy(UserDefinedExternalSymbols.begin(),
534 UserDefinedExternalSymbols.end(),
535 std::back_inserter(ExportSymbols));
536
Daniel Malea094881f2011-12-14 17:39:16 -0500537 llvm::PassManager LTOPasses;
538
539 // Add TargetData to LTO passes
540 LTOPasses.add(TD);
541
Logan Chien4cc00332011-06-12 14:00:46 +0800542 // We now create passes list performing LTO. These are copied from
543 // (including comments) llvm::createStandardLTOPasses().
Daniel Malea094881f2011-12-14 17:39:16 -0500544 // Only a subset of these LTO passes are enabled in optimization level 0
545 // as they interfere with interactive debugging.
546 // FIXME: figure out which passes (if any) makes sense for levels 1 and 2
Logan Chien4cc00332011-06-12 14:00:46 +0800547
Daniel Malea094881f2011-12-14 17:39:16 -0500548 if (OptimizationLevel != llvm::CodeGenOpt::None) {
549 // Internalize all other symbols not listed in ExportSymbols
550 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
Logan Chien4cc00332011-06-12 14:00:46 +0800551
Daniel Malea094881f2011-12-14 17:39:16 -0500552 // Propagate constants at call sites into the functions they call. This
553 // opens opportunities for globalopt (and inlining) by substituting
554 // function pointers passed as arguments to direct uses of functions.
555 LTOPasses.add(llvm::createIPSCCPPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800556
Daniel Malea094881f2011-12-14 17:39:16 -0500557 // Now that we internalized some globals, see if we can hack on them!
558 LTOPasses.add(llvm::createGlobalOptimizerPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800559
Daniel Malea094881f2011-12-14 17:39:16 -0500560 // Linking modules together can lead to duplicated global constants, only
561 // keep one copy of each constant...
562 LTOPasses.add(llvm::createConstantMergePass());
Logan Chien4cc00332011-06-12 14:00:46 +0800563
Daniel Malea094881f2011-12-14 17:39:16 -0500564 // Remove unused arguments from functions...
565 LTOPasses.add(llvm::createDeadArgEliminationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800566
Daniel Malea094881f2011-12-14 17:39:16 -0500567 // Reduce the code after globalopt and ipsccp. Both can open up
568 // significant simplification opportunities, and both can propagate
569 // functions through function pointers. When this happens, we often have
570 // to resolve varargs calls, etc, so let instcombine do this.
571 LTOPasses.add(llvm::createInstructionCombiningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800572
Daniel Malea094881f2011-12-14 17:39:16 -0500573 // Inline small functions
574 LTOPasses.add(llvm::createFunctionInliningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800575
Daniel Malea094881f2011-12-14 17:39:16 -0500576 // Remove dead EH info.
577 LTOPasses.add(llvm::createPruneEHPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800578
Daniel Malea094881f2011-12-14 17:39:16 -0500579 // Internalize the globals again after inlining
580 LTOPasses.add(llvm::createGlobalOptimizerPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800581
Daniel Malea094881f2011-12-14 17:39:16 -0500582 // Remove dead functions.
583 LTOPasses.add(llvm::createGlobalDCEPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800584
Daniel Malea094881f2011-12-14 17:39:16 -0500585 // If we didn't decide to inline a function, check to see if we can
586 // transform it to pass arguments by value instead of by reference.
587 LTOPasses.add(llvm::createArgumentPromotionPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800588
Daniel Malea094881f2011-12-14 17:39:16 -0500589 // The IPO passes may leave cruft around. Clean up after them.
590 LTOPasses.add(llvm::createInstructionCombiningPass());
591 LTOPasses.add(llvm::createJumpThreadingPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800592
Daniel Malea094881f2011-12-14 17:39:16 -0500593 // Break up allocas
594 LTOPasses.add(llvm::createScalarReplAggregatesPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800595
Daniel Malea094881f2011-12-14 17:39:16 -0500596 // Run a few AA driven optimizations here and now, to cleanup the code.
597 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
598 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
Logan Chien4cc00332011-06-12 14:00:46 +0800599
Daniel Malea094881f2011-12-14 17:39:16 -0500600 // Hoist loop invariants.
601 LTOPasses.add(llvm::createLICMPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800602
Daniel Malea094881f2011-12-14 17:39:16 -0500603 // Remove redundancies.
604 LTOPasses.add(llvm::createGVNPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800605
Daniel Malea094881f2011-12-14 17:39:16 -0500606 // Remove dead memcpys.
607 LTOPasses.add(llvm::createMemCpyOptPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800608
Daniel Malea094881f2011-12-14 17:39:16 -0500609 // Nuke dead stores.
610 LTOPasses.add(llvm::createDeadStoreEliminationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800611
Daniel Malea094881f2011-12-14 17:39:16 -0500612 // Cleanup and simplify the code after the scalar optimizations.
613 LTOPasses.add(llvm::createInstructionCombiningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800614
Daniel Malea094881f2011-12-14 17:39:16 -0500615 LTOPasses.add(llvm::createJumpThreadingPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800616
Daniel Malea094881f2011-12-14 17:39:16 -0500617 // Delete basic blocks, which optimization passes may have killed.
618 LTOPasses.add(llvm::createCFGSimplificationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800619
Daniel Malea094881f2011-12-14 17:39:16 -0500620 // Now that we have optimized the program, discard unreachable functions.
621 LTOPasses.add(llvm::createGlobalDCEPass());
622
623 } else {
624 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
625 LTOPasses.add(llvm::createGlobalOptimizerPass());
626 LTOPasses.add(llvm::createConstantMergePass());
627 }
Logan Chien4cc00332011-06-12 14:00:46 +0800628
629 LTOPasses.run(*mModule);
Logan Chienda5e0c32011-06-13 03:47:21 +0800630
Daniel Malea094881f2011-12-14 17:39:16 -0500631#if ANDROID_ENGINEERING_BUILD
632 if (0 != gDebugDumpDirectory) {
633 std::string errs;
634 std::string Filename(gDebugDumpDirectory);
635 Filename += "/post-lto-module.ll";
636 llvm::raw_fd_ostream FS(Filename.c_str(), errs);
637 mModule->print(FS, 0);
638 FS.close();
639 }
640#endif
641
Logan Chienda5e0c32011-06-13 03:47:21 +0800642 return 0;
Logan Chien4cc00332011-06-12 14:00:46 +0800643}
644
645
Logan Chienda5e0c32011-06-13 03:47:21 +0800646void *Compiler::getSymbolAddress(char const *name) {
647 return rsloaderGetSymbolAddress(mRSExecutable, name);
648}
Logan Chienda5e0c32011-06-13 03:47:21 +0800649
650
Logan Chienda5e0c32011-06-13 03:47:21 +0800651void *Compiler::resolveSymbolAdapter(void *context, char const *name) {
652 Compiler *self = reinterpret_cast<Compiler *>(context);
653
654 if (void *Addr = FindRuntimeFunction(name)) {
655 return Addr;
656 }
657
658 if (self->mpSymbolLookupFn) {
659 if (void *Addr = self->mpSymbolLookupFn(self->mpSymbolLookupContext, name)) {
660 return Addr;
661 }
662 }
663
Steve Block10c14122012-01-08 10:15:06 +0000664 ALOGE("Unable to resolve symbol: %s\n", name);
Logan Chienda5e0c32011-06-13 03:47:21 +0800665 return NULL;
666}
Logan Chienda5e0c32011-06-13 03:47:21 +0800667
668
Logan1f028c02010-11-27 01:02:48 +0800669Compiler::~Compiler() {
Logan Chienda5e0c32011-06-13 03:47:21 +0800670 rsloaderDisposeExec(mRSExecutable);
Logan Chienda5e0c32011-06-13 03:47:21 +0800671
Logana4994f52010-11-27 14:06:02 +0800672 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800673}
674
Shih-wei Liao90cd3d12011-06-20 15:43:34 -0700675
Logan1f028c02010-11-27 01:02:48 +0800676} // namespace bcc