blob: cf18ef63d180f230c4bd9eb2a669aab5191cbf50 [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
Stephen Hines2f6a4932012-05-03 12:27:13 -070017#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080018
Stephen Hines4a68b1c2012-05-03 12:28:14 -070019#include "Config.h"
20#include <bcinfo/MetadataExtractor.h>
Logan35849002011-01-15 07:30:43 +080021
Stephen Hines4a68b1c2012-05-03 12:28:14 -070022#if USE_DISASSEMBLER
23#include "Disassembler/Disassembler.h"
24#endif
25
Stephen Hines2f6a4932012-05-03 12:27:13 -070026#include "DebugHelper.h"
Stephen Hines758d00c2012-05-03 12:30:15 -070027#include "FileHandle.h"
Stephen Hines5fb14742012-05-03 12:29:50 -070028#include "Runtime.h"
Stephen Hines4a68b1c2012-05-03 12:28:14 -070029#include "ScriptCompiled.h"
30#include "Sha1Helper.h"
31#include "CompilerOption.h"
Loganeb3d12b2010-12-16 06:20:18 +080032
Stephen Hines4a68b1c2012-05-03 12:28:14 -070033#include "librsloader.h"
Logan Chienda5e0c32011-06-13 03:47:21 +080034
Stephen Hines09ebd172012-05-03 12:28:26 -070035#include "Transforms/BCCTransforms.h"
Stephen Hinesdb169182012-01-05 18:46:36 -080036
Stephen Hines4a68b1c2012-05-03 12:28:14 -070037#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080038
Stephen Hines4a68b1c2012-05-03 12:28:14 -070039#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080040
Stephen Hines4a68b1c2012-05-03 12:28:14 -070041#include "llvm/CodeGen/Passes.h"
42#include "llvm/CodeGen/RegAllocRegistry.h"
43#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080044
Stephen Hines4a68b1c2012-05-03 12:28:14 -070045#include "llvm/MC/MCContext.h"
46#include "llvm/MC/SubtargetFeature.h"
Shih-wei Liao40bcd662011-10-22 17:51:01 -070047
Stephen Hines4a68b1c2012-05-03 12:28:14 -070048#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/Scalar.h"
Logan1f028c02010-11-27 01:02:48 +080050
Stephen Hines4a68b1c2012-05-03 12:28:14 -070051#include "llvm/Target/TargetData.h"
52#include "llvm/Target/TargetMachine.h"
Logan1f028c02010-11-27 01:02:48 +080053
Stephen Hines4a68b1c2012-05-03 12:28:14 -070054#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/FormattedStream.h"
56#include "llvm/Support/TargetRegistry.h"
57#include "llvm/Support/TargetSelect.h"
58#include "llvm/Support/raw_ostream.h"
Zonr Changfef9a1b2012-04-13 15:58:24 +080059
Stephen Hines4a68b1c2012-05-03 12:28:14 -070060#include "llvm/Constants.h"
61#include "llvm/GlobalValue.h"
62#include "llvm/Linker.h"
63#include "llvm/LLVMContext.h"
64#include "llvm/Module.h"
65#include "llvm/PassManager.h"
66#include "llvm/Type.h"
67#include "llvm/Value.h"
68
69#include <errno.h>
70#include <sys/file.h>
71#include <sys/stat.h>
72#include <sys/types.h>
73#include <unistd.h>
74
75#include <string.h>
76
77#include <algorithm>
78#include <iterator>
79#include <string>
80#include <vector>
81
82extern char* gDebugDumpDirectory;
83
84namespace bcc {
85
86//////////////////////////////////////////////////////////////////////////////
87// BCC Compiler Static Variables
88//////////////////////////////////////////////////////////////////////////////
89
90bool Compiler::GlobalInitialized = false;
91
92
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
106// Code generation optimization level for the compiler
107llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
108
109std::string Compiler::Triple;
110llvm::Triple::ArchType Compiler::ArchType;
111
112std::string Compiler::CPU;
113
114std::vector<std::string> Compiler::Features;
115
116
117//////////////////////////////////////////////////////////////////////////////
118// Compiler
119//////////////////////////////////////////////////////////////////////////////
120
121void Compiler::GlobalInitialization() {
122 if (GlobalInitialized) {
Zonr Changfef9a1b2012-04-13 15:58:24 +0800123 return;
Logan1f028c02010-11-27 01:02:48 +0800124 }
Zonr Changfef9a1b2012-04-13 15:58:24 +0800125
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700126#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
151 // if (!llvm::llvm_is_multithreaded())
152 // llvm::llvm_start_multithreaded();
153
154 // Set Triple, CPU and Features here
155 Triple = TARGET_TRIPLE_STRING;
156
157 // Determine ArchType
158#if defined(__HOST__)
159 {
160 std::string Err;
161 llvm::Target const *Target = llvm::TargetRegistry::lookupTarget(Triple, Err);
162 if (Target != NULL) {
163 ArchType = llvm::Triple::getArchTypeForLLVMName(Target->getName());
164 } else {
165 ArchType = llvm::Triple::UnknownArch;
166 ALOGE("%s", Err.c_str());
167 }
168 }
169#elif defined(DEFAULT_ARM_CODEGEN)
170 ArchType = llvm::Triple::arm;
171#elif defined(DEFAULT_MIPS_CODEGEN)
172 ArchType = llvm::Triple::mipsel;
173#elif defined(DEFAULT_X86_CODEGEN)
174 ArchType = llvm::Triple::x86;
175#elif defined(DEFAULT_X86_64_CODEGEN)
176 ArchType = llvm::Triple::x86_64;
177#else
178 ArchType = llvm::Triple::UnknownArch;
179#endif
180
181 if ((ArchType == llvm::Triple::arm) || (ArchType == llvm::Triple::thumb)) {
182# if defined(ARCH_ARM_HAVE_VFP)
183 Features.push_back("+vfp3");
184# if !defined(ARCH_ARM_HAVE_VFP_D32)
185 Features.push_back("+d16");
186# endif
187# endif
188
Stephen Hinesfc274772012-05-10 12:20:02 -0700189# if defined(ARCH_ARM_HAVE_NEON) && !defined(DISABLE_ARCH_ARM_HAVE_NEON)
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700190 Features.push_back("+neon");
191 Features.push_back("+neonfp");
192# else
193 Features.push_back("-neon");
194 Features.push_back("-neonfp");
195# endif
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700196 }
197
198 // Register the scheduler
199 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
200
201 // Read in SHA1 checksum of libbcc and libRS.
202 readSHA1(sha1LibBCC_SHA1, sizeof(sha1LibBCC_SHA1), pathLibBCC_SHA1);
203
204 calcFileSHA1(sha1LibRS, pathLibRS);
205
206 GlobalInitialized = true;
207}
208
209
210void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
211 std::string *Error = static_cast<std::string*>(UserData);
212 Error->assign(Message);
213 ALOGE("%s", Message.c_str());
214 exit(1);
215}
216
217
218Compiler::Compiler(ScriptCompiled *result)
219 : mpResult(result),
220 mRSExecutable(NULL),
221 mpSymbolLookupFn(NULL),
222 mpSymbolLookupContext(NULL),
Stephen Hinesead5ccb2012-05-03 12:30:38 -0700223 mModule(NULL),
224 mHasLinked(false) /* Turn off linker */ {
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700225 llvm::remove_fatal_error_handler();
226 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
Zonr Changfef9a1b2012-04-13 15:58:24 +0800227 return;
Logan1f028c02010-11-27 01:02:48 +0800228}
229
Stephen Hinesead5ccb2012-05-03 12:30:38 -0700230
231int Compiler::linkModule(llvm::Module *moduleWith) {
232 if (llvm::Linker::LinkModules(mModule, moduleWith,
233 llvm::Linker::PreserveSource,
234 &mError) != 0) {
235 return hasError();
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700236 }
Stephen Hinesead5ccb2012-05-03 12:30:38 -0700237
238 // Everything for linking should be settled down here with no error occurs
239 mHasLinked = true;
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700240 return hasError();
241}
242
Stephen Hinesead5ccb2012-05-03 12:30:38 -0700243
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700244int Compiler::compile(const CompilerOption &option) {
245 llvm::Target const *Target = NULL;
246 llvm::TargetData *TD = NULL;
247 llvm::TargetMachine *TM = NULL;
248
Stephen Hinesfc274772012-05-10 12:20:02 -0700249 std::vector<std::string> ExtraFeatures;
250
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700251 std::string FeaturesStr;
252
253 if (mModule == NULL) // No module was loaded
254 return 0;
255
256 bcinfo::MetadataExtractor ME(mModule);
257 ME.extract();
258
259 size_t VarCount = ME.getExportVarCount();
260 size_t FuncCount = ME.getExportFuncCount();
261 size_t ForEachSigCount = ME.getExportForEachSignatureCount();
262 size_t ObjectSlotCount = ME.getObjectSlotCount();
263 size_t PragmaCount = ME.getPragmaCount();
264
265 std::vector<std::string> &VarNameList = mpResult->mExportVarsName;
266 std::vector<std::string> &FuncNameList = mpResult->mExportFuncsName;
267 std::vector<std::string> &ForEachExpandList = mpResult->mExportForEachName;
Stephen Hines09ebd172012-05-03 12:28:26 -0700268 std::vector<std::string> ForEachNameList;
269 std::vector<uint32_t> ForEachSigList;
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700270 std::vector<const char*> ExportSymbols;
271
272 // Defaults to maximum optimization level from MetadataExtractor.
273 uint32_t OptimizationLevel = ME.getOptimizationLevel();
274
275 if (OptimizationLevel == 0) {
276 CodeGenOptLevel = llvm::CodeGenOpt::None;
277 } else if (OptimizationLevel == 1) {
278 CodeGenOptLevel = llvm::CodeGenOpt::Less;
279 } else if (OptimizationLevel == 2) {
280 CodeGenOptLevel = llvm::CodeGenOpt::Default;
281 } else if (OptimizationLevel == 3) {
282 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Daniel Malea094881f2011-12-14 17:39:16 -0500283 }
284
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700285 // not the best place for this, but we need to set the register allocation
286 // policy after we read the optimization_level metadata from the bitcode
Daniel Malea094881f2011-12-14 17:39:16 -0500287
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700288 // Register allocation policy:
Daniel Malea094881f2011-12-14 17:39:16 -0500289 // createFastRegisterAllocator: fast but bad quality
290 // createLinearScanRegisterAllocator: not so fast but good quality
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700291 llvm::RegisterRegAlloc::setDefault
292 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
293 llvm::createFastRegisterAllocator :
294 llvm::createGreedyRegisterAllocator);
295
296 // Find LLVM Target
297 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
298 if (hasError())
299 goto on_bcc_compile_error;
300
301#if defined(ARCH_ARM_HAVE_NEON)
302 // Full-precision means we have to disable NEON
303 if (ME.getRSFloatPrecision() == bcinfo::RS_FP_Full) {
Stephen Hinesfc274772012-05-10 12:20:02 -0700304 ExtraFeatures.push_back("-neon");
305 ExtraFeatures.push_back("-neonfp");
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700306 }
307#endif
308
Stephen Hinesfc274772012-05-10 12:20:02 -0700309 if (!CPU.empty() || !Features.empty() || !ExtraFeatures.empty()) {
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700310 llvm::SubtargetFeatures F;
311
312 for (std::vector<std::string>::const_iterator
313 I = Features.begin(), E = Features.end(); I != E; I++) {
314 F.AddFeature(*I);
315 }
316
Stephen Hinesfc274772012-05-10 12:20:02 -0700317 for (std::vector<std::string>::const_iterator
318 I = ExtraFeatures.begin(), E = ExtraFeatures.end(); I != E; I++) {
319 F.AddFeature(*I);
320 }
321
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700322 FeaturesStr = F.getString();
Logan1f028c02010-11-27 01:02:48 +0800323 }
324
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700325 // Create LLVM Target Machine
326 TM = Target->createTargetMachine(Triple, CPU, FeaturesStr,
327 option.TargetOpt,
328 option.RelocModelOpt,
329 option.CodeModelOpt);
Logan Chienbe81e102011-12-16 13:31:39 +0800330
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700331 if (TM == NULL) {
332 setError("Failed to create target machine implementation for the"
333 " specified triple '" + Triple + "'");
334 goto on_bcc_compile_error;
335 }
336
337 // Get target data from Module
338 TD = new llvm::TargetData(mModule);
339
340 // Read pragma information from MetadataExtractor
341 if (PragmaCount) {
342 ScriptCompiled::PragmaList &PragmaPairs = mpResult->mPragmas;
343 const char **PragmaKeys = ME.getPragmaKeyList();
344 const char **PragmaValues = ME.getPragmaValueList();
345 for (size_t i = 0; i < PragmaCount; i++) {
346 PragmaPairs.push_back(std::make_pair(PragmaKeys[i], PragmaValues[i]));
347 }
348 }
349
350 if (VarCount) {
351 const char **VarNames = ME.getExportVarNameList();
352 for (size_t i = 0; i < VarCount; i++) {
353 VarNameList.push_back(VarNames[i]);
354 ExportSymbols.push_back(VarNames[i]);
355 }
356 }
357
358 if (FuncCount) {
359 const char **FuncNames = ME.getExportFuncNameList();
360 for (size_t i = 0; i < FuncCount; i++) {
361 FuncNameList.push_back(FuncNames[i]);
362 ExportSymbols.push_back(FuncNames[i]);
363 }
364 }
365
366 if (ForEachSigCount) {
367 const char **ForEachNames = ME.getExportForEachNameList();
368 const uint32_t *ForEachSigs = ME.getExportForEachSignatureList();
369 for (size_t i = 0; i < ForEachSigCount; i++) {
Stephen Hines09ebd172012-05-03 12:28:26 -0700370 std::string Name(ForEachNames[i]);
371 ForEachNameList.push_back(Name);
372 ForEachExpandList.push_back(Name + ".expand");
373 ForEachSigList.push_back(ForEachSigs[i]);
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700374 }
375
376 // Need to wait until ForEachExpandList is fully populated to fill in
377 // exported symbols.
378 for (size_t i = 0; i < ForEachSigCount; i++) {
379 ExportSymbols.push_back(ForEachExpandList[i].c_str());
380 }
381 }
382
383 if (ObjectSlotCount) {
384 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
385 const uint32_t *ObjectSlots = ME.getObjectSlotList();
386 for (size_t i = 0; i < ObjectSlotCount; i++) {
387 objectSlotList.push_back(ObjectSlots[i]);
388 }
389 }
390
Stephen Hines09ebd172012-05-03 12:28:26 -0700391 runInternalPasses(ForEachNameList, ForEachSigList);
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700392
393 // Perform link-time optimization if we have multiple modules
Stephen Hinesead5ccb2012-05-03 12:30:38 -0700394 if (mHasLinked) {
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700395 runLTO(new llvm::TargetData(*TD), ExportSymbols, CodeGenOptLevel);
396 }
397
398 // Perform code generation
399 if (runMCCodeGen(new llvm::TargetData(*TD), TM) != 0) {
400 goto on_bcc_compile_error;
401 }
402
403 if (!option.LoadAfterCompile)
404 return 0;
405
406 // Load the ELF Object
Stephen Hines5fb14742012-05-03 12:29:50 -0700407 mRSExecutable =
408 rsloaderCreateExec((unsigned char *)&*mEmittedELFExecutable.begin(),
409 mEmittedELFExecutable.size(),
410 &resolveSymbolAdapter, this);
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700411
412 if (!mRSExecutable) {
413 setError("Fail to load emitted ELF relocatable file");
414 goto on_bcc_compile_error;
415 }
416
417 rsloaderUpdateSectionHeaders(mRSExecutable,
418 (unsigned char*) mEmittedELFExecutable.begin());
419
420 // Once the ELF object has been loaded, populate the various slots for RS
421 // with the appropriate relocated addresses.
422 if (VarCount) {
423 ScriptCompiled::ExportVarList &VarList = mpResult->mExportVars;
424 for (size_t i = 0; i < VarCount; i++) {
425 VarList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
426 VarNameList[i].c_str()));
427 }
428 }
429
430 if (FuncCount) {
431 ScriptCompiled::ExportFuncList &FuncList = mpResult->mExportFuncs;
432 for (size_t i = 0; i < FuncCount; i++) {
433 FuncList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
434 FuncNameList[i].c_str()));
435 }
436 }
437
438 if (ForEachSigCount) {
439 ScriptCompiled::ExportForEachList &ForEachList = mpResult->mExportForEach;
440 for (size_t i = 0; i < ForEachSigCount; i++) {
441 ForEachList.push_back(rsloaderGetSymbolAddress(mRSExecutable,
442 ForEachExpandList[i].c_str()));
443 }
444 }
445
446#if DEBUG_MC_DISASSEMBLER
447 {
448 // Get MC codegen emitted function name list
449 size_t func_list_size = rsloaderGetFuncCount(mRSExecutable);
450 std::vector<char const *> func_list(func_list_size, NULL);
451 rsloaderGetFuncNameList(mRSExecutable, func_list_size, &*func_list.begin());
452
453 // Disassemble each function
454 for (size_t i = 0; i < func_list_size; ++i) {
455 void *func = rsloaderGetSymbolAddress(mRSExecutable, func_list[i]);
456 if (func) {
457 size_t size = rsloaderGetSymbolSize(mRSExecutable, func_list[i]);
458 Disassemble(DEBUG_MC_DISASSEMBLER_FILE,
459 Target, TM, func_list[i], (unsigned char const *)func, size);
460 }
461 }
462 }
463#endif
464
465on_bcc_compile_error:
466 // ALOGE("on_bcc_compiler_error");
467 if (TD) {
468 delete TD;
469 }
470
471 if (TM) {
472 delete TM;
473 }
474
475 if (mError.empty()) {
476 return 0;
477 }
478
479 // ALOGE(getErrorMessage());
480 return 1;
Logan Chienda5e0c32011-06-13 03:47:21 +0800481}
482
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700483
484int Compiler::runMCCodeGen(llvm::TargetData *TD, llvm::TargetMachine *TM) {
485 // Decorate mEmittedELFExecutable with formatted ostream
486 llvm::raw_svector_ostream OutSVOS(mEmittedELFExecutable);
487
488 // Relax all machine instructions
489 TM->setMCRelaxAll(/* RelaxAll= */ true);
490
491 // Create MC code generation pass manager
492 llvm::PassManager MCCodeGenPasses;
493
494 // Add TargetData to MC code generation pass manager
495 MCCodeGenPasses.add(TD);
496
497 // Add MC code generation passes to pass manager
498 llvm::MCContext *Ctx = NULL;
499 if (TM->addPassesToEmitMC(MCCodeGenPasses, Ctx, OutSVOS, false)) {
500 setError("Fail to add passes to emit file");
501 return 1;
502 }
503
504 MCCodeGenPasses.run(*mModule);
505 OutSVOS.flush();
506 return 0;
Zonr Changfef9a1b2012-04-13 15:58:24 +0800507}
Logan Chienda5e0c32011-06-13 03:47:21 +0800508
Stephen Hines09ebd172012-05-03 12:28:26 -0700509int Compiler::runInternalPasses(std::vector<std::string>& Names,
510 std::vector<uint32_t>& Signatures) {
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700511 llvm::PassManager BCCPasses;
Logan Chienda5e0c32011-06-13 03:47:21 +0800512
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700513 // Expand ForEach on CPU path to reduce launch overhead.
Stephen Hines09ebd172012-05-03 12:28:26 -0700514 BCCPasses.add(createForEachExpandPass(Names, Signatures));
Logan Chienda5e0c32011-06-13 03:47:21 +0800515
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700516 BCCPasses.run(*mModule);
Logan Chienda5e0c32011-06-13 03:47:21 +0800517
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700518 return 0;
519}
Logan Chienda5e0c32011-06-13 03:47:21 +0800520
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700521int Compiler::runLTO(llvm::TargetData *TD,
522 std::vector<const char*>& ExportSymbols,
523 llvm::CodeGenOpt::Level OptimizationLevel) {
524 // Note: ExportSymbols is a workaround for getting all exported variable,
525 // function, and kernel names.
526 // We should refine it soon.
527
528 // TODO(logan): Remove this after we have finished the
529 // bccMarkExternalSymbol API.
530
531 // root(), init(), and .rs.dtor() are born to be exported
532 ExportSymbols.push_back("root");
533 ExportSymbols.push_back("init");
534 ExportSymbols.push_back(".rs.dtor");
535
536 // User-defined exporting symbols
537 std::vector<char const *> const &UserDefinedExternalSymbols =
538 mpResult->getUserDefinedExternalSymbols();
539
540 std::copy(UserDefinedExternalSymbols.begin(),
541 UserDefinedExternalSymbols.end(),
542 std::back_inserter(ExportSymbols));
543
544 llvm::PassManager LTOPasses;
545
546 // Add TargetData to LTO passes
547 LTOPasses.add(TD);
Daniel Malea094881f2011-12-14 17:39:16 -0500548
Logan Chien4cc00332011-06-12 14:00:46 +0800549 // We now create passes list performing LTO. These are copied from
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700550 // (including comments) llvm::createStandardLTOPasses().
551 // Only a subset of these LTO passes are enabled in optimization level 0
552 // as they interfere with interactive debugging.
553 // FIXME: figure out which passes (if any) makes sense for levels 1 and 2
554
555 if (OptimizationLevel != llvm::CodeGenOpt::None) {
556 // Internalize all other symbols not listed in ExportSymbols
557 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
558
Daniel Malea094881f2011-12-14 17:39:16 -0500559 // Propagate constants at call sites into the functions they call. This
560 // opens opportunities for globalopt (and inlining) by substituting
561 // function pointers passed as arguments to direct uses of functions.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700562 LTOPasses.add(llvm::createIPSCCPPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800563
Daniel Malea094881f2011-12-14 17:39:16 -0500564 // Now that we internalized some globals, see if we can hack on them!
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700565 LTOPasses.add(llvm::createGlobalOptimizerPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800566
Daniel Malea094881f2011-12-14 17:39:16 -0500567 // Linking modules together can lead to duplicated global constants, only
568 // keep one copy of each constant...
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700569 LTOPasses.add(llvm::createConstantMergePass());
Logan Chien4cc00332011-06-12 14:00:46 +0800570
Daniel Malea094881f2011-12-14 17:39:16 -0500571 // Remove unused arguments from functions...
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700572 LTOPasses.add(llvm::createDeadArgEliminationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800573
Daniel Malea094881f2011-12-14 17:39:16 -0500574 // Reduce the code after globalopt and ipsccp. Both can open up
575 // significant simplification opportunities, and both can propagate
576 // functions through function pointers. When this happens, we often have
577 // to resolve varargs calls, etc, so let instcombine do this.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700578 LTOPasses.add(llvm::createInstructionCombiningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800579
Daniel Malea094881f2011-12-14 17:39:16 -0500580 // Inline small functions
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700581 LTOPasses.add(llvm::createFunctionInliningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800582
Daniel Malea094881f2011-12-14 17:39:16 -0500583 // Remove dead EH info.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700584 LTOPasses.add(llvm::createPruneEHPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800585
Daniel Malea094881f2011-12-14 17:39:16 -0500586 // Internalize the globals again after inlining
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700587 LTOPasses.add(llvm::createGlobalOptimizerPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800588
Daniel Malea094881f2011-12-14 17:39:16 -0500589 // Remove dead functions.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700590 LTOPasses.add(llvm::createGlobalDCEPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800591
Daniel Malea094881f2011-12-14 17:39:16 -0500592 // If we didn't decide to inline a function, check to see if we can
593 // transform it to pass arguments by value instead of by reference.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700594 LTOPasses.add(llvm::createArgumentPromotionPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800595
Daniel Malea094881f2011-12-14 17:39:16 -0500596 // The IPO passes may leave cruft around. Clean up after them.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700597 LTOPasses.add(llvm::createInstructionCombiningPass());
598 LTOPasses.add(llvm::createJumpThreadingPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800599
Daniel Malea094881f2011-12-14 17:39:16 -0500600 // Break up allocas
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700601 LTOPasses.add(llvm::createScalarReplAggregatesPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800602
Daniel Malea094881f2011-12-14 17:39:16 -0500603 // Run a few AA driven optimizations here and now, to cleanup the code.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700604 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
605 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
Logan Chien4cc00332011-06-12 14:00:46 +0800606
Daniel Malea094881f2011-12-14 17:39:16 -0500607 // Hoist loop invariants.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700608 LTOPasses.add(llvm::createLICMPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800609
Daniel Malea094881f2011-12-14 17:39:16 -0500610 // Remove redundancies.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700611 LTOPasses.add(llvm::createGVNPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800612
Daniel Malea094881f2011-12-14 17:39:16 -0500613 // Remove dead memcpys.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700614 LTOPasses.add(llvm::createMemCpyOptPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800615
Daniel Malea094881f2011-12-14 17:39:16 -0500616 // Nuke dead stores.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700617 LTOPasses.add(llvm::createDeadStoreEliminationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800618
Daniel Malea094881f2011-12-14 17:39:16 -0500619 // Cleanup and simplify the code after the scalar optimizations.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700620 LTOPasses.add(llvm::createInstructionCombiningPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800621
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700622 LTOPasses.add(llvm::createJumpThreadingPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800623
Daniel Malea094881f2011-12-14 17:39:16 -0500624 // Delete basic blocks, which optimization passes may have killed.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700625 LTOPasses.add(llvm::createCFGSimplificationPass());
Logan Chien4cc00332011-06-12 14:00:46 +0800626
Daniel Malea094881f2011-12-14 17:39:16 -0500627 // Now that we have optimized the program, discard unreachable functions.
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700628 LTOPasses.add(llvm::createGlobalDCEPass());
629
630 } else {
631 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
632 LTOPasses.add(llvm::createGlobalOptimizerPass());
633 LTOPasses.add(llvm::createConstantMergePass());
Daniel Malea094881f2011-12-14 17:39:16 -0500634 }
Logan Chien4cc00332011-06-12 14:00:46 +0800635
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700636 LTOPasses.run(*mModule);
637
638#if ANDROID_ENGINEERING_BUILD
639 if (0 != gDebugDumpDirectory) {
640 std::string errs;
641 std::string Filename(gDebugDumpDirectory);
642 Filename += "/post-lto-module.ll";
643 llvm::raw_fd_ostream FS(Filename.c_str(), errs);
644 mModule->print(FS, 0);
645 FS.close();
Daniel Malea094881f2011-12-14 17:39:16 -0500646 }
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700647#endif
Daniel Malea094881f2011-12-14 17:39:16 -0500648
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700649 return 0;
Logan Chien4cc00332011-06-12 14:00:46 +0800650}
651
652
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700653void *Compiler::getSymbolAddress(char const *name) {
654 return rsloaderGetSymbolAddress(mRSExecutable, name);
Logan Chienda5e0c32011-06-13 03:47:21 +0800655}
Logan Chienda5e0c32011-06-13 03:47:21 +0800656
Stephen Hines5fb14742012-05-03 12:29:50 -0700657
658void *Compiler::resolveSymbolAdapter(void *context, char const *name) {
659 Compiler *self = reinterpret_cast<Compiler *>(context);
660
661 if (void *Addr = FindRuntimeFunction(name)) {
662 return Addr;
663 }
664
665 if (self->mpSymbolLookupFn) {
666 if (void *Addr = self->mpSymbolLookupFn(self->mpSymbolLookupContext, name)) {
667 return Addr;
668 }
669 }
670
671 ALOGE("Unable to resolve symbol: %s\n", name);
672 return NULL;
673}
674
675
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700676Compiler::~Compiler() {
677 rsloaderDisposeExec(mRSExecutable);
Logan Chienda5e0c32011-06-13 03:47:21 +0800678
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700679 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800680}
681
Shih-wei Liao90cd3d12011-06-20 15:43:34 -0700682
Stephen Hines4a68b1c2012-05-03 12:28:14 -0700683} // namespace bcc