blob: 8770528d9396347bca379d8deab4b5f2ef721053 [file] [log] [blame]
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001/*
Zonr Chang932648d2010-10-13 22:23:56 +08002 * Copyright 2010, The Android Open Source Project
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003 *
Zonr Chang932648d2010-10-13 22:23:56 +08004 * 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.
Shih-wei Liao77ed6142010-04-07 12:21:42 -070015 */
16
Zonr Chang932648d2010-10-13 22:23:56 +080017// Bitcode compiler (bcc) for Android:
18// This is an eager-compilation JIT running on Android.
19
Shih-wei Liao3d77c422010-11-21 19:51:59 -080020// Fixed BCC_CODE_ADDR here only works for 1 cached EXE.
Loganad7e8e12010-11-22 20:43:43 +080021// At most 1 live Compiler object will have set BccCodeAddrTaken
Shih-wei Liao3d77c422010-11-21 19:51:59 -080022#define BCC_CODE_ADDR 0x7e00000
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -080023
Shih-wei Liao77ed6142010-04-07 12:21:42 -070024#define LOG_TAG "bcc"
25#include <cutils/log.h>
26
27#include <ctype.h>
28#include <errno.h>
29#include <limits.h>
30#include <stdarg.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -080034#include <stddef.h>
Shih-wei Liao77ed6142010-04-07 12:21:42 -070035#include <string.h>
36#include <unistd.h>
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -070037#include <sys/mman.h>
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -080038#include <sys/file.h>
39#include <sys/stat.h>
40#include <sys/types.h>
Shih-wei Liao77ed6142010-04-07 12:21:42 -070041
42#include <cutils/hashmap.h>
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -080043#include <utils/StopWatch.h>
Shih-wei Liao77ed6142010-04-07 12:21:42 -070044
Shih-wei Liao77ed6142010-04-07 12:21:42 -070045#if defined(__arm__)
Zonr Chang932648d2010-10-13 22:23:56 +080046# define DEFAULT_ARM_CODEGEN
47# define PROVIDE_ARM_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070048#elif defined(__i386__)
Zonr Chang932648d2010-10-13 22:23:56 +080049# define DEFAULT_X86_CODEGEN
50# define PROVIDE_X86_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070051#elif defined(__x86_64__)
Zonr Chang932648d2010-10-13 22:23:56 +080052# define DEFAULT_X64_CODEGEN
53# define PROVIDE_X64_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070054#endif
55
56#if defined(FORCE_ARM_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080057# define DEFAULT_ARM_CODEGEN
58# undef DEFAULT_X86_CODEGEN
59# undef DEFAULT_X64_CODEGEN
60# define PROVIDE_ARM_CODEGEN
61# undef PROVIDE_X86_CODEGEN
62# undef PROVIDE_X64_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070063#elif defined(FORCE_X86_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080064# undef DEFAULT_ARM_CODEGEN
65# define DEFAULT_X86_CODEGEN
66# undef DEFAULT_X64_CODEGEN
67# undef PROVIDE_ARM_CODEGEN
68# define PROVIDE_X86_CODEGEN
69# undef PROVIDE_X64_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070070#elif defined(FORCE_X64_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080071# undef DEFAULT_ARM_CODEGEN
72# undef DEFAULT_X86_CODEGEN
73# define DEFAULT_X64_CODEGEN
74# undef PROVIDE_ARM_CODEGEN
75# undef PROVIDE_X86_CODEGEN
76# define PROVIDE_X64_CODEGEN
Shih-wei Liao77ed6142010-04-07 12:21:42 -070077#endif
78
79#if defined(DEFAULT_ARM_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080080# define TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
Shih-wei Liao77ed6142010-04-07 12:21:42 -070081#elif defined(DEFAULT_X86_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080082# define TARGET_TRIPLE_STRING "i686-unknown-linux"
Shih-wei Liao77ed6142010-04-07 12:21:42 -070083#elif defined(DEFAULT_X64_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +080084# define TARGET_TRIPLE_STRING "x86_64-unknown-linux"
Shih-wei Liao77ed6142010-04-07 12:21:42 -070085#endif
86
87#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
Zonr Chang932648d2010-10-13 22:23:56 +080088# define ARM_USE_VFP
Shih-wei Liao77ed6142010-04-07 12:21:42 -070089#endif
90
91#include <bcc/bcc.h>
92#include "bcc_runtime.h"
93
Zonr Chang932648d2010-10-13 22:23:56 +080094#define LOG_API(...) do {} while (0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -070095// #define LOG_API(...) fprintf (stderr, __VA_ARGS__)
96
Zonr Chang932648d2010-10-13 22:23:56 +080097#define LOG_STACK(...) do {} while (0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -070098// #define LOG_STACK(...) fprintf (stderr, __VA_ARGS__)
99
100// #define PROVIDE_TRACE_CODEGEN
101
102#if defined(USE_DISASSEMBLER)
Zonr Chang932648d2010-10-13 22:23:56 +0800103# include "llvm/MC/MCInst.h"
104# include "llvm/MC/MCAsmInfo.h"
105# include "llvm/MC/MCInstPrinter.h"
106# include "llvm/MC/MCDisassembler.h"
Shih-wei Liao3cf39d12010-04-29 19:30:51 -0700107// If you want the disassemble results written to file, define this:
108# define USE_DISASSEMBLER_FILE
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700109#endif
110
111#include <set>
112#include <map>
113#include <list>
114#include <cmath>
115#include <string>
116#include <cstring>
Zonr Chang932648d2010-10-13 22:23:56 +0800117#include <algorithm> // for std::reverse
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700118
Zonr Chang932648d2010-10-13 22:23:56 +0800119// VMCore
120#include "llvm/Use.h"
121#include "llvm/User.h"
Zonr Chang97f5e612010-10-22 20:38:26 +0800122#include "llvm/Linker.h"
Zonr Chang932648d2010-10-13 22:23:56 +0800123#include "llvm/Module.h"
124#include "llvm/Function.h"
125#include "llvm/Constant.h"
126#include "llvm/Constants.h"
127#include "llvm/Instruction.h"
128#include "llvm/PassManager.h"
129#include "llvm/LLVMContext.h"
130#include "llvm/GlobalValue.h"
131#include "llvm/Instructions.h"
132#include "llvm/OperandTraits.h"
133#include "llvm/TypeSymbolTable.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700134
135// System
Zonr Chang932648d2010-10-13 22:23:56 +0800136#include "llvm/System/Host.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700137
138// ADT
Zonr Chang932648d2010-10-13 22:23:56 +0800139#include "llvm/ADT/APInt.h"
140#include "llvm/ADT/APFloat.h"
141#include "llvm/ADT/DenseMap.h"
142#include "llvm/ADT/ValueMap.h"
143#include "llvm/ADT/StringMap.h"
144#include "llvm/ADT/OwningPtr.h"
145#include "llvm/ADT/SmallString.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700146
147// Target
Zonr Chang932648d2010-10-13 22:23:56 +0800148#include "llvm/Target/TargetData.h"
149#include "llvm/Target/TargetSelect.h"
150#include "llvm/Target/TargetOptions.h"
151#include "llvm/Target/TargetMachine.h"
152#include "llvm/Target/TargetJITInfo.h"
153#include "llvm/Target/TargetRegistry.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700154#include "llvm/Target/SubtargetFeature.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700155
156// Support
Zonr Chang932648d2010-10-13 22:23:56 +0800157#include "llvm/Support/Casting.h"
158#include "llvm/Support/raw_ostream.h"
159#include "llvm/Support/ValueHandle.h"
160#include "llvm/Support/MemoryBuffer.h"
161#include "llvm/Support/MemoryObject.h"
162#include "llvm/Support/ManagedStatic.h"
163#include "llvm/Support/ErrorHandling.h"
164#include "llvm/Support/StandardPasses.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700165#include "llvm/Support/FormattedStream.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700166
167// Bitcode
Zonr Chang932648d2010-10-13 22:23:56 +0800168#include "llvm/Bitcode/ReaderWriter.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700169
170// CodeGen
Zonr Chang932648d2010-10-13 22:23:56 +0800171#include "llvm/CodeGen/Passes.h"
172#include "llvm/CodeGen/JITCodeEmitter.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700173#include "llvm/CodeGen/MachineFunction.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700174#include "llvm/CodeGen/RegAllocRegistry.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700175#include "llvm/CodeGen/SchedulerRegistry.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700176#include "llvm/CodeGen/MachineRelocation.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700177#include "llvm/CodeGen/MachineModuleInfo.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700178#include "llvm/CodeGen/MachineCodeEmitter.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700179#include "llvm/CodeGen/MachineConstantPool.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700180#include "llvm/CodeGen/MachineJumpTableInfo.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700181
182// ExecutionEngine
183#include "llvm/ExecutionEngine/GenericValue.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700184#include "llvm/ExecutionEngine/JITMemoryManager.h"
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700185
Shih-wei Liaoe64c2872010-10-25 13:44:53 -0700186extern "C" void LLVMInitializeARMDisassembler();
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700187
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800188// For caching
189struct oBCCHeader {
190 uint8_t magic[4]; // includes version number
191 uint8_t magicVersion[4];
192
193 uint32_t sourceWhen;
194 uint32_t rslibWhen;
195 uint32_t libRSWhen;
196 uint32_t libbccWhen;
197
198 uint32_t cachedCodeDataAddr;
199 uint32_t rootAddr;
200 uint32_t initAddr;
201
202 uint32_t relocOffset; // offset of reloc table.
203 uint32_t relocCount;
204 uint32_t exportVarsOffset; // offset of export var table
205 uint32_t exportVarsCount;
206 uint32_t exportFuncsOffset; // offset of export func table
207 uint32_t exportFuncsCount;
208 uint32_t exportPragmasOffset; // offset of export pragma table
209 uint32_t exportPragmasCount;
210
211 uint32_t codeOffset; // offset of code: 64-bit alignment
212 uint32_t codeSize;
213 uint32_t dataOffset; // offset of data section
214 uint32_t dataSize;
215
216 // uint32_t flags; // some info flags
217 uint32_t checksum; // adler32 checksum covering deps/opt
218};
219
Logan824dd0a2010-11-20 01:45:54 +0800220struct oBCCRelocEntry {
221 uint32_t relocType; // target instruction relocation type
222 uint32_t relocOffset; // offset of hole (holeAddr - codeAddr)
223 uint32_t cachedResultAddr; // address resolved at compile time
224
Logan634bd832010-11-20 09:00:36 +0800225 oBCCRelocEntry(uint32_t ty, uintptr_t off, void *addr)
Logan824dd0a2010-11-20 01:45:54 +0800226 : relocType(ty),
227 relocOffset(static_cast<uint32_t>(off)),
228 cachedResultAddr(reinterpret_cast<uint32_t>(addr)) {
229 }
230};
231
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800232/* oBCCHeader Offset Table */
233#define k_magic offsetof(oBCCHeader, magic)
234#define k_magicVersion offsetof(oBCCHeader, magicVersion)
235#define k_sourceWhen offsetof(oBCCHeader, sourceWhen)
236#define k_rslibWhen offsetof(oBCCHeader, rslibWhen)
237#define k_libRSWhen offsetof(oBCCHeader, libRSWhen)
238#define k_libbccWhen offsetof(oBCCHeader, libbccWhen)
239#define k_cachedCodeDataAddr offsetof(oBCCHeader, cachedCodeDataAddr)
240#define k_rootAddr offsetof(oBCCHeader, rootAddr)
241#define k_initAddr offsetof(oBCCHeader, initAddr)
242#define k_relocOffset offsetof(oBCCHeader, relocOffset)
243#define k_relocCount offsetof(oBCCHeader, relocCount)
244#define k_exportVarsOffset offsetof(oBCCHeader, exportVarsOffset)
245#define k_exportVarsCount offsetof(oBCCHeader, exportVarsCount)
246#define k_exportFuncsOffset offsetof(oBCCHeader, exportFuncsOffset)
247#define k_exportFuncsCount offsetof(oBCCHeader, exportFuncsCount)
248#define k_exportPragmasOffset offsetof(oBCCHeader, exportPragmasOffset)
249#define k_exportPragmasCount offsetof(oBCCHeader, exportPragmasCount)
250#define k_codeOffset offsetof(oBCCHeader, codeOffset)
251#define k_codeSize offsetof(oBCCHeader, codeSize)
252#define k_dataOffset offsetof(oBCCHeader, dataOffset)
253#define k_dataSize offsetof(oBCCHeader, dataSize)
254#define k_checksum offsetof(oBCCHeader, checksum)
255
256/* oBCC file magic number */
257#define OBCC_MAGIC "bcc\n"
258/* version, encoded in 4 bytes of ASCII */
259#define OBCC_MAGIC_VERS "001\0"
260
261#define TEMP_FAILURE_RETRY1(exp) ({ \
262 typeof (exp) _rc; \
263 do { \
264 _rc = (exp); \
265 } while (_rc == -1 && errno == EINTR); \
266 _rc; })
267
268static int sysWriteFully(int fd, const void* buf, size_t count, const char* logMsg)
269{
270 while (count != 0) {
271 ssize_t actual = TEMP_FAILURE_RETRY1(write(fd, buf, count));
272 if (actual < 0) {
273 int err = errno;
274 LOGE("%s: write failed: %s\n", logMsg, strerror(err));
275 return err;
276 } else if (actual != (ssize_t) count) {
277 LOGD("%s: partial write (will retry): (%d of %zd)\n",
278 logMsg, (int) actual, count);
279 buf = (const void*) (((const uint8_t*) buf) + actual);
280 }
281 count -= actual;
282 }
283
284 return 0;
285}
286
Zonr Chang932648d2010-10-13 22:23:56 +0800287//
288// Compilation class that suits Android's needs.
289// (Support: no argument passed, ...)
290//
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700291namespace bcc {
292
293class Compiler {
Zonr Chang932648d2010-10-13 22:23:56 +0800294 // This part is designed to be orthogonal to those exported bcc*() functions
295 // implementation and internal struct BCCscript.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700296
Zonr Chang932648d2010-10-13 22:23:56 +0800297 //////////////////////////////////////////////////////////////////////////////
298 // The variable section below (e.g., Triple, CodeGenOptLevel)
299 // is initialized in GlobalInitialization()
300 //
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700301 static bool GlobalInitialized;
Loganad7e8e12010-11-22 20:43:43 +0800302 static bool BccCodeAddrTaken;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700303
Zonr Chang932648d2010-10-13 22:23:56 +0800304 // If given, this will be the name of the target triple to compile for.
305 // If not given, the initial values defined in this file will be used.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700306 static std::string Triple;
307
308 static llvm::CodeGenOpt::Level CodeGenOptLevel;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700309
Zonr Chang932648d2010-10-13 22:23:56 +0800310 // End of section of GlobalInitializing variables
311 //////////////////////////////////////////////////////////////////////////////
312
313 // If given, the name of the target CPU to generate code for.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700314 static std::string CPU;
315
Zonr Chang932648d2010-10-13 22:23:56 +0800316 // The list of target specific features to enable or disable -- this should
317 // be a list of strings starting with '+' (enable) or '-' (disable).
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700318 static std::vector<std::string> Features;
319
320 struct Runtime {
Zonr Chang932648d2010-10-13 22:23:56 +0800321 const char *mName;
322 void *mPtr;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700323 };
324 static struct Runtime Runtimes[];
325
326 static void GlobalInitialization() {
Zonr Chang932648d2010-10-13 22:23:56 +0800327 if (GlobalInitialized)
328 return;
Shih-wei Liaobe5c5312010-05-09 05:30:09 -0700329
Zonr Chang932648d2010-10-13 22:23:56 +0800330 // if (!llvm::llvm_is_multithreaded())
331 // llvm::llvm_start_multithreaded();
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700332
Zonr Chang932648d2010-10-13 22:23:56 +0800333 // Set Triple, CPU and Features here
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700334 Triple = TARGET_TRIPLE_STRING;
335
Zonr Chang932648d2010-10-13 22:23:56 +0800336 // TODO(zonr): NEON for JIT
337 // Features.push_back("+neon");
338 // Features.push_back("+vmlx");
339 // Features.push_back("+neonfp");
Shih-wei Liao3cf39d12010-04-29 19:30:51 -0700340 Features.push_back("+vfp3");
Shih-wei Liao21ef3072010-10-23 22:33:12 -0700341 Features.push_back("+d16");
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700342
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700343#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
344 LLVMInitializeARMTargetInfo();
345 LLVMInitializeARMTarget();
Shih-wei Liaocd61af32010-04-29 00:02:57 -0700346#if defined(USE_DISASSEMBLER)
347 LLVMInitializeARMDisassembler();
348 LLVMInitializeARMAsmPrinter();
349#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700350#endif
351
352#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
353 LLVMInitializeX86TargetInfo();
354 LLVMInitializeX86Target();
Shih-wei Liaocd61af32010-04-29 00:02:57 -0700355#if defined(USE_DISASSEMBLER)
356 LLVMInitializeX86Disassembler();
357 LLVMInitializeX86AsmPrinter();
358#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700359#endif
360
361#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
362 LLVMInitializeX86TargetInfo();
363 LLVMInitializeX86Target();
Shih-wei Liaocd61af32010-04-29 00:02:57 -0700364#if defined(USE_DISASSEMBLER)
365 LLVMInitializeX86Disassembler();
366 LLVMInitializeX86AsmPrinter();
367#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700368#endif
369
Zonr Chang932648d2010-10-13 22:23:56 +0800370 // -O0: llvm::CodeGenOpt::None
371 // -O1: llvm::CodeGenOpt::Less
372 // -O2: llvm::CodeGenOpt::Default
373 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liaobfda6c92010-10-24 02:43:04 -0700374 CodeGenOptLevel = llvm::CodeGenOpt::None;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700375
Zonr Chang932648d2010-10-13 22:23:56 +0800376 // Below are the global settings to LLVM
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700377
Zonr Chang932648d2010-10-13 22:23:56 +0800378 // Disable frame pointer elimination optimization
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700379 llvm::NoFramePointerElim = false;
380
Zonr Chang932648d2010-10-13 22:23:56 +0800381 // Use hardfloat ABI
382 //
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800383 // TODO(all): Need to detect the CPU capability and decide whether to use
Zonr Chang932648d2010-10-13 22:23:56 +0800384 // softfp. To use softfp, change following 2 lines to
385 //
386 // llvm::FloatABIType = llvm::FloatABI::Soft;
387 // llvm::UseSoftFloat = true;
388 //
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700389 llvm::FloatABIType = llvm::FloatABI::Soft;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700390 llvm::UseSoftFloat = false;
391
Zonr Chang932648d2010-10-13 22:23:56 +0800392 // BCC needs all unknown symbols resolved at JIT/compilation time.
393 // So we don't need any dynamic relocation model.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700394 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
395
Shih-wei Liaocd61af32010-04-29 00:02:57 -0700396#if defined(DEFAULT_X64_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +0800397 // Data address in X86_64 architecture may reside in a far-away place
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700398 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
399#else
Zonr Chang932648d2010-10-13 22:23:56 +0800400 // This is set for the linker (specify how large of the virtual addresses
401 // we can access for all unknown symbols.)
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700402 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
403#endif
404
Zonr Chang932648d2010-10-13 22:23:56 +0800405 // Register the scheduler
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700406 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
407
Zonr Chang932648d2010-10-13 22:23:56 +0800408 // Register allocation policy:
409 // createFastRegisterAllocator: fast but bad quality
410 // createLinearScanRegisterAllocator: not so fast but good quality
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700411 llvm::RegisterRegAlloc::setDefault
412 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
Shih-wei Liao16016012010-09-10 17:55:03 -0700413 llvm::createFastRegisterAllocator :
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700414 llvm::createLinearScanRegisterAllocator);
415
416 GlobalInitialized = true;
417 return;
418 }
419
420 static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Zonr Chang932648d2010-10-13 22:23:56 +0800421 std::string *Error = static_cast<std::string*>(UserData);
Shih-wei Liao066d5ef2010-05-11 03:28:39 -0700422 Error->assign(Message);
Nick Kralevichfc97e9f2010-05-17 14:59:16 -0700423 LOGE("%s", Message.c_str());
Zonr Chang932648d2010-10-13 22:23:56 +0800424 exit(1);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700425 }
426
427 static const llvm::StringRef PragmaMetadataName;
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700428 static const llvm::StringRef ExportVarMetadataName;
Shih-wei Liao6bfd5422010-05-07 05:20:22 -0700429 static const llvm::StringRef ExportFuncMetadataName;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700430
431 private:
Shih-wei Liaoc5611992010-05-09 06:37:55 -0700432 std::string mError;
433
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700434 inline bool hasError() const {
435 return !mError.empty();
436 }
Zonr Chang932648d2010-10-13 22:23:56 +0800437 inline void setError(const char *Error) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700438 mError.assign(Error); // Copying
439 return;
440 }
Zonr Chang932648d2010-10-13 22:23:56 +0800441 inline void setError(const std::string &Error) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700442 mError = Error;
443 return;
444 }
445
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800446 bool mNeverCache; // Set by readBC()
447 bool mCacheNew; // Set by readBC()
448 int mCacheFd; // Set by readBC()
449 char *mCacheMapAddr; // Set by loader() if mCacheNew is false
450 oBCCHeader *mCacheHdr; // Set by loader()
Shih-wei Liao7f941bb2010-11-19 01:40:16 -0800451 size_t mCacheSize; // Set by loader()
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800452 ptrdiff_t mCacheDiff; // Set by loader()
453 char *mCodeDataAddr; // Set by CodeMemoryManager if mCacheNew is true.
454 // Used by genCacheFile() for dumping
455
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700456 typedef std::list< std::pair<std::string, std::string> > PragmaList;
457 PragmaList mPragmas;
458
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700459 typedef std::list<void*> ExportVarList;
460 ExportVarList mExportVars;
461
Shih-wei Liao6bfd5422010-05-07 05:20:22 -0700462 typedef std::list<void*> ExportFuncList;
463 ExportFuncList mExportFuncs;
464
Zonr Chang932648d2010-10-13 22:23:56 +0800465 //////////////////////////////////////////////////////////////////////////////
466 // Memory manager for the code reside in memory
467 //
468 // The memory for our code emitter is very simple and is conforming to the
469 // design decisions of Android RenderScript's Exection Environment:
470 // The code, data, and symbol sizes are limited (currently 100KB.)
471 //
472 // It's very different from typical compiler, which has no limitation
473 // on the code size. How does code emitter know the size of the code
474 // it is about to emit? It does not know beforehand. We want to solve
475 // this without complicating the code emitter too much.
476 //
477 // We solve this by pre-allocating a certain amount of memory,
478 // and then start the code emission. Once the buffer overflows, the emitter
479 // simply discards all the subsequent emission but still has a counter
480 // on how many bytes have been emitted.
481 //
482 // So once the whole emission is done, if there's a buffer overflow,
483 // it re-allocates the buffer with enough size (based on the
484 // counter from previous emission) and re-emit again.
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800485
486 // 128 KiB for code
487 static const unsigned int MaxCodeSize = 128 * 1024;
488 // 1 KiB for global offset table (GOT)
489 static const unsigned int MaxGOTSize = 1 * 1024;
490 // 128 KiB for global variable
491 static const unsigned int MaxGlobalVarSize = 128 * 1024;
492
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700493 class CodeMemoryManager : public llvm::JITMemoryManager {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700494 private:
Zonr Chang932648d2010-10-13 22:23:56 +0800495 //
496 // Our memory layout is as follows:
497 //
498 // The direction of arrows (-> and <-) shows memory's growth direction
499 // when more space is needed.
500 //
501 // @mpCodeMem:
502 // +--------------------------------------------------------------+
503 // | Function Memory ... -> <- ... Stub/GOT |
504 // +--------------------------------------------------------------+
505 // |<------------------ Total: @MaxCodeSize KiB ----------------->|
506 //
507 // Where size of GOT is @MaxGOTSize KiB.
508 //
509 // @mpGVMem:
510 // +--------------------------------------------------------------+
511 // | Global variable ... -> |
512 // +--------------------------------------------------------------+
513 // |<--------------- Total: @MaxGlobalVarSize KiB --------------->|
514 //
515 //
516 // @mCurFuncMemIdx: The current index (starting from 0) of the last byte
517 // of function code's memory usage
518 // @mCurSGMemIdx: The current index (starting from tail) of the last byte
519 // of stub/GOT's memory usage
520 // @mCurGVMemIdx: The current index (starting from tail) of the last byte
521 // of global variable's memory usage
522 //
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700523 uintptr_t mCurFuncMemIdx;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700524 uintptr_t mCurSGMemIdx;
525 uintptr_t mCurGVMemIdx;
Zonr Chang932648d2010-10-13 22:23:56 +0800526 void *mpCodeMem;
527 void *mpGVMem;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700528
Zonr Chang932648d2010-10-13 22:23:56 +0800529 // GOT Base
530 uint8_t *mpGOTBase;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700531
532 typedef std::map<const llvm::Function*, pair<void* /* start address */,
533 void* /* end address */>
534 > FunctionMapTy;
535 FunctionMapTy mFunctionMap;
536
Zonr Chang932648d2010-10-13 22:23:56 +0800537 inline intptr_t getFreeCodeMemSize() const {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700538 return mCurSGMemIdx - mCurFuncMemIdx;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700539 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700540
Zonr Chang932648d2010-10-13 22:23:56 +0800541 uint8_t *allocateSGMemory(uintptr_t Size,
542 unsigned Alignment = 1 /* no alignment */) {
543 intptr_t FreeMemSize = getFreeCodeMemSize();
544 if ((FreeMemSize < 0) || (static_cast<uintptr_t>(FreeMemSize) < Size))
545 // The code size excesses our limit
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700546 return NULL;
547
Zonr Chang932648d2010-10-13 22:23:56 +0800548 if (Alignment == 0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700549 Alignment = 1;
550
Zonr Chang932648d2010-10-13 22:23:56 +0800551 uint8_t *result = getCodeMemBase() + mCurSGMemIdx - Size;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700552 result = (uint8_t*) (((intptr_t) result) & ~(intptr_t) (Alignment - 1));
553
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700554 mCurSGMemIdx = result - getCodeMemBase();
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700555
556 return result;
557 }
558
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700559 inline uintptr_t getFreeGVMemSize() const {
560 return MaxGlobalVarSize - mCurGVMemIdx;
561 }
Zonr Chang932648d2010-10-13 22:23:56 +0800562 inline uint8_t *getGVMemBase() const {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700563 return reinterpret_cast<uint8_t*>(mpGVMem);
564 }
565
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700566 public:
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700567 CodeMemoryManager() : mpCodeMem(NULL), mpGVMem(NULL), mpGOTBase(NULL) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700568 reset();
569 std::string ErrMsg;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700570
Loganad7e8e12010-11-22 20:43:43 +0800571 if (!Compiler::BccCodeAddrTaken) { // Try to use BCC_CODE_ADDR
572 mpCodeMem = mmap(reinterpret_cast<void*>(BCC_CODE_ADDR),
573 MaxCodeSize + MaxGlobalVarSize,
574 PROT_READ | PROT_EXEC | PROT_WRITE,
575 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
576 -1, 0);
Shih-wei Liao1f45b862010-11-21 23:22:38 -0800577
Loganad7e8e12010-11-22 20:43:43 +0800578 if (mpCodeMem == MAP_FAILED) {
579 LOGE("Mmap mpCodeMem at %p failed with reason: %s.\n",
580 reinterpret_cast<void *>(BCC_CODE_ADDR), strerror(errno));
581 LOGE("Retry to mmap mpCodeMem at arbitary address\n");
582 }
583 }
584
585 if (Compiler::BccCodeAddrTaken || mpCodeMem == MAP_FAILED) {
586 // If BCC_CODE_ADDR has been occuppied, or we can't allocate
587 // mpCodeMem in previous mmap, then allocate them in arbitary
588 // location.
589
Shih-wei Liao1f45b862010-11-21 23:22:38 -0800590 mpCodeMem = mmap(NULL,
591 MaxCodeSize + MaxGlobalVarSize,
592 PROT_READ | PROT_EXEC | PROT_WRITE,
593 MAP_PRIVATE | MAP_ANON,
Loganad7e8e12010-11-22 20:43:43 +0800594 -1, 0);
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800595
Loganad7e8e12010-11-22 20:43:43 +0800596 if (mpCodeMem == MAP_FAILED) {
597 LOGE("Unable to mmap mpCodeMem with reason: %s.\n", strerror(errno));
598 llvm::report_fatal_error("Failed to allocate memory for emitting "
599 "codes\n" + ErrMsg);
600 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800601 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800602
Loganad7e8e12010-11-22 20:43:43 +0800603 // One instance of script is occupping BCC_CODE_ADDR
604 Compiler::BccCodeAddrTaken = true;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700605
Loganad7e8e12010-11-22 20:43:43 +0800606 // Set global variable pool
607 mpGVMem = (void *) ((char *)mpCodeMem + MaxCodeSize);
608
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700609 return;
610 }
611
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800612 inline uint8_t *getCodeMemBase() const {
613 return reinterpret_cast<uint8_t*>(mpCodeMem);
614 }
615
Zonr Chang932648d2010-10-13 22:23:56 +0800616 // setMemoryWritable - When code generation is in progress, the code pages
617 // may need permissions changed.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700618 void setMemoryWritable() {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700619 ::mprotect(mpCodeMem, MaxCodeSize, PROT_READ | PROT_WRITE | PROT_EXEC);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700620 return;
621 }
622
Zonr Chang932648d2010-10-13 22:23:56 +0800623 // When code generation is done and we're ready to start execution, the
624 // code pages may need permissions changed.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700625 void setMemoryExecutable() {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700626 ::mprotect(mpCodeMem, MaxCodeSize, PROT_READ | PROT_EXEC);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700627 return;
628 }
629
Zonr Chang932648d2010-10-13 22:23:56 +0800630 // Setting this flag to true makes the memory manager garbage values over
631 // freed memory. This is useful for testing and debugging, and is to be
632 // turned on by default in debug mode.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700633 void setPoisonMemory(bool poison) {
Zonr Chang932648d2010-10-13 22:23:56 +0800634 // no effect
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700635 return;
636 }
637
Zonr Chang932648d2010-10-13 22:23:56 +0800638 // Global Offset Table Management
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700639
Zonr Chang932648d2010-10-13 22:23:56 +0800640 // If the current table requires a Global Offset Table, this method is
641 // invoked to allocate it. This method is required to set HasGOT to true.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700642 void AllocateGOT() {
643 assert(mpGOTBase != NULL && "Cannot allocate the GOT multiple times");
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700644 mpGOTBase = allocateSGMemory(MaxGOTSize);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700645 HasGOT = true;
646 return;
647 }
648
Zonr Chang932648d2010-10-13 22:23:56 +0800649 // If this is managing a Global Offset Table, this method should return a
650 // pointer to its base.
651 uint8_t *getGOTBase() const {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700652 return mpGOTBase;
653 }
654
Zonr Chang932648d2010-10-13 22:23:56 +0800655 // Main Allocation Functions
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700656
Zonr Chang932648d2010-10-13 22:23:56 +0800657 // When we start JITing a function, the JIT calls this method to allocate a
658 // block of free RWX memory, which returns a pointer to it. If the JIT wants
659 // to request a block of memory of at least a certain size, it passes that
660 // value as ActualSize, and this method returns a block with at least that
661 // much space. If the JIT doesn't know ahead of time how much space it will
662 // need to emit the function, it passes 0 for the ActualSize. In either
663 // case, this method is required to pass back the size of the allocated
664 // block through ActualSize. The JIT will be careful to not write more than
665 // the returned ActualSize bytes of memory.
666 uint8_t *startFunctionBody(const llvm::Function *F, uintptr_t &ActualSize) {
667 intptr_t FreeMemSize = getFreeCodeMemSize();
668 if ((FreeMemSize < 0) ||
669 (static_cast<uintptr_t>(FreeMemSize) < ActualSize))
670 // The code size excesses our limit
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700671 return NULL;
672
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700673 ActualSize = getFreeCodeMemSize();
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700674 return (getCodeMemBase() + mCurFuncMemIdx);
675 }
676
Zonr Chang932648d2010-10-13 22:23:56 +0800677 // This method is called by the JIT to allocate space for a function stub
678 // (used to handle limited branch displacements) while it is JIT compiling a
679 // function. For example, if foo calls bar, and if bar either needs to be
680 // lazily compiled or is a native function that exists too far away from the
681 // call site to work, this method will be used to make a thunk for it. The
682 // stub should be "close" to the current function body, but should not be
683 // included in the 'actualsize' returned by startFunctionBody.
684 uint8_t *allocateStub(const llvm::GlobalValue *F, unsigned StubSize,
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700685 unsigned Alignment) {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700686 return allocateSGMemory(StubSize, Alignment);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700687 }
688
Zonr Chang932648d2010-10-13 22:23:56 +0800689 // This method is called when the JIT is done codegen'ing the specified
690 // function. At this point we know the size of the JIT compiled function.
691 // This passes in FunctionStart (which was returned by the startFunctionBody
692 // method) and FunctionEnd which is a pointer to the actual end of the
693 // function. This method should mark the space allocated and remember where
694 // it is in case the client wants to deallocate it.
695 void endFunctionBody(const llvm::Function *F, uint8_t *FunctionStart,
696 uint8_t *FunctionEnd) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700697 assert(FunctionEnd > FunctionStart);
698 assert(FunctionStart == (getCodeMemBase() + mCurFuncMemIdx) &&
699 "Mismatched function start/end!");
700
Zonr Chang932648d2010-10-13 22:23:56 +0800701 // Advance the pointer
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700702 intptr_t FunctionCodeSize = FunctionEnd - FunctionStart;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700703 assert(FunctionCodeSize <= getFreeCodeMemSize() &&
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700704 "Code size excess the limitation!");
705 mCurFuncMemIdx += FunctionCodeSize;
706
Zonr Chang932648d2010-10-13 22:23:56 +0800707 // Record there's a function in our memory start from @FunctionStart
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700708 assert(mFunctionMap.find(F) == mFunctionMap.end() &&
709 "Function already emitted!");
Zonr Chang932648d2010-10-13 22:23:56 +0800710 mFunctionMap.insert(
711 std::make_pair<const llvm::Function*, std::pair<void*, void*> >(
712 F, std::make_pair(FunctionStart, FunctionEnd)));
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700713
714 return;
715 }
716
Zonr Chang932648d2010-10-13 22:23:56 +0800717 // Allocate a (function code) memory block of the given size. This method
718 // cannot be called between calls to startFunctionBody and endFunctionBody.
719 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
720 if (getFreeCodeMemSize() < Size)
721 // The code size excesses our limit
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700722 return NULL;
723
Zonr Chang932648d2010-10-13 22:23:56 +0800724 if (Alignment == 0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700725 Alignment = 1;
726
Zonr Chang932648d2010-10-13 22:23:56 +0800727 uint8_t *result = getCodeMemBase() + mCurFuncMemIdx;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700728 result = (uint8_t*) (((intptr_t) result + Alignment - 1) &
Zonr Chang932648d2010-10-13 22:23:56 +0800729 ~(intptr_t) (Alignment - 1));
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700730
731 mCurFuncMemIdx = (result + Size) - getCodeMemBase();
732
733 return result;
734 }
735
Zonr Chang932648d2010-10-13 22:23:56 +0800736 // Allocate memory for a global variable.
737 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700738 if (getFreeGVMemSize() < Size) {
Zonr Chang932648d2010-10-13 22:23:56 +0800739 // The code size excesses our limit
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700740 LOGE("No Global Memory");
741 return NULL;
742 }
743
Zonr Chang932648d2010-10-13 22:23:56 +0800744 if (Alignment == 0)
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700745 Alignment = 1;
746
Zonr Chang932648d2010-10-13 22:23:56 +0800747 uint8_t *result = getGVMemBase() + mCurGVMemIdx;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700748 result = (uint8_t*) (((intptr_t) result + Alignment - 1) &
Zonr Chang932648d2010-10-13 22:23:56 +0800749 ~(intptr_t) (Alignment - 1));
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700750
751 mCurGVMemIdx = (result + Size) - getGVMemBase();
752
753 return result;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700754 }
755
Zonr Chang932648d2010-10-13 22:23:56 +0800756 // Free the specified function body. The argument must be the return value
757 // from a call to startFunctionBody() that hasn't been deallocated yet. This
758 // is never called when the JIT is currently emitting a function.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700759 void deallocateFunctionBody(void *Body) {
Zonr Chang932648d2010-10-13 22:23:56 +0800760 // linear search
761 uint8_t *FunctionStart = NULL, *FunctionEnd = NULL;
762 for (FunctionMapTy::iterator I = mFunctionMap.begin(),
763 E = mFunctionMap.end();
764 I != E;
765 I++)
766 if (I->second.first == Body) {
767 FunctionStart = reinterpret_cast<uint8_t*>(I->second.first);
768 FunctionEnd = reinterpret_cast<uint8_t*>(I->second.second);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700769 break;
Zonr Chang932648d2010-10-13 22:23:56 +0800770 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700771
Zonr Chang932648d2010-10-13 22:23:56 +0800772 assert((FunctionStart == NULL) && "Memory is never allocated!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700773
Zonr Chang932648d2010-10-13 22:23:56 +0800774 // free the memory
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700775 intptr_t SizeNeedMove = (getCodeMemBase() + mCurFuncMemIdx) - FunctionEnd;
776
777 assert(SizeNeedMove >= 0 &&
778 "Internal error: CodeMemoryManager::mCurFuncMemIdx may not"
779 " be correctly calculated!");
780
Zonr Chang932648d2010-10-13 22:23:56 +0800781 if (SizeNeedMove > 0)
782 // there's data behind deallocating function
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700783 ::memmove(FunctionStart, FunctionEnd, SizeNeedMove);
784 mCurFuncMemIdx -= (FunctionEnd - FunctionStart);
785
786 return;
787 }
788
Zonr Chang932648d2010-10-13 22:23:56 +0800789 // When we finished JITing the function, if exception handling is set, we
790 // emit the exception table.
791 uint8_t *startExceptionTable(const llvm::Function *F,
792 uintptr_t &ActualSize) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700793 assert(false && "Exception is not allowed in our language specification");
794 return NULL;
795 }
796
Zonr Chang932648d2010-10-13 22:23:56 +0800797 // This method is called when the JIT is done emitting the exception table.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700798 void endExceptionTable(const llvm::Function *F, uint8_t *TableStart,
Zonr Chang932648d2010-10-13 22:23:56 +0800799 uint8_t *TableEnd, uint8_t *FrameRegister) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700800 assert(false && "Exception is not allowed in our language specification");
801 return;
802 }
803
Zonr Chang932648d2010-10-13 22:23:56 +0800804 // Free the specified exception table's memory. The argument must be the
805 // return value from a call to startExceptionTable() that hasn't been
806 // deallocated yet. This is never called when the JIT is currently emitting
807 // an exception table.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700808 void deallocateExceptionTable(void *ET) {
809 assert(false && "Exception is not allowed in our language specification");
810 return;
811 }
812
Zonr Chang932648d2010-10-13 22:23:56 +0800813 // Below are the methods we create
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700814 void reset() {
815 mpGOTBase = NULL;
816 HasGOT = false;
817
818 mCurFuncMemIdx = 0;
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -0700819 mCurSGMemIdx = MaxCodeSize - 1;
820 mCurGVMemIdx = 0;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700821
822 mFunctionMap.clear();
823
824 return;
825 }
826
827 ~CodeMemoryManager() {
Loganad7e8e12010-11-22 20:43:43 +0800828 if (mpCodeMem != NULL && mpCodeMem != MAP_FAILED)
829 munmap(mpCodeMem, MaxCodeSize + MaxGlobalVarSize);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700830 return;
831 }
Zonr Chang932648d2010-10-13 22:23:56 +0800832 };
833 // End of class CodeMemoryManager
834 //////////////////////////////////////////////////////////////////////////////
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700835
Zonr Chang932648d2010-10-13 22:23:56 +0800836 // The memory manager for code emitter
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700837 llvm::OwningPtr<CodeMemoryManager> mCodeMemMgr;
Zonr Chang932648d2010-10-13 22:23:56 +0800838 CodeMemoryManager *createCodeMemoryManager() {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700839 mCodeMemMgr.reset(new CodeMemoryManager());
840 return mCodeMemMgr.get();
841 }
842
Zonr Chang932648d2010-10-13 22:23:56 +0800843 //////////////////////////////////////////////////////////////////////////////
844 // Code emitter
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700845 class CodeEmitter : public llvm::JITCodeEmitter {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700846 public:
847 typedef llvm::DenseMap<const llvm::GlobalValue*, void*> GlobalAddressMapTy;
848 typedef GlobalAddressMapTy::const_iterator global_addresses_const_iterator;
849
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -0800850 GlobalAddressMapTy mGlobalAddressMap;
851
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700852 private:
Zonr Chang932648d2010-10-13 22:23:56 +0800853 CodeMemoryManager *mpMemMgr;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700854
Zonr Chang932648d2010-10-13 22:23:56 +0800855 // The JITInfo for the target we are compiling to
856 const llvm::Target *mpTarget;
Shih-wei Liaocd61af32010-04-29 00:02:57 -0700857
Zonr Chang932648d2010-10-13 22:23:56 +0800858 llvm::TargetJITInfo *mpTJI;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700859
Zonr Chang932648d2010-10-13 22:23:56 +0800860 const llvm::TargetData *mpTD;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700861
862 class EmittedFunctionCode {
863 public:
Zonr Chang932648d2010-10-13 22:23:56 +0800864 // Beginning of the function's allocation.
865 void *FunctionBody;
866
867 // The address the function's code actually starts at.
868 void *Code;
869
870 // The size of the function code
871 int Size;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700872
873 EmittedFunctionCode() : FunctionBody(NULL), Code(NULL) { return; }
874 };
Zonr Chang932648d2010-10-13 22:23:56 +0800875 EmittedFunctionCode *mpCurEmitFunction;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700876
Zonr Chang932648d2010-10-13 22:23:56 +0800877 typedef std::map<const std::string,
878 EmittedFunctionCode*> EmittedFunctionsMapTy;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700879 EmittedFunctionsMapTy mEmittedFunctions;
880
Zonr Chang932648d2010-10-13 22:23:56 +0800881 // This vector is a mapping from MBB ID's to their address. It is filled in
882 // by the StartMachineBasicBlock callback and queried by the
883 // getMachineBasicBlockAddress callback.
884 std::vector<uintptr_t> mMBBLocations;
885
886 // The constant pool for the current function.
887 llvm::MachineConstantPool *mpConstantPool;
888
889 // A pointer to the first entry in the constant pool.
890 void *mpConstantPoolBase;
891
892 // Addresses of individual constant pool entries.
893 llvm::SmallVector<uintptr_t, 8> mConstPoolAddresses;
894
895 // The jump tables for the current function.
896 llvm::MachineJumpTableInfo *mpJumpTable;
897
898 // A pointer to the first entry in the jump table.
899 void *mpJumpTableBase;
900
901 // When outputting a function stub in the context of some other function, we
902 // save BufferBegin/BufferEnd/CurBufferPtr here.
903 uint8_t *mpSavedBufferBegin, *mpSavedBufferEnd, *mpSavedCurBufferPtr;
904
905 // These are the relocations that the function needs, as emitted.
906 std::vector<llvm::MachineRelocation> mRelocations;
907
Logan824dd0a2010-11-20 01:45:54 +0800908 std::vector<oBCCRelocEntry> mCachingRelocations;
909
Zonr Chang932648d2010-10-13 22:23:56 +0800910 // This vector is a mapping from Label ID's to their address.
911 llvm::DenseMap<llvm::MCSymbol*, uintptr_t> mLabelLocations;
912
913 // Machine module info for exception informations
914 llvm::MachineModuleInfo *mpMMI;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700915
Zonr Chang932648d2010-10-13 22:23:56 +0800916 // Replace an existing mapping for GV with a new address. This updates both
917 // maps as required. If Addr is null, the entry for the global is removed
918 // from the mappings.
919 void *UpdateGlobalMapping(const llvm::GlobalValue *GV, void *Addr) {
920 if (Addr == NULL) {
921 // Removing mapping
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700922 GlobalAddressMapTy::iterator I = mGlobalAddressMap.find(GV);
923 void *OldVal;
924
Zonr Chang932648d2010-10-13 22:23:56 +0800925 if (I == mGlobalAddressMap.end()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700926 OldVal = NULL;
Zonr Chang932648d2010-10-13 22:23:56 +0800927 } else {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700928 OldVal = I->second;
929 mGlobalAddressMap.erase(I);
930 }
931
932 return OldVal;
933 }
934
Zonr Chang932648d2010-10-13 22:23:56 +0800935 void *&CurVal = mGlobalAddressMap[GV];
936 void *OldVal = CurVal;
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700937
938 CurVal = Addr;
939
940 return OldVal;
941 }
942
Zonr Chang932648d2010-10-13 22:23:56 +0800943 // Tell the execution engine that the specified global is at the specified
944 // location. This is used internally as functions are JIT'd and as global
945 // variables are laid out in memory.
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700946 void AddGlobalMapping(const llvm::GlobalValue *GV, void *Addr) {
Zonr Chang932648d2010-10-13 22:23:56 +0800947 void *&CurVal = mGlobalAddressMap[GV];
948 assert((CurVal == 0 || Addr == 0) &&
949 "GlobalMapping already established!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700950 CurVal = Addr;
951 return;
952 }
953
Zonr Chang932648d2010-10-13 22:23:56 +0800954 // This returns the address of the specified global value if it is has
955 // already been codegen'd, otherwise it returns null.
956 void *GetPointerToGlobalIfAvailable(const llvm::GlobalValue *GV) {
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -0700957 GlobalAddressMapTy::iterator I = mGlobalAddressMap.find(GV);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700958 return ((I != mGlobalAddressMap.end()) ? I->second : NULL);
959 }
960
Zonr Chang932648d2010-10-13 22:23:56 +0800961 unsigned int GetConstantPoolSizeInBytes(llvm::MachineConstantPool *MCP) {
962 const std::vector<llvm::MachineConstantPoolEntry> &Constants =
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700963 MCP->getConstants();
964
Zonr Chang932648d2010-10-13 22:23:56 +0800965 if (Constants.empty())
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700966 return 0;
967
968 unsigned int Size = 0;
Zonr Chang932648d2010-10-13 22:23:56 +0800969 for (int i = 0, e = Constants.size(); i != e; i++) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700970 llvm::MachineConstantPoolEntry CPE = Constants[i];
971 unsigned int AlignMask = CPE.getAlignment() - 1;
972 Size = (Size + AlignMask) & ~AlignMask;
Zonr Chang932648d2010-10-13 22:23:56 +0800973 const llvm::Type *Ty = CPE.getType();
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700974 Size += mpTD->getTypeAllocSize(Ty);
975 }
976
977 return Size;
978 }
979
Zonr Chang932648d2010-10-13 22:23:56 +0800980 // This function converts a Constant* into a GenericValue. The interesting
981 // part is if C is a ConstantExpr.
982 void GetConstantValue(const llvm::Constant *C, llvm::GenericValue &Result) {
983 if (C->getValueID() == llvm::Value::UndefValueVal)
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700984 return;
Zonr Chang932648d2010-10-13 22:23:56 +0800985 else if (C->getValueID() == llvm::Value::ConstantExprVal) {
986 const llvm::ConstantExpr *CE = (llvm::ConstantExpr*) C;
987 const llvm::Constant *Op0 = CE->getOperand(0);
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700988
Zonr Chang932648d2010-10-13 22:23:56 +0800989 switch (CE->getOpcode()) {
990 case llvm::Instruction::GetElementPtr: {
991 // Compute the index
992 llvm::SmallVector<llvm::Value*, 8> Indices(CE->op_begin() + 1,
993 CE->op_end());
994 uint64_t Offset = mpTD->getIndexedOffset(Op0->getType(),
995 &Indices[0],
996 Indices.size());
Shih-wei Liao77ed6142010-04-07 12:21:42 -0700997
Zonr Chang932648d2010-10-13 22:23:56 +0800998 GetConstantValue(Op0, Result);
999 Result.PointerVal =
1000 static_cast<uint8_t*>(Result.PointerVal) + Offset;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001001
Zonr Chang932648d2010-10-13 22:23:56 +08001002 return;
1003 }
1004 case llvm::Instruction::Trunc: {
1005 uint32_t BitWidth =
1006 llvm::cast<llvm::IntegerType>(CE->getType())->getBitWidth();
1007
1008 GetConstantValue(Op0, Result);
1009 Result.IntVal = Result.IntVal.trunc(BitWidth);
1010
1011 return;
1012 }
1013 case llvm::Instruction::ZExt: {
1014 uint32_t BitWidth =
1015 llvm::cast<llvm::IntegerType>(CE->getType())->getBitWidth();
1016
1017 GetConstantValue(Op0, Result);
1018 Result.IntVal = Result.IntVal.zext(BitWidth);
1019
1020 return;
1021 }
1022 case llvm::Instruction::SExt: {
1023 uint32_t BitWidth =
1024 llvm::cast<llvm::IntegerType>(CE->getType())->getBitWidth();
1025
1026 GetConstantValue(Op0, Result);
1027 Result.IntVal = Result.IntVal.sext(BitWidth);
1028
1029 return;
1030 }
1031 case llvm::Instruction::FPTrunc: {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001032 // TODO(all): fixme: long double
Zonr Chang932648d2010-10-13 22:23:56 +08001033 GetConstantValue(Op0, Result);
1034 Result.FloatVal = static_cast<float>(Result.DoubleVal);
1035 return;
1036 }
1037 case llvm::Instruction::FPExt: {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001038 // TODO(all): fixme: long double
Zonr Chang932648d2010-10-13 22:23:56 +08001039 GetConstantValue(Op0, Result);
1040 Result.DoubleVal = static_cast<double>(Result.FloatVal);
1041 return;
1042 }
1043 case llvm::Instruction::UIToFP: {
1044 GetConstantValue(Op0, Result);
1045 if (CE->getType()->isFloatTy())
1046 Result.FloatVal =
1047 static_cast<float>(Result.IntVal.roundToDouble());
1048 else if (CE->getType()->isDoubleTy())
1049 Result.DoubleVal = Result.IntVal.roundToDouble();
1050 else if (CE->getType()->isX86_FP80Ty()) {
1051 const uint64_t zero[] = { 0, 0 };
1052 llvm::APFloat apf(llvm::APInt(80, 2, zero));
1053 apf.convertFromAPInt(Result.IntVal,
1054 false,
1055 llvm::APFloat::rmNearestTiesToEven);
1056 Result.IntVal = apf.bitcastToAPInt();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001057 }
Zonr Chang932648d2010-10-13 22:23:56 +08001058 return;
1059 }
1060 case llvm::Instruction::SIToFP: {
1061 GetConstantValue(Op0, Result);
1062 if (CE->getType()->isFloatTy())
1063 Result.FloatVal =
1064 static_cast<float>(Result.IntVal.signedRoundToDouble());
1065 else if (CE->getType()->isDoubleTy())
1066 Result.DoubleVal = Result.IntVal.signedRoundToDouble();
1067 else if (CE->getType()->isX86_FP80Ty()) {
1068 const uint64_t zero[] = { 0, 0 };
1069 llvm::APFloat apf = llvm::APFloat(llvm::APInt(80, 2, zero));
1070 apf.convertFromAPInt(Result.IntVal,
1071 true,
1072 llvm::APFloat::rmNearestTiesToEven);
1073 Result.IntVal = apf.bitcastToAPInt();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001074 }
Zonr Chang932648d2010-10-13 22:23:56 +08001075 return;
1076 }
1077 // double->APInt conversion handles sign
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001078 case llvm::Instruction::FPToUI:
Zonr Chang932648d2010-10-13 22:23:56 +08001079 case llvm::Instruction::FPToSI: {
1080 uint32_t BitWidth =
1081 llvm::cast<llvm::IntegerType>(CE->getType())->getBitWidth();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001082
Zonr Chang932648d2010-10-13 22:23:56 +08001083 GetConstantValue(Op0, Result);
1084 if (Op0->getType()->isFloatTy())
1085 Result.IntVal =
1086 llvm::APIntOps::RoundFloatToAPInt(Result.FloatVal, BitWidth);
1087 else if (Op0->getType()->isDoubleTy())
1088 Result.IntVal =
1089 llvm::APIntOps::RoundDoubleToAPInt(Result.DoubleVal,
1090 BitWidth);
1091 else if (Op0->getType()->isX86_FP80Ty()) {
1092 llvm::APFloat apf = llvm::APFloat(Result.IntVal);
1093 uint64_t V;
1094 bool Ignored;
1095 apf.convertToInteger(&V,
1096 BitWidth,
1097 CE->getOpcode() == llvm::Instruction::FPToSI,
1098 llvm::APFloat::rmTowardZero,
1099 &Ignored);
1100 Result.IntVal = V; // endian?
1101 }
1102 return;
1103 }
1104 case llvm::Instruction::PtrToInt: {
1105 uint32_t PtrWidth = mpTD->getPointerSizeInBits();
1106
1107 GetConstantValue(Op0, Result);
1108 Result.IntVal = llvm::APInt(PtrWidth, uintptr_t
1109 (Result.PointerVal));
1110
1111 return;
1112 }
1113 case llvm::Instruction::IntToPtr: {
1114 uint32_t PtrWidth = mpTD->getPointerSizeInBits();
1115
1116 GetConstantValue(Op0, Result);
1117 if (PtrWidth != Result.IntVal.getBitWidth())
1118 Result.IntVal = Result.IntVal.zextOrTrunc(PtrWidth);
1119 assert(Result.IntVal.getBitWidth() <= 64 && "Bad pointer width");
1120
1121 Result.PointerVal =
1122 llvm::PointerTy(
1123 static_cast<uintptr_t>(Result.IntVal.getZExtValue()));
1124
1125 return;
1126 }
1127 case llvm::Instruction::BitCast: {
1128 GetConstantValue(Op0, Result);
1129 const llvm::Type *DestTy = CE->getType();
1130
1131 switch (Op0->getType()->getTypeID()) {
1132 case llvm::Type::IntegerTyID: {
1133 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
1134 if (DestTy->isFloatTy())
1135 Result.FloatVal = Result.IntVal.bitsToFloat();
1136 else if (DestTy->isDoubleTy())
1137 Result.DoubleVal = Result.IntVal.bitsToDouble();
1138 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001139 }
Zonr Chang932648d2010-10-13 22:23:56 +08001140 case llvm::Type::FloatTyID: {
1141 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
1142 Result.IntVal.floatToBits(Result.FloatVal);
1143 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001144 }
Zonr Chang932648d2010-10-13 22:23:56 +08001145 case llvm::Type::DoubleTyID: {
1146 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
1147 Result.IntVal.doubleToBits(Result.DoubleVal);
1148 break;
1149 }
1150 case llvm::Type::PointerTyID: {
1151 assert(DestTy->isPointerTy() && "Invalid bitcast");
1152 break; // getConstantValue(Op0) above already converted it
1153 }
1154 default: {
1155 llvm_unreachable("Invalid bitcast operand");
1156 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001157 }
Zonr Chang932648d2010-10-13 22:23:56 +08001158 return;
1159 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001160 case llvm::Instruction::Add:
1161 case llvm::Instruction::FAdd:
1162 case llvm::Instruction::Sub:
1163 case llvm::Instruction::FSub:
1164 case llvm::Instruction::Mul:
1165 case llvm::Instruction::FMul:
1166 case llvm::Instruction::UDiv:
1167 case llvm::Instruction::SDiv:
1168 case llvm::Instruction::URem:
1169 case llvm::Instruction::SRem:
1170 case llvm::Instruction::And:
1171 case llvm::Instruction::Or:
Zonr Chang932648d2010-10-13 22:23:56 +08001172 case llvm::Instruction::Xor: {
1173 llvm::GenericValue LHS, RHS;
1174 GetConstantValue(Op0, LHS);
1175 GetConstantValue(CE->getOperand(1), RHS);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001176
Zonr Chang932648d2010-10-13 22:23:56 +08001177 switch (Op0->getType()->getTypeID()) {
1178 case llvm::Type::IntegerTyID: {
1179 switch (CE->getOpcode()) {
1180 case llvm::Instruction::Add: {
1181 Result.IntVal = LHS.IntVal + RHS.IntVal;
1182 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001183 }
Zonr Chang932648d2010-10-13 22:23:56 +08001184 case llvm::Instruction::Sub: {
1185 Result.IntVal = LHS.IntVal - RHS.IntVal;
1186 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001187 }
Zonr Chang932648d2010-10-13 22:23:56 +08001188 case llvm::Instruction::Mul: {
1189 Result.IntVal = LHS.IntVal * RHS.IntVal;
1190 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001191 }
Zonr Chang932648d2010-10-13 22:23:56 +08001192 case llvm::Instruction::UDiv: {
1193 Result.IntVal = LHS.IntVal.udiv(RHS.IntVal);
1194 break;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001195 }
Zonr Chang932648d2010-10-13 22:23:56 +08001196 case llvm::Instruction::SDiv: {
1197 Result.IntVal = LHS.IntVal.sdiv(RHS.IntVal);
1198 break;
1199 }
1200 case llvm::Instruction::URem: {
1201 Result.IntVal = LHS.IntVal.urem(RHS.IntVal);
1202 break;
1203 }
1204 case llvm::Instruction::SRem: {
1205 Result.IntVal = LHS.IntVal.srem(RHS.IntVal);
1206 break;
1207 }
1208 case llvm::Instruction::And: {
1209 Result.IntVal = LHS.IntVal & RHS.IntVal;
1210 break;
1211 }
1212 case llvm::Instruction::Or: {
1213 Result.IntVal = LHS.IntVal | RHS.IntVal;
1214 break;
1215 }
1216 case llvm::Instruction::Xor: {
1217 Result.IntVal = LHS.IntVal ^ RHS.IntVal;
1218 break;
1219 }
1220 default: {
1221 llvm_unreachable("Invalid integer opcode");
1222 }
1223 }
1224 break;
1225 }
1226 case llvm::Type::FloatTyID: {
1227 switch (CE->getOpcode()) {
1228 case llvm::Instruction::FAdd: {
1229 Result.FloatVal = LHS.FloatVal + RHS.FloatVal;
1230 break;
1231 }
1232 case llvm::Instruction::FSub: {
1233 Result.FloatVal = LHS.FloatVal - RHS.FloatVal;
1234 break;
1235 }
1236 case llvm::Instruction::FMul: {
1237 Result.FloatVal = LHS.FloatVal * RHS.FloatVal;
1238 break;
1239 }
1240 case llvm::Instruction::FDiv: {
1241 Result.FloatVal = LHS.FloatVal / RHS.FloatVal;
1242 break;
1243 }
1244 case llvm::Instruction::FRem: {
1245 Result.FloatVal = ::fmodf(LHS.FloatVal, RHS.FloatVal);
1246 break;
1247 }
1248 default: {
1249 llvm_unreachable("Invalid float opcode");
1250 }
1251 }
1252 break;
1253 }
1254 case llvm::Type::DoubleTyID: {
1255 switch (CE->getOpcode()) {
1256 case llvm::Instruction::FAdd: {
1257 Result.DoubleVal = LHS.DoubleVal + RHS.DoubleVal;
1258 break;
1259 }
1260 case llvm::Instruction::FSub: {
1261 Result.DoubleVal = LHS.DoubleVal - RHS.DoubleVal;
1262 break;
1263 }
1264 case llvm::Instruction::FMul: {
1265 Result.DoubleVal = LHS.DoubleVal * RHS.DoubleVal;
1266 break;
1267 }
1268 case llvm::Instruction::FDiv: {
1269 Result.DoubleVal = LHS.DoubleVal / RHS.DoubleVal;
1270 break;
1271 }
1272 case llvm::Instruction::FRem: {
1273 Result.DoubleVal = ::fmod(LHS.DoubleVal, RHS.DoubleVal);
1274 break;
1275 }
1276 default: {
1277 llvm_unreachable("Invalid double opcode");
1278 }
1279 }
1280 break;
1281 }
1282 case llvm::Type::X86_FP80TyID:
1283 case llvm::Type::PPC_FP128TyID:
1284 case llvm::Type::FP128TyID: {
1285 llvm::APFloat apfLHS = llvm::APFloat(LHS.IntVal);
1286 switch (CE->getOpcode()) {
1287 case llvm::Instruction::FAdd: {
1288 apfLHS.add(llvm::APFloat(RHS.IntVal),
1289 llvm::APFloat::rmNearestTiesToEven);
1290 break;
1291 }
1292 case llvm::Instruction::FSub: {
1293 apfLHS.subtract(llvm::APFloat(RHS.IntVal),
1294 llvm::APFloat::rmNearestTiesToEven);
1295 break;
1296 }
1297 case llvm::Instruction::FMul: {
1298 apfLHS.multiply(llvm::APFloat(RHS.IntVal),
1299 llvm::APFloat::rmNearestTiesToEven);
1300 break;
1301 }
1302 case llvm::Instruction::FDiv: {
1303 apfLHS.divide(llvm::APFloat(RHS.IntVal),
1304 llvm::APFloat::rmNearestTiesToEven);
1305 break;
1306 }
1307 case llvm::Instruction::FRem: {
1308 apfLHS.mod(llvm::APFloat(RHS.IntVal),
1309 llvm::APFloat::rmNearestTiesToEven);
1310 break;
1311 }
1312 default: {
1313 llvm_unreachable("Invalid long double opcode");
1314 }
1315 }
1316 Result.IntVal = apfLHS.bitcastToAPInt();
1317 break;
1318 }
1319 default: {
1320 llvm_unreachable("Bad add type!");
1321 }
1322 } // End switch (Op0->getType()->getTypeID())
1323 return;
1324 }
1325 default: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001326 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001327 }
1328 } // End switch (CE->getOpcode())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001329
1330 std::string msg;
1331 llvm::raw_string_ostream Msg(msg);
1332 Msg << "ConstantExpr not handled: " << *CE;
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001333 llvm::report_fatal_error(Msg.str());
Zonr Chang932648d2010-10-13 22:23:56 +08001334 } // C->getValueID() == llvm::Value::ConstantExprVal
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001335
1336 switch (C->getType()->getTypeID()) {
Zonr Chang932648d2010-10-13 22:23:56 +08001337 case llvm::Type::FloatTyID: {
1338 Result.FloatVal =
1339 llvm::cast<llvm::ConstantFP>(C)->getValueAPF().convertToFloat();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001340 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001341 }
1342 case llvm::Type::DoubleTyID: {
1343 Result.DoubleVal =
1344 llvm::cast<llvm::ConstantFP>(C)->getValueAPF().convertToDouble();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001345 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001346 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001347 case llvm::Type::X86_FP80TyID:
1348 case llvm::Type::FP128TyID:
Zonr Chang932648d2010-10-13 22:23:56 +08001349 case llvm::Type::PPC_FP128TyID: {
1350 Result.IntVal =
1351 llvm::cast<llvm::ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001352 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001353 }
1354 case llvm::Type::IntegerTyID: {
1355 Result.IntVal =
1356 llvm::cast<llvm::ConstantInt>(C)->getValue();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001357 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001358 }
1359 case llvm::Type::PointerTyID: {
1360 switch (C->getValueID()) {
1361 case llvm::Value::ConstantPointerNullVal: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001362 Result.PointerVal = NULL;
1363 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001364 }
1365 case llvm::Value::FunctionVal: {
1366 const llvm::Function *F = static_cast<const llvm::Function*>(C);
1367 Result.PointerVal =
1368 GetPointerToFunctionOrStub(const_cast<llvm::Function*>(F));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001369 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001370 }
1371 case llvm::Value::GlobalVariableVal: {
1372 const llvm::GlobalVariable *GV =
1373 static_cast<const llvm::GlobalVariable*>(C);
1374 Result.PointerVal =
1375 GetOrEmitGlobalVariable(const_cast<llvm::GlobalVariable*>(GV));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001376 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001377 }
1378 case llvm::Value::BlockAddressVal: {
1379 assert(false && "JIT does not support address-of-label yet!");
1380 }
1381 default: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001382 llvm_unreachable("Unknown constant pointer type!");
Zonr Chang932648d2010-10-13 22:23:56 +08001383 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001384 }
1385 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001386 }
1387 default: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001388 std::string msg;
1389 llvm::raw_string_ostream Msg(msg);
1390 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001391 llvm::report_fatal_error(Msg.str());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001392 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001393 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001394 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001395 return;
1396 }
1397
Zonr Chang932648d2010-10-13 22:23:56 +08001398 // Stores the data in @Val of type @Ty at address @Addr.
1399 void StoreValueToMemory(const llvm::GenericValue &Val, void *Addr,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001400 const llvm::Type *Ty) {
1401 const unsigned int StoreBytes = mpTD->getTypeStoreSize(Ty);
1402
Zonr Chang932648d2010-10-13 22:23:56 +08001403 switch (Ty->getTypeID()) {
1404 case llvm::Type::IntegerTyID: {
1405 const llvm::APInt &IntVal = Val.IntVal;
1406 assert(((IntVal.getBitWidth() + 7) / 8 >= StoreBytes) &&
1407 "Integer too small!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001408
Zonr Chang932648d2010-10-13 22:23:56 +08001409 const uint8_t *Src =
1410 reinterpret_cast<const uint8_t*>(IntVal.getRawData());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001411
Zonr Chang932648d2010-10-13 22:23:56 +08001412 if (llvm::sys::isLittleEndianHost()) {
1413 // Little-endian host - the source is ordered from LSB to MSB.
1414 // Order the destination from LSB to MSB: Do a straight copy.
1415 memcpy(Addr, Src, StoreBytes);
1416 } else {
1417 // Big-endian host - the source is an array of 64 bit words
1418 // ordered from LSW to MSW.
1419 //
1420 // Each word is ordered from MSB to LSB.
1421 //
1422 // Order the destination from MSB to LSB:
1423 // Reverse the word order, but not the bytes in a word.
1424 unsigned int i = StoreBytes;
1425 while (i > sizeof(uint64_t)) {
1426 i -= sizeof(uint64_t);
1427 ::memcpy(reinterpret_cast<uint8_t*>(Addr) + i,
1428 Src,
1429 sizeof(uint64_t));
1430 Src += sizeof(uint64_t);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001431 }
Zonr Chang932648d2010-10-13 22:23:56 +08001432 ::memcpy(Addr, Src + sizeof(uint64_t) - i, i);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001433 }
1434 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001435 }
1436 case llvm::Type::FloatTyID: {
1437 *reinterpret_cast<float*>(Addr) = Val.FloatVal;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001438 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001439 }
1440 case llvm::Type::DoubleTyID: {
1441 *reinterpret_cast<double*>(Addr) = Val.DoubleVal;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001442 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001443 }
1444 case llvm::Type::X86_FP80TyID: {
1445 memcpy(Addr, Val.IntVal.getRawData(), 10);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001446 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001447 }
1448 case llvm::Type::PointerTyID: {
1449 // Ensure 64 bit target pointers are fully initialized on 32 bit
1450 // hosts.
1451 if (StoreBytes != sizeof(llvm::PointerTy))
1452 memset(Addr, 0, StoreBytes);
1453 *((llvm::PointerTy*) Addr) = Val.PointerVal;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001454 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001455 }
1456 default: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001457 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001458 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001459 }
1460
Zonr Chang932648d2010-10-13 22:23:56 +08001461 if (llvm::sys::isLittleEndianHost() != mpTD->isLittleEndian())
1462 std::reverse(reinterpret_cast<uint8_t*>(Addr),
1463 reinterpret_cast<uint8_t*>(Addr) + StoreBytes);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001464
1465 return;
1466 }
1467
Zonr Chang932648d2010-10-13 22:23:56 +08001468 // Recursive function to apply a @Constant value into the specified memory
1469 // location @Addr.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001470 void InitializeConstantToMemory(const llvm::Constant *C, void *Addr) {
Zonr Chang932648d2010-10-13 22:23:56 +08001471 switch (C->getValueID()) {
1472 case llvm::Value::UndefValueVal: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001473 // Nothing to do
1474 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001475 }
1476 case llvm::Value::ConstantVectorVal: {
1477 // dynamic cast may hurt performance
1478 const llvm::ConstantVector *CP = (llvm::ConstantVector*) C;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001479
Zonr Chang932648d2010-10-13 22:23:56 +08001480 unsigned int ElementSize = mpTD->getTypeAllocSize
1481 (CP->getType()->getElementType());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001482
Zonr Chang932648d2010-10-13 22:23:56 +08001483 for (int i = 0, e = CP->getNumOperands(); i != e;i++)
1484 InitializeConstantToMemory(
1485 CP->getOperand(i),
1486 reinterpret_cast<uint8_t*>(Addr) + i * ElementSize);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001487 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001488 }
1489 case llvm::Value::ConstantAggregateZeroVal: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001490 memset(Addr, 0, (size_t) mpTD->getTypeAllocSize(C->getType()));
1491 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001492 }
1493 case llvm::Value::ConstantArrayVal: {
1494 const llvm::ConstantArray *CPA = (llvm::ConstantArray*) C;
1495 unsigned int ElementSize = mpTD->getTypeAllocSize
1496 (CPA->getType()->getElementType());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001497
Zonr Chang932648d2010-10-13 22:23:56 +08001498 for (int i = 0, e = CPA->getNumOperands(); i != e; i++)
1499 InitializeConstantToMemory(
1500 CPA->getOperand(i),
1501 reinterpret_cast<uint8_t*>(Addr) + i * ElementSize);
1502 break;
1503 }
1504 case llvm::Value::ConstantStructVal: {
1505 const llvm::ConstantStruct *CPS =
1506 static_cast<const llvm::ConstantStruct*>(C);
1507 const llvm::StructLayout *SL = mpTD->getStructLayout
1508 (llvm::cast<llvm::StructType>(CPS->getType()));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001509
Zonr Chang932648d2010-10-13 22:23:56 +08001510 for (int i = 0, e = CPS->getNumOperands(); i != e; i++)
1511 InitializeConstantToMemory(
1512 CPS->getOperand(i),
1513 reinterpret_cast<uint8_t*>(Addr) + SL->getElementOffset(i));
1514 break;
1515 }
1516 default: {
1517 if (C->getType()->isFirstClassType()) {
1518 llvm::GenericValue Val;
1519 GetConstantValue(C, Val);
1520 StoreValueToMemory(Val, Addr, C->getType());
1521 } else {
1522 llvm_unreachable("Unknown constant type to initialize memory "
1523 "with!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001524 }
1525 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001526 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001527 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001528 return;
1529 }
1530
1531 void emitConstantPool(llvm::MachineConstantPool *MCP) {
Zonr Chang932648d2010-10-13 22:23:56 +08001532 if (mpTJI->hasCustomConstantPool())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001533 return;
1534
Zonr Chang932648d2010-10-13 22:23:56 +08001535 // Constant pool address resolution is handled by the target itself in ARM
1536 // (TargetJITInfo::hasCustomConstantPool() returns true).
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001537#if !defined(PROVIDE_ARM_CODEGEN)
Zonr Chang932648d2010-10-13 22:23:56 +08001538 const std::vector<llvm::MachineConstantPoolEntry> &Constants =
1539 MCP->getConstants();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001540
Zonr Chang932648d2010-10-13 22:23:56 +08001541 if (Constants.empty())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001542 return;
1543
1544 unsigned Size = GetConstantPoolSizeInBytes(MCP);
1545 unsigned Align = MCP->getConstantPoolAlignment();
1546
1547 mpConstantPoolBase = allocateSpace(Size, Align);
1548 mpConstantPool = MCP;
1549
Zonr Chang932648d2010-10-13 22:23:56 +08001550 if (mpConstantPoolBase == NULL)
1551 return; // out of memory
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001552
1553 unsigned Offset = 0;
Zonr Chang932648d2010-10-13 22:23:56 +08001554 for (int i = 0, e = Constants.size(); i != e; i++) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001555 llvm::MachineConstantPoolEntry CPE = Constants[i];
1556 unsigned AlignMask = CPE.getAlignment() - 1;
1557 Offset = (Offset + AlignMask) & ~AlignMask;
1558
1559 uintptr_t CAddr = (uintptr_t) mpConstantPoolBase + Offset;
1560 mConstPoolAddresses.push_back(CAddr);
1561
Zonr Chang932648d2010-10-13 22:23:56 +08001562 if (CPE.isMachineConstantPoolEntry())
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001563 llvm::report_fatal_error
Zonr Chang932648d2010-10-13 22:23:56 +08001564 ("Initialize memory with machine specific constant pool"
1565 " entry has not been implemented!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001566
1567 InitializeConstantToMemory(CPE.Val.ConstVal, (void*) CAddr);
1568
1569 const llvm::Type *Ty = CPE.Val.ConstVal->getType();
1570 Offset += mpTD->getTypeAllocSize(Ty);
1571 }
1572#endif
1573 return;
1574 }
1575
1576 void initJumpTableInfo(llvm::MachineJumpTableInfo *MJTI) {
Zonr Chang932648d2010-10-13 22:23:56 +08001577 if (mpTJI->hasCustomJumpTables())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001578 return;
1579
Zonr Chang932648d2010-10-13 22:23:56 +08001580 const std::vector<llvm::MachineJumpTableEntry> &JT =
1581 MJTI->getJumpTables();
1582 if (JT.empty())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001583 return;
1584
1585 unsigned NumEntries = 0;
Zonr Chang932648d2010-10-13 22:23:56 +08001586 for (int i = 0, e = JT.size(); i != e; i++)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001587 NumEntries += JT[i].MBBs.size();
1588
1589 unsigned EntrySize = MJTI->getEntrySize(*mpTD);
1590
Zonr Chang932648d2010-10-13 22:23:56 +08001591 mpJumpTable = MJTI;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001592 mpJumpTableBase = allocateSpace(NumEntries * EntrySize,
Zonr Chang932648d2010-10-13 22:23:56 +08001593 MJTI->getEntryAlignment(*mpTD));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001594
1595 return;
1596 }
1597
1598 void emitJumpTableInfo(llvm::MachineJumpTableInfo *MJTI) {
Zonr Chang932648d2010-10-13 22:23:56 +08001599 if (mpTJI->hasCustomJumpTables())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001600 return;
1601
Zonr Chang932648d2010-10-13 22:23:56 +08001602 const std::vector<llvm::MachineJumpTableEntry> &JT =
1603 MJTI->getJumpTables();
1604 if (JT.empty() || mpJumpTableBase == 0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001605 return;
1606
Zonr Chang932648d2010-10-13 22:23:56 +08001607 assert(llvm::TargetMachine::getRelocationModel() == llvm::Reloc::Static &&
1608 (MJTI->getEntrySize(*mpTD) == sizeof(mpTD /* a pointer type */)) &&
1609 "Cross JIT'ing?");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001610
Zonr Chang932648d2010-10-13 22:23:56 +08001611 // For each jump table, map each target in the jump table to the
1612 // address of an emitted MachineBasicBlock.
1613 intptr_t *SlotPtr = reinterpret_cast<intptr_t*>(mpJumpTableBase);
1614 for (int i = 0, ie = JT.size(); i != ie; i++) {
1615 const std::vector<llvm::MachineBasicBlock*> &MBBs = JT[i].MBBs;
1616 // Store the address of the basic block for this jump table slot in the
1617 // memory we allocated for the jump table in 'initJumpTableInfo'
1618 for (int j = 0, je = MBBs.size(); j != je; j++)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001619 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[j]);
1620 }
1621 }
1622
Zonr Chang932648d2010-10-13 22:23:56 +08001623 void *GetPointerToGlobal(llvm::GlobalValue *V, void *Reference,
1624 bool MayNeedFarStub) {
1625 switch (V->getValueID()) {
1626 case llvm::Value::FunctionVal: {
1627 llvm::Function *F = (llvm::Function*) V;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001628
Zonr Chang932648d2010-10-13 22:23:56 +08001629 // If we have code, go ahead and return that.
1630 if (void *ResultPtr = GetPointerToGlobalIfAvailable(F))
1631 return ResultPtr;
Shih-wei Liao800e9c22010-04-18 16:08:16 -07001632
Zonr Chang932648d2010-10-13 22:23:56 +08001633 if (void *FnStub = GetLazyFunctionStubIfAvailable(F))
1634 // Return the function stub if it's already created.
1635 // We do this first so that:
1636 // we're returning the same address for the function as any
1637 // previous call.
1638 //
1639 // TODO(llvm.org): Yes, this is wrong. The lazy stub isn't
1640 // guaranteed to be close enough to call.
1641 return FnStub;
Shih-wei Liao800e9c22010-04-18 16:08:16 -07001642
Zonr Chang932648d2010-10-13 22:23:56 +08001643 // If we know the target can handle arbitrary-distance calls, try to
1644 // return a direct pointer.
1645 if (!MayNeedFarStub) {
1646 //
1647 // x86_64 architecture may encounter the bug:
1648 // http://llvm.org/bugs/show_bug.cgi?id=5201
1649 // which generate instruction "call" instead of "callq".
1650 //
1651 // And once the real address of stub is greater than 64-bit
1652 // long, the replacement will truncate to 32-bit resulting a
1653 // serious problem.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001654#if !defined(__x86_64__)
Zonr Chang932648d2010-10-13 22:23:56 +08001655 // If this is an external function pointer, we can force the JIT
1656 // to 'compile' it, which really just adds it to the map.
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001657 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
1658 return GetPointerToFunction(F, /* AbortOnFailure = */false);
1659 // Changing to false because wanting to allow later calls to
1660 // mpTJI->relocate() without aborting. For caching purpose
1661 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001662#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001663 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001664
Zonr Chang932648d2010-10-13 22:23:56 +08001665 // Otherwise, we may need a to emit a stub, and, conservatively, we
1666 // always do so.
1667 return GetLazyFunctionStub(F);
1668 break;
1669 }
1670 case llvm::Value::GlobalVariableVal: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001671 return GetOrEmitGlobalVariable((llvm::GlobalVariable*) V);
1672 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001673 }
1674 case llvm::Value::GlobalAliasVal: {
1675 llvm::GlobalAlias *GA = (llvm::GlobalAlias*) V;
1676 const llvm::GlobalValue *GV = GA->resolveAliasedGlobal(false);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001677
Zonr Chang932648d2010-10-13 22:23:56 +08001678 switch (GV->getValueID()) {
1679 case llvm::Value::FunctionVal: {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001680 // TODO(all): is there's any possibility that the function is not
Zonr Chang932648d2010-10-13 22:23:56 +08001681 // code-gen'd?
1682 return GetPointerToFunction(
1683 static_cast<const llvm::Function*>(GV),
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001684 /* AbortOnFailure = */false);
1685 // Changing to false because wanting to allow later calls to
1686 // mpTJI->relocate() without aborting. For caching purpose
Zonr Chang932648d2010-10-13 22:23:56 +08001687 break;
1688 }
1689 case llvm::Value::GlobalVariableVal: {
1690 if (void *P = mGlobalAddressMap[GV])
1691 return P;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001692
Zonr Chang932648d2010-10-13 22:23:56 +08001693 llvm::GlobalVariable *GVar = (llvm::GlobalVariable*) GV;
1694 EmitGlobalVariable(GVar);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001695
Zonr Chang932648d2010-10-13 22:23:56 +08001696 return mGlobalAddressMap[GV];
1697 break;
1698 }
1699 case llvm::Value::GlobalAliasVal: {
1700 assert(false && "Alias should be resolved ultimately!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001701 }
1702 }
1703 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001704 }
1705 default: {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001706 break;
Zonr Chang932648d2010-10-13 22:23:56 +08001707 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001708 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001709 llvm_unreachable("Unknown type of global value!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001710 }
1711
Zonr Chang932648d2010-10-13 22:23:56 +08001712 // If the specified function has been code-gen'd, return a pointer to the
1713 // function. If not, compile it, or use a stub to implement lazy compilation
1714 // if available.
1715 void *GetPointerToFunctionOrStub(llvm::Function *F) {
1716 // If we have already code generated the function, just return the
1717 // address.
1718 if (void *Addr = GetPointerToGlobalIfAvailable(F))
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001719 return Addr;
1720
Zonr Chang932648d2010-10-13 22:23:56 +08001721 // Get a stub if the target supports it.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001722 return GetLazyFunctionStub(F);
1723 }
1724
Zonr Chang932648d2010-10-13 22:23:56 +08001725 typedef llvm::DenseMap<const llvm::Function*,
1726 void*> FunctionToLazyStubMapTy;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001727 FunctionToLazyStubMapTy mFunctionToLazyStubMap;
1728
Zonr Chang932648d2010-10-13 22:23:56 +08001729 void *GetLazyFunctionStubIfAvailable(llvm::Function *F) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001730 return mFunctionToLazyStubMap.lookup(F);
1731 }
1732
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001733 std::set<const llvm::Function*> PendingFunctions;
Zonr Chang932648d2010-10-13 22:23:56 +08001734 void *GetLazyFunctionStub(llvm::Function *F) {
1735 // If we already have a lazy stub for this function, recycle it.
1736 void *&Stub = mFunctionToLazyStubMap[F];
1737 if (Stub)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001738 return Stub;
1739
Zonr Chang932648d2010-10-13 22:23:56 +08001740 // In any cases, we should NOT resolve function at runtime (though we are
1741 // able to). We resolve this right now.
1742 void *Actual = NULL;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08001743 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
1744 Actual = GetPointerToFunction(F, /* AbortOnFailure = */false);
1745 // Changing to false because wanting to allow later calls to
1746 // mpTJI->relocate() without aborting. For caching purpose
1747 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001748
Zonr Chang932648d2010-10-13 22:23:56 +08001749 // Codegen a new stub, calling the actual address of the external
1750 // function, if it was resolved.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001751 llvm::TargetJITInfo::StubLayout SL = mpTJI->getStubLayout();
1752 startGVStub(F, SL.Size, SL.Alignment);
1753 Stub = mpTJI->emitFunctionStub(F, Actual, *this);
1754 finishGVStub();
1755
Zonr Chang932648d2010-10-13 22:23:56 +08001756 // We really want the address of the stub in the GlobalAddressMap for the
1757 // JIT, not the address of the external function.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001758 UpdateGlobalMapping(F, Stub);
1759
Zonr Chang932648d2010-10-13 22:23:56 +08001760 if (!Actual)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001761 PendingFunctions.insert(F);
1762 else
Zonr Chang932648d2010-10-13 22:23:56 +08001763 Disassemble(F->getName(), reinterpret_cast<uint8_t*>(Stub),
1764 SL.Size, true);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001765
1766 return Stub;
1767 }
1768
Zonr Chang932648d2010-10-13 22:23:56 +08001769 void *GetPointerToFunction(const llvm::Function *F, bool AbortOnFailure) {
1770 void *Addr = GetPointerToGlobalIfAvailable(F);
1771 if (Addr)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001772 return Addr;
1773
1774 assert((F->isDeclaration() || F->hasAvailableExternallyLinkage()) &&
1775 "Internal error: only external defined function routes here!");
1776
Zonr Chang932648d2010-10-13 22:23:56 +08001777 // Handle the failure resolution by ourselves.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001778 Addr = GetPointerToNamedSymbol(F->getName().str().c_str(),
Zonr Chang932648d2010-10-13 22:23:56 +08001779 /* AbortOnFailure = */ false);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001780
Zonr Chang932648d2010-10-13 22:23:56 +08001781 // If we resolved the symbol to a null address (eg. a weak external)
1782 // return a null pointer let the application handle it.
1783 if (Addr == NULL) {
1784 if (AbortOnFailure)
1785 llvm::report_fatal_error("Could not resolve external function "
1786 "address: " + F->getName());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001787 else
1788 return NULL;
Zonr Chang932648d2010-10-13 22:23:56 +08001789 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001790
1791 AddGlobalMapping(F, Addr);
1792
1793 return Addr;
1794 }
1795
Zonr Chang932648d2010-10-13 22:23:56 +08001796 void *GetPointerToNamedSymbol(const std::string &Name,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001797 bool AbortOnFailure) {
Zonr Chang932648d2010-10-13 22:23:56 +08001798 if (void *Addr = FindRuntimeFunction(Name.c_str()))
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001799 return Addr;
1800
Zonr Chang932648d2010-10-13 22:23:56 +08001801 if (mpSymbolLookupFn)
1802 if (void *Addr = mpSymbolLookupFn(mpSymbolLookupContext, Name.c_str()))
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001803 return Addr;
1804
Zonr Chang932648d2010-10-13 22:23:56 +08001805 if (AbortOnFailure)
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001806 llvm::report_fatal_error("Program used external symbol '" + Name +
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001807 "' which could not be resolved!");
1808
1809 return NULL;
1810 }
1811
Zonr Chang932648d2010-10-13 22:23:56 +08001812 // Return the address of the specified global variable, possibly emitting it
1813 // to memory if needed. This is used by the Emitter.
1814 void *GetOrEmitGlobalVariable(const llvm::GlobalVariable *GV) {
1815 void *Ptr = GetPointerToGlobalIfAvailable(GV);
1816 if (Ptr)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001817 return Ptr;
1818
Zonr Chang932648d2010-10-13 22:23:56 +08001819 if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
1820 // If the global is external, just remember the address.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001821 Ptr = GetPointerToNamedSymbol(GV->getName().str(), true);
1822 AddGlobalMapping(GV, Ptr);
1823 } else {
Zonr Chang932648d2010-10-13 22:23:56 +08001824 // If the global hasn't been emitted to memory yet, allocate space and
1825 // emit it into memory.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001826 Ptr = GetMemoryForGV(GV);
1827 AddGlobalMapping(GV, Ptr);
1828 EmitGlobalVariable(GV);
1829 }
1830
1831 return Ptr;
1832 }
1833
Zonr Chang932648d2010-10-13 22:23:56 +08001834 // This method abstracts memory allocation of global variable so that the
1835 // JIT can allocate thread local variables depending on the target.
1836 void *GetMemoryForGV(const llvm::GlobalVariable *GV) {
1837 void *Ptr;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001838
Zonr Chang932648d2010-10-13 22:23:56 +08001839 const llvm::Type *GlobalType = GV->getType()->getElementType();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001840 size_t S = mpTD->getTypeAllocSize(GlobalType);
1841 size_t A = mpTD->getPreferredAlignment(GV);
1842
Zonr Chang932648d2010-10-13 22:23:56 +08001843 if (GV->isThreadLocal()) {
1844 // We can support TLS by
1845 //
1846 // Ptr = TJI.allocateThreadLocalMemory(S);
1847 //
1848 // But I tend not to.
1849 // (should we disable this in the front-end (i.e., slang)?).
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001850 llvm::report_fatal_error
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001851 ("Compilation of Thread Local Storage (TLS) is disabled!");
1852
Zonr Chang932648d2010-10-13 22:23:56 +08001853 } else if (mpTJI->allocateSeparateGVMemory()) {
1854 if (A <= 8) {
1855 Ptr = malloc(S);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001856 } else {
Zonr Chang932648d2010-10-13 22:23:56 +08001857 // Allocate (S + A) bytes of memory, then use an aligned pointer
1858 // within that space.
1859 Ptr = malloc(S + A);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001860 unsigned int MisAligned = ((intptr_t) Ptr & (A - 1));
Zonr Chang932648d2010-10-13 22:23:56 +08001861 Ptr = reinterpret_cast<uint8_t*>(Ptr) +
1862 (MisAligned ? (A - MisAligned) : 0);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001863 }
1864 } else {
Zonr Chang932648d2010-10-13 22:23:56 +08001865 Ptr = allocateGlobal(S, A);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001866 }
1867
1868 return Ptr;
1869 }
1870
1871 void EmitGlobalVariable(const llvm::GlobalVariable *GV) {
Zonr Chang932648d2010-10-13 22:23:56 +08001872 void *GA = GetPointerToGlobalIfAvailable(GV);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001873
Zonr Chang932648d2010-10-13 22:23:56 +08001874 if (GV->isThreadLocal())
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07001875 llvm::report_fatal_error
1876 ("We don't support Thread Local Storage (TLS)!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001877
Zonr Chang932648d2010-10-13 22:23:56 +08001878 if (GA == NULL) {
1879 // If it's not already specified, allocate memory for the global.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001880 GA = GetMemoryForGV(GV);
1881 AddGlobalMapping(GV, GA);
1882 }
1883
1884 InitializeConstantToMemory(GV->getInitializer(), GA);
1885
Zonr Chang932648d2010-10-13 22:23:56 +08001886 // You can do some statistics on global variable here.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001887 return;
1888 }
1889
1890 typedef std::map<llvm::AssertingVH<llvm::GlobalValue>, void*
1891 > GlobalToIndirectSymMapTy;
1892 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
1893
Zonr Chang932648d2010-10-13 22:23:56 +08001894 void *GetPointerToGVIndirectSym(llvm::GlobalValue *V, void *Reference) {
1895 // Make sure GV is emitted first, and create a stub containing the fully
1896 // resolved address.
1897 void *GVAddress = GetPointerToGlobal(V, Reference, false);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001898
Zonr Chang932648d2010-10-13 22:23:56 +08001899 // If we already have a stub for this global variable, recycle it.
1900 void *&IndirectSym = GlobalToIndirectSymMap[V];
1901 // Otherwise, codegen a new indirect symbol.
1902 if (!IndirectSym)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001903 IndirectSym = mpTJI->emitGlobalValueIndirectSym(V, GVAddress, *this);
1904
1905 return IndirectSym;
1906 }
1907
Zonr Chang932648d2010-10-13 22:23:56 +08001908 // This is the equivalent of FunctionToLazyStubMap for external functions.
1909 //
1910 // TODO(llvm.org): Of course, external functions don't need a lazy stub.
1911 // It's actually here to make it more likely that far calls
1912 // succeed, but no single stub can guarantee that. I'll
1913 // remove this in a subsequent checkin when I actually fix
1914 // far calls.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001915 std::map<void*, void*> ExternalFnToStubMap;
1916
Zonr Chang932648d2010-10-13 22:23:56 +08001917 // Return a stub for the function at the specified address.
1918 void *GetExternalFunctionStub(void *FnAddr) {
1919 void *&Stub = ExternalFnToStubMap[FnAddr];
1920 if (Stub)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001921 return Stub;
1922
1923 llvm::TargetJITInfo::StubLayout SL = mpTJI->getStubLayout();
1924 startGVStub(0, SL.Size, SL.Alignment);
1925 Stub = mpTJI->emitFunctionStub(0, FnAddr, *this);
1926 finishGVStub();
1927
1928 return Stub;
1929 }
1930
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001931#if defined(USE_DISASSEMBLER)
Zonr Chang932648d2010-10-13 22:23:56 +08001932 const llvm::MCAsmInfo *mpAsmInfo;
1933 const llvm::MCDisassembler *mpDisassmbler;
1934 llvm::MCInstPrinter *mpIP;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001935
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001936 class BufferMemoryObject : public llvm::MemoryObject {
1937 private:
Zonr Chang932648d2010-10-13 22:23:56 +08001938 const uint8_t *mBytes;
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001939 uint64_t mLength;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001940
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001941 public:
1942 BufferMemoryObject(const uint8_t *Bytes, uint64_t Length) :
1943 mBytes(Bytes), mLength(Length) { }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001944
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001945 uint64_t getBase() const { return 0; }
1946 uint64_t getExtent() const { return mLength; }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001947
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001948 int readByte(uint64_t Addr, uint8_t *Byte) const {
Zonr Chang932648d2010-10-13 22:23:56 +08001949 if (Addr > getExtent())
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001950 return -1;
1951 *Byte = mBytes[Addr];
1952 return 0;
1953 }
1954 };
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001955
Shih-wei Liaofdc568d2010-11-19 15:51:13 -08001956 public:
Zonr Chang932648d2010-10-13 22:23:56 +08001957 void Disassemble(const llvm::StringRef &Name, uint8_t *Start,
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001958 size_t Length, bool IsStub) {
Zonr Chang932648d2010-10-13 22:23:56 +08001959 llvm::raw_fd_ostream *OS;
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07001960#if defined(USE_DISASSEMBLER_FILE)
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001961 std::string ErrorInfo;
Zonr Chang932648d2010-10-13 22:23:56 +08001962 OS = new llvm::raw_fd_ostream("/data/local/tmp/out.S",
1963 ErrorInfo,
1964 llvm::raw_fd_ostream::F_Append);
1965 if (!ErrorInfo.empty()) { // some errors occurred
1966 // LOGE("Error in creating disassembly file");
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001967 delete OS;
1968 return;
1969 }
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07001970#else
1971 OS = &llvm::outs();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001972#endif
Zonr Chang932648d2010-10-13 22:23:56 +08001973 *OS << "JIT: Disassembled code: " << Name << ((IsStub) ? " (stub)" : "")
1974 << "\n";
Shih-wei Liao77ed6142010-04-07 12:21:42 -07001975
Zonr Chang932648d2010-10-13 22:23:56 +08001976 if (mpAsmInfo == NULL)
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001977 mpAsmInfo = mpTarget->createAsmInfo(Triple);
Zonr Chang932648d2010-10-13 22:23:56 +08001978 if (mpDisassmbler == NULL)
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001979 mpDisassmbler = mpTarget->createMCDisassembler();
Zonr Chang932648d2010-10-13 22:23:56 +08001980 if (mpIP == NULL)
1981 mpIP = mpTarget->createMCInstPrinter(mpAsmInfo->getAssemblerDialect(),
1982 *mpAsmInfo);
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001983
Zonr Chang932648d2010-10-13 22:23:56 +08001984 const BufferMemoryObject *BufferMObj = new BufferMemoryObject(Start,
1985 Length);
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001986 uint64_t Size;
1987 uint64_t Index;
1988
Zonr Chang932648d2010-10-13 22:23:56 +08001989 for (Index = 0; Index < Length; Index += Size) {
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001990 llvm::MCInst Inst;
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07001991
Zonr Chang932648d2010-10-13 22:23:56 +08001992 if (mpDisassmbler->getInstruction(Inst, Size, *BufferMObj, Index,
1993 /* REMOVED */ llvm::nulls())) {
1994 (*OS).indent(4)
1995 .write("0x", 2)
1996 .write_hex((uint32_t) Start + Index)
1997 .write(':');
Shih-wei Liaocd61af32010-04-29 00:02:57 -07001998 mpIP->printInst(&Inst, *OS);
1999 *OS << "\n";
2000 } else {
2001 if (Size == 0)
Zonr Chang932648d2010-10-13 22:23:56 +08002002 Size = 1; // skip illegible bytes
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07002003 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002004 }
2005
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002006 *OS << "\n";
2007 delete BufferMObj;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002008
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07002009#if defined(USE_DISASSEMBLER_FILE)
Zonr Chang932648d2010-10-13 22:23:56 +08002010 // If you want the disassemble results write to file, uncomment this.
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002011 OS->close();
2012 delete OS;
2013#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002014 return;
2015 }
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002016#else
Zonr Chang932648d2010-10-13 22:23:56 +08002017 inline void Disassemble(const std::string &Name, uint8_t *Start,
2018 size_t Length, bool IsStub) {
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002019 return;
2020 }
Zonr Chang932648d2010-10-13 22:23:56 +08002021#endif // defined(USE_DISASSEMBLER)
2022
Shih-wei Liaofdc568d2010-11-19 15:51:13 -08002023 private:
Zonr Chang932648d2010-10-13 22:23:56 +08002024 // Resolver to undefined symbol in CodeEmitter
2025 BCCSymbolLookupFn mpSymbolLookupFn;
2026 void *mpSymbolLookupContext;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002027
2028 public:
Zonr Chang932648d2010-10-13 22:23:56 +08002029 // Will take the ownership of @MemMgr
2030 explicit CodeEmitter(CodeMemoryManager *pMemMgr)
2031 : mpMemMgr(pMemMgr),
2032 mpTarget(NULL),
2033 mpTJI(NULL),
2034 mpTD(NULL),
2035 mpCurEmitFunction(NULL),
2036 mpConstantPool(NULL),
2037 mpJumpTable(NULL),
2038 mpMMI(NULL),
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002039#if defined(USE_DISASSEMBLER)
Zonr Chang932648d2010-10-13 22:23:56 +08002040 mpAsmInfo(NULL),
2041 mpDisassmbler(NULL),
2042 mpIP(NULL),
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002043#endif
Zonr Chang932648d2010-10-13 22:23:56 +08002044 mpSymbolLookupFn(NULL),
2045 mpSymbolLookupContext(NULL) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002046 return;
2047 }
2048
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07002049 inline global_addresses_const_iterator global_address_begin() const {
2050 return mGlobalAddressMap.begin();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002051 }
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07002052 inline global_addresses_const_iterator global_address_end() const {
2053 return mGlobalAddressMap.end();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002054 }
2055
Logan824dd0a2010-11-20 01:45:54 +08002056 std::vector<oBCCRelocEntry> const &getCachingRelocations() const {
2057 return mCachingRelocations;
2058 }
2059
Zonr Chang932648d2010-10-13 22:23:56 +08002060 void registerSymbolCallback(BCCSymbolLookupFn pFn, BCCvoid *pContext) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002061 mpSymbolLookupFn = pFn;
2062 mpSymbolLookupContext = pContext;
2063 return;
2064 }
2065
Zonr Chang932648d2010-10-13 22:23:56 +08002066 void setTargetMachine(llvm::TargetMachine &TM) {
2067 // Set Target
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002068 mpTarget = &TM.getTarget();
Zonr Chang932648d2010-10-13 22:23:56 +08002069 // Set TargetJITInfo
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002070 mpTJI = TM.getJITInfo();
Zonr Chang932648d2010-10-13 22:23:56 +08002071 // set TargetData
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002072 mpTD = TM.getTargetData();
2073
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002074 assert(!mpTJI->needsGOT() && "We don't support GOT needed target!");
2075
2076 return;
2077 }
2078
Zonr Chang932648d2010-10-13 22:23:56 +08002079 // This callback is invoked when the specified function is about to be code
2080 // generated. This initializes the BufferBegin/End/Ptr fields.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002081 void startFunction(llvm::MachineFunction &F) {
2082 uintptr_t ActualSize = 0;
2083
2084 mpMemMgr->setMemoryWritable();
Zonr Chang932648d2010-10-13 22:23:56 +08002085
2086 // BufferBegin, BufferEnd and CurBufferPtr are all inherited from class
2087 // MachineCodeEmitter, which is the super class of the class
2088 // JITCodeEmitter.
2089 //
2090 // BufferBegin/BufferEnd - Pointers to the start and end of the memory
2091 // allocated for this code buffer.
2092 //
2093 // CurBufferPtr - Pointer to the next byte of memory to fill when emitting
2094 // code. This is guranteed to be in the range
2095 // [BufferBegin, BufferEnd]. If this pointer is at
2096 // BufferEnd, it will never move due to code emission, and
2097 // all code emission requests will be ignored (this is the
2098 // buffer overflow condition).
2099 BufferBegin = CurBufferPtr =
2100 mpMemMgr->startFunctionBody(F.getFunction(), ActualSize);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002101 BufferEnd = BufferBegin + ActualSize;
2102
Zonr Chang932648d2010-10-13 22:23:56 +08002103 if (mpCurEmitFunction == NULL)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002104 mpCurEmitFunction = new EmittedFunctionCode();
2105 mpCurEmitFunction->FunctionBody = BufferBegin;
2106
Zonr Chang932648d2010-10-13 22:23:56 +08002107 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002108 emitAlignment(16);
2109
2110 emitConstantPool(F.getConstantPool());
Zonr Chang932648d2010-10-13 22:23:56 +08002111 if (llvm::MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002112 initJumpTableInfo(MJTI);
2113
Zonr Chang932648d2010-10-13 22:23:56 +08002114 // About to start emitting the machine code for the function.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002115 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
2116
2117 UpdateGlobalMapping(F.getFunction(), CurBufferPtr);
2118
2119 mpCurEmitFunction->Code = CurBufferPtr;
2120
2121 mMBBLocations.clear();
2122
2123 return;
2124 }
2125
Zonr Chang932648d2010-10-13 22:23:56 +08002126 // This callback is invoked when the specified function has finished code
2127 // generation. If a buffer overflow has occurred, this method returns true
2128 // (the callee is required to try again).
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002129 bool finishFunction(llvm::MachineFunction &F) {
Zonr Chang932648d2010-10-13 22:23:56 +08002130 if (CurBufferPtr == BufferEnd) {
2131 // No enough memory
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002132 mpMemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
2133 return false;
2134 }
2135
Zonr Chang932648d2010-10-13 22:23:56 +08002136 if (llvm::MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002137 emitJumpTableInfo(MJTI);
2138
Zonr Chang932648d2010-10-13 22:23:56 +08002139 // FnStart is the start of the text, not the start of the constant pool
2140 // and other per-function data.
2141 uint8_t *FnStart =
2142 reinterpret_cast<uint8_t*>(
2143 GetPointerToGlobalIfAvailable(F.getFunction()));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002144
Zonr Chang932648d2010-10-13 22:23:56 +08002145 // FnEnd is the end of the function's machine code.
2146 uint8_t *FnEnd = CurBufferPtr;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002147
Zonr Chang932648d2010-10-13 22:23:56 +08002148 if (!mRelocations.empty()) {
Logan824dd0a2010-11-20 01:45:54 +08002149 ptrdiff_t BufferOffset = BufferBegin - mpMemMgr->getCodeMemBase();
2150
Zonr Chang932648d2010-10-13 22:23:56 +08002151 // Resolve the relocations to concrete pointers.
2152 for (int i = 0, e = mRelocations.size(); i != e; i++) {
2153 llvm::MachineRelocation &MR = mRelocations[i];
2154 void *ResultPtr = NULL;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002155
Zonr Chang932648d2010-10-13 22:23:56 +08002156 if (!MR.letTargetResolve()) {
2157 if (MR.isExternalSymbol()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002158 ResultPtr = GetPointerToNamedSymbol(MR.getExternalSymbol(), true);
Logan824dd0a2010-11-20 01:45:54 +08002159
2160 if (MR.mayNeedFarStub()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002161 ResultPtr = GetExternalFunctionStub(ResultPtr);
Logan824dd0a2010-11-20 01:45:54 +08002162 }
2163
Zonr Chang932648d2010-10-13 22:23:56 +08002164 } else if (MR.isGlobalValue()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002165 ResultPtr = GetPointerToGlobal(MR.getGlobalValue(),
2166 BufferBegin
2167 + MR.getMachineCodeOffset(),
2168 MR.mayNeedFarStub());
Zonr Chang932648d2010-10-13 22:23:56 +08002169 } else if (MR.isIndirectSymbol()) {
2170 ResultPtr =
2171 GetPointerToGVIndirectSym(
2172 MR.getGlobalValue(),
2173 BufferBegin + MR.getMachineCodeOffset());
2174 } else if (MR.isBasicBlock()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002175 ResultPtr =
2176 (void*) getMachineBasicBlockAddress(MR.getBasicBlock());
Zonr Chang932648d2010-10-13 22:23:56 +08002177 } else if (MR.isConstantPoolIndex()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002178 ResultPtr =
Zonr Chang932648d2010-10-13 22:23:56 +08002179 (void*) getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002180 } else {
2181 assert(MR.isJumpTableIndex() && "Unknown type of relocation");
2182 ResultPtr =
2183 (void*) getJumpTableEntryAddress(MR.getJumpTableIndex());
2184 }
2185
Logan824dd0a2010-11-20 01:45:54 +08002186 if (!MR.isExternalSymbol() || MR.mayNeedFarStub()) {
2187 // TODO(logan): Cache external symbol relocation entry.
2188 // Currently, we are not caching them. But since Android
2189 // system is using prelink, it is not a problem.
2190
2191 // Cache the relocation result address
2192 mCachingRelocations.push_back(
Logan634bd832010-11-20 09:00:36 +08002193 oBCCRelocEntry(MR.getRelocationType(),
2194 MR.getMachineCodeOffset() + BufferOffset,
Logan824dd0a2010-11-20 01:45:54 +08002195 ResultPtr));
2196 }
2197
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002198 MR.setResultPointer(ResultPtr);
2199 }
2200 }
2201
2202 mpTJI->relocate(BufferBegin, &mRelocations[0], mRelocations.size(),
2203 mpMemMgr->getGOTBase());
2204 }
2205
2206 mpMemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Zonr Chang932648d2010-10-13 22:23:56 +08002207 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
2208 // global variables that were referenced in the relocations.
2209 if (CurBufferPtr == BufferEnd)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002210 return false;
2211
Zonr Chang932648d2010-10-13 22:23:56 +08002212 // Now that we've succeeded in emitting the function.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002213 mpCurEmitFunction->Size = CurBufferPtr - BufferBegin;
2214 BufferBegin = CurBufferPtr = 0;
2215
Zonr Chang932648d2010-10-13 22:23:56 +08002216 if (F.getFunction()->hasName())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002217 mEmittedFunctions[F.getFunction()->getNameStr()] = mpCurEmitFunction;
2218 mpCurEmitFunction = NULL;
2219
2220 mRelocations.clear();
2221 mConstPoolAddresses.clear();
2222
Zonr Chang932648d2010-10-13 22:23:56 +08002223 if (mpMMI)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002224 mpMMI->EndFunction();
2225
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002226 updateFunctionStub(F.getFunction());
2227
Zonr Chang932648d2010-10-13 22:23:56 +08002228 // Mark code region readable and executable if it's not so already.
Shih-wei Liaoc4e4ddf2010-09-24 14:50:26 -07002229 mpMemMgr->setMemoryExecutable();
2230
2231 Disassemble(F.getFunction()->getName(), FnStart, FnEnd - FnStart, false);
2232
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002233 return false;
2234 }
2235
Zonr Chang932648d2010-10-13 22:23:56 +08002236 void startGVStub(const llvm::GlobalValue *GV, unsigned StubSize,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002237 unsigned Alignment) {
2238 mpSavedBufferBegin = BufferBegin;
2239 mpSavedBufferEnd = BufferEnd;
2240 mpSavedCurBufferPtr = CurBufferPtr;
2241
2242 BufferBegin = CurBufferPtr = mpMemMgr->allocateStub(GV, StubSize,
2243 Alignment);
2244 BufferEnd = BufferBegin + StubSize + 1;
2245
2246 return;
2247 }
2248
Zonr Chang932648d2010-10-13 22:23:56 +08002249 void startGVStub(void *Buffer, unsigned StubSize) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002250 mpSavedBufferBegin = BufferBegin;
2251 mpSavedBufferEnd = BufferEnd;
2252 mpSavedCurBufferPtr = CurBufferPtr;
2253
Zonr Chang932648d2010-10-13 22:23:56 +08002254 BufferBegin = CurBufferPtr = reinterpret_cast<uint8_t *>(Buffer);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002255 BufferEnd = BufferBegin + StubSize + 1;
2256
2257 return;
2258 }
2259
2260 void finishGVStub() {
2261 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
2262
Zonr Chang932648d2010-10-13 22:23:56 +08002263 // restore
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002264 BufferBegin = mpSavedBufferBegin;
2265 BufferEnd = mpSavedBufferEnd;
2266 CurBufferPtr = mpSavedCurBufferPtr;
2267
2268 return;
2269 }
2270
Zonr Chang932648d2010-10-13 22:23:56 +08002271 // Allocates and fills storage for an indirect GlobalValue, and returns the
2272 // address.
2273 void *allocIndirectGV(const llvm::GlobalValue *GV,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002274 const uint8_t *Buffer, size_t Size,
2275 unsigned Alignment) {
Zonr Chang932648d2010-10-13 22:23:56 +08002276 uint8_t *IndGV = mpMemMgr->allocateStub(GV, Size, Alignment);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002277 memcpy(IndGV, Buffer, Size);
2278 return IndGV;
2279 }
2280
Zonr Chang932648d2010-10-13 22:23:56 +08002281 // Emits a label
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002282 void emitLabel(llvm::MCSymbol *Label) {
2283 mLabelLocations[Label] = getCurrentPCValue();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002284 return;
2285 }
2286
Zonr Chang932648d2010-10-13 22:23:56 +08002287 // Allocate memory for a global. Unlike allocateSpace, this method does not
2288 // allocate memory in the current output buffer, because a global may live
2289 // longer than the current function.
2290 void *allocateGlobal(uintptr_t Size, unsigned Alignment) {
2291 // Delegate this call through the memory manager.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002292 return mpMemMgr->allocateGlobal(Size, Alignment);
2293 }
2294
Zonr Chang932648d2010-10-13 22:23:56 +08002295 // This should be called by the target when a new basic block is about to be
2296 // emitted. This way the MCE knows where the start of the block is, and can
2297 // implement getMachineBasicBlockAddress.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002298 void StartMachineBasicBlock(llvm::MachineBasicBlock *MBB) {
Zonr Chang932648d2010-10-13 22:23:56 +08002299 if (mMBBLocations.size() <= (unsigned) MBB->getNumber())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002300 mMBBLocations.resize((MBB->getNumber() + 1) * 2);
2301 mMBBLocations[MBB->getNumber()] = getCurrentPCValue();
2302 return;
2303 }
2304
Zonr Chang932648d2010-10-13 22:23:56 +08002305 // Whenever a relocatable address is needed, it should be noted with this
2306 // interface.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002307 void addRelocation(const llvm::MachineRelocation &MR) {
2308 mRelocations.push_back(MR);
2309 return;
2310 }
2311
Zonr Chang932648d2010-10-13 22:23:56 +08002312 // Return the address of the @Index entry in the constant pool that was
2313 // last emitted with the emitConstantPool method.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002314 uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
2315 assert(Index < mpConstantPool->getConstants().size() &&
2316 "Invalid constant pool index!");
2317 return mConstPoolAddresses[Index];
2318 }
2319
Zonr Chang932648d2010-10-13 22:23:56 +08002320 // Return the address of the jump table with index @Index in the function
2321 // that last called initJumpTableInfo.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002322 uintptr_t getJumpTableEntryAddress(unsigned Index) const {
Zonr Chang932648d2010-10-13 22:23:56 +08002323 const std::vector<llvm::MachineJumpTableEntry> &JT =
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002324 mpJumpTable->getJumpTables();
2325
Zonr Chang932648d2010-10-13 22:23:56 +08002326 assert((Index < JT.size()) && "Invalid jump table index!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002327
2328 unsigned int Offset = 0;
2329 unsigned int EntrySize = mpJumpTable->getEntrySize(*mpTD);
2330
Zonr Chang932648d2010-10-13 22:23:56 +08002331 for (unsigned i = 0; i < Index; i++)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002332 Offset += JT[i].MBBs.size();
2333 Offset *= EntrySize;
2334
Zonr Chang932648d2010-10-13 22:23:56 +08002335 return (uintptr_t)(reinterpret_cast<uint8_t*>(mpJumpTableBase) + Offset);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002336 }
2337
Zonr Chang932648d2010-10-13 22:23:56 +08002338 // Return the address of the specified MachineBasicBlock, only usable after
2339 // the label for the MBB has been emitted.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002340 uintptr_t getMachineBasicBlockAddress(llvm::MachineBasicBlock *MBB) const {
2341 assert(mMBBLocations.size() > (unsigned) MBB->getNumber() &&
Zonr Chang932648d2010-10-13 22:23:56 +08002342 mMBBLocations[MBB->getNumber()] &&
2343 "MBB not emitted!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002344 return mMBBLocations[MBB->getNumber()];
2345 }
2346
Zonr Chang932648d2010-10-13 22:23:56 +08002347 // Return the address of the specified LabelID, only usable after the
2348 // LabelID has been emitted.
2349 uintptr_t getLabelAddress(llvm::MCSymbol *Label) const {
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002350 assert(mLabelLocations.count(Label) && "Label not emitted!");
2351 return mLabelLocations.find(Label)->second;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002352 }
2353
Zonr Chang932648d2010-10-13 22:23:56 +08002354 // Specifies the MachineModuleInfo object. This is used for exception
2355 // handling purposes.
2356 void setModuleInfo(llvm::MachineModuleInfo *Info) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002357 mpMMI = Info;
2358 return;
2359 }
2360
Zonr Chang932648d2010-10-13 22:23:56 +08002361 void updateFunctionStub(const llvm::Function *F) {
2362 // Get the empty stub we generated earlier.
2363 void *Stub;
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002364 std::set<const llvm::Function*>::iterator I = PendingFunctions.find(F);
Zonr Chang932648d2010-10-13 22:23:56 +08002365 if (I != PendingFunctions.end())
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002366 Stub = mFunctionToLazyStubMap[F];
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002367 else
2368 return;
2369
Zonr Chang932648d2010-10-13 22:23:56 +08002370 void *Addr = GetPointerToGlobalIfAvailable(F);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002371
2372 assert(Addr != Stub &&
2373 "Function must have non-stub address to be updated.");
2374
Zonr Chang932648d2010-10-13 22:23:56 +08002375 // Tell the target jit info to rewrite the stub at the specified address,
2376 // rather than creating a new one.
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002377 llvm::TargetJITInfo::StubLayout SL = mpTJI->getStubLayout();
2378 startGVStub(Stub, SL.Size);
2379 mpTJI->emitFunctionStub(F, Addr, *this);
2380 finishGVStub();
2381
Zonr Chang932648d2010-10-13 22:23:56 +08002382 Disassemble(F->getName(), reinterpret_cast<uint8_t*>(Stub),
2383 SL.Size, true);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002384
2385 PendingFunctions.erase(I);
2386
2387 return;
2388 }
2389
Zonr Chang932648d2010-10-13 22:23:56 +08002390 // Once you finish the compilation on a translation unit, you can call this
2391 // function to recycle the memory (which is used at compilation time and not
2392 // needed for runtime).
2393 //
2394 // NOTE: You should not call this funtion until the code-gen passes for a
2395 // given module is done. Otherwise, the results is undefined and may
2396 // cause the system crash!
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002397 void releaseUnnecessary() {
2398 mMBBLocations.clear();
2399 mLabelLocations.clear();
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002400 mGlobalAddressMap.clear();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002401 mFunctionToLazyStubMap.clear();
2402 GlobalToIndirectSymMap.clear();
2403 ExternalFnToStubMap.clear();
2404 PendingFunctions.clear();
2405
2406 return;
2407 }
2408
2409 void reset() {
2410 releaseUnnecessary();
2411
2412 mpSymbolLookupFn = NULL;
2413 mpSymbolLookupContext = NULL;
2414
2415 mpTJI = NULL;
2416 mpTD = NULL;
2417
Zonr Chang932648d2010-10-13 22:23:56 +08002418 for (EmittedFunctionsMapTy::iterator I = mEmittedFunctions.begin(),
2419 E = mEmittedFunctions.end();
2420 I != E;
2421 I++)
2422 if (I->second != NULL)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002423 delete I->second;
2424 mEmittedFunctions.clear();
2425
2426 mpMemMgr->reset();
2427
2428 return;
2429 }
2430
Zonr Chang932648d2010-10-13 22:23:56 +08002431 void *lookup(const char *Name) {
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07002432 return lookup( llvm::StringRef(Name) );
2433 }
2434
Zonr Chang932648d2010-10-13 22:23:56 +08002435 void *lookup(const llvm::StringRef &Name) {
2436 EmittedFunctionsMapTy::const_iterator I =
2437 mEmittedFunctions.find(Name.str());
2438 if (I == mEmittedFunctions.end())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002439 return NULL;
2440 else
2441 return I->second->Code;
2442 }
2443
Zonr Chang932648d2010-10-13 22:23:56 +08002444 void getFunctionNames(BCCsizei *actualFunctionCount,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002445 BCCsizei maxFunctionCount,
Zonr Chang932648d2010-10-13 22:23:56 +08002446 BCCchar **functions) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002447 int functionCount = mEmittedFunctions.size();
2448
Zonr Chang932648d2010-10-13 22:23:56 +08002449 if (actualFunctionCount)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002450 *actualFunctionCount = functionCount;
Zonr Chang932648d2010-10-13 22:23:56 +08002451 if (functionCount > maxFunctionCount)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002452 functionCount = maxFunctionCount;
Zonr Chang932648d2010-10-13 22:23:56 +08002453 if (functions)
2454 for (EmittedFunctionsMapTy::const_iterator
2455 I = mEmittedFunctions.begin(), E = mEmittedFunctions.end();
2456 (I != E) && (functionCount > 0);
2457 I++, functionCount--)
2458 *functions++ = const_cast<BCCchar*>(I->first.c_str());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002459
2460 return;
2461 }
2462
Zonr Chang932648d2010-10-13 22:23:56 +08002463 void getFunctionBinary(BCCchar *label,
2464 BCCvoid **base,
2465 BCCsizei *length) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002466 EmittedFunctionsMapTy::const_iterator I = mEmittedFunctions.find(label);
Zonr Chang932648d2010-10-13 22:23:56 +08002467 if (I == mEmittedFunctions.end()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002468 *base = NULL;
2469 *length = 0;
2470 } else {
2471 *base = I->second->Code;
2472 *length = I->second->Size;
2473 }
2474 return;
2475 }
2476
2477 ~CodeEmitter() {
Zonr Chang932648d2010-10-13 22:23:56 +08002478 delete mpMemMgr;
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002479#if defined(USE_DISASSEMBLER)
Zonr Chang932648d2010-10-13 22:23:56 +08002480 delete mpAsmInfo;
2481 delete mpDisassmbler;
2482 delete mpIP;
Shih-wei Liaocd61af32010-04-29 00:02:57 -07002483#endif
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002484 return;
2485 }
Zonr Chang932648d2010-10-13 22:23:56 +08002486 };
2487 // End of Class CodeEmitter
2488 //////////////////////////////////////////////////////////////////////////////
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002489
Zonr Chang932648d2010-10-13 22:23:56 +08002490 // The CodeEmitter
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002491 llvm::OwningPtr<CodeEmitter> mCodeEmitter;
Zonr Chang932648d2010-10-13 22:23:56 +08002492 CodeEmitter *createCodeEmitter() {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002493 mCodeEmitter.reset(new CodeEmitter(mCodeMemMgr.take()));
2494 return mCodeEmitter.get();
2495 }
2496
2497 BCCSymbolLookupFn mpSymbolLookupFn;
Zonr Chang932648d2010-10-13 22:23:56 +08002498 void *mpSymbolLookupContext;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002499
Zonr Chang932648d2010-10-13 22:23:56 +08002500 llvm::LLVMContext *mContext;
2501 llvm::Module *mModule;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002502
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002503 bool mHasLinked;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002504
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002505 public:
Zonr Chang932648d2010-10-13 22:23:56 +08002506 Compiler()
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002507 : mNeverCache(true),
2508 mCacheNew(false),
2509 mCacheFd(-1),
2510 mCacheMapAddr(NULL),
2511 mCacheHdr(NULL),
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08002512 mCacheSize(0),
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002513 mCacheDiff(0),
2514 mCodeDataAddr(NULL),
2515 mpSymbolLookupFn(NULL),
Zonr Chang932648d2010-10-13 22:23:56 +08002516 mpSymbolLookupContext(NULL),
2517 mContext(NULL),
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002518 mModule(NULL),
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002519 mHasLinked(false) /* Turn off linker */ {
Shih-wei Liaoc5611992010-05-09 06:37:55 -07002520 llvm::remove_fatal_error_handler();
2521 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07002522 mContext = new llvm::LLVMContext();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002523 return;
2524 }
2525
Zonr Chang932648d2010-10-13 22:23:56 +08002526 // interface for BCCscript::registerSymbolCallback()
2527 void registerSymbolCallback(BCCSymbolLookupFn pFn, BCCvoid *pContext) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002528 mpSymbolLookupFn = pFn;
2529 mpSymbolLookupContext = pContext;
2530 return;
2531 }
2532
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002533 int readModule(llvm::Module *module) {
Zonr Changdbee68b2010-10-22 05:02:16 +08002534 GlobalInitialization();
2535 mModule = module;
2536 return hasError();
2537 }
2538
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002539 int readBC(const char *bitcode,
2540 size_t bitcodeSize,
2541 const BCCchar *resName) {
2542 GlobalInitialization();
2543
2544 if (resName) {
Loganad7e8e12010-11-22 20:43:43 +08002545 if (!BccCodeAddrTaken) {
2546 // Turn off the default NeverCaching mode
2547 mNeverCache = false;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002548
Loganad7e8e12010-11-22 20:43:43 +08002549 mCacheFd = openCacheFile(resName, true /* createIfMissing */);
2550 if (mCacheFd >= 0 && !mCacheNew) { // Just use cache file
2551 return -mCacheFd;
2552 }
2553 } else {
2554 mNeverCache = true;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002555 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002556 }
2557
2558 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002559
Zonr Chang932648d2010-10-13 22:23:56 +08002560 if (bitcode == NULL || bitcodeSize <= 0)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002561 return 0;
Shih-wei Liaoc5611992010-05-09 06:37:55 -07002562
Zonr Chang932648d2010-10-13 22:23:56 +08002563 // Package input to object MemoryBuffer
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002564 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
Zonr Chang97f5e612010-10-22 20:38:26 +08002565 llvm::StringRef(bitcode, bitcodeSize)));
2566
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002567 if (MEM.get() == NULL) {
Zonr Chang97f5e612010-10-22 20:38:26 +08002568 setError("Error reading input program bitcode into memory");
2569 return hasError();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002570 }
2571
Zonr Chang932648d2010-10-13 22:23:56 +08002572 // Read the input Bitcode as a Module
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002573 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
2574 MEM.reset();
Zonr Chang97f5e612010-10-22 20:38:26 +08002575 return hasError();
2576 }
Shih-wei Liaoc5611992010-05-09 06:37:55 -07002577
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002578 int linkBC(const char *bitcode, size_t bitcodeSize) {
2579 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
Zonr Chang97f5e612010-10-22 20:38:26 +08002580
2581 if (bitcode == NULL || bitcodeSize <= 0)
2582 return 0;
2583
2584 if (mModule == NULL) {
2585 setError("No module presents for linking");
2586 return hasError();
2587 }
2588
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002589 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
Zonr Chang97f5e612010-10-22 20:38:26 +08002590 llvm::StringRef(bitcode, bitcodeSize)));
2591
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002592 if (MEM.get() == NULL) {
Zonr Chang97f5e612010-10-22 20:38:26 +08002593 setError("Error reading input library bitcode into memory");
2594 return hasError();
2595 }
2596
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002597 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
Zonr Chang97f5e612010-10-22 20:38:26 +08002598 *mContext,
2599 &mError));
2600 if (Lib.get() == NULL)
2601 return hasError();
2602
2603 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
2604 return hasError();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002605
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002606 // Everything for linking should be settled down here with no error occurs
2607 mHasLinked = true;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002608 return hasError();
2609 }
2610
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002611
2612 // interface for bccLoadBinary()
2613 int loader() {
2614 // Check File Descriptor
2615 if (mCacheFd < 0) {
2616 LOGE("loading cache from invalid mCacheFd = %d\n", (int)mCacheFd);
2617 goto giveup;
2618 }
2619
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002620 // Check File Size
2621 struct stat statCacheFd;
2622 if (fstat(mCacheFd, &statCacheFd) < 0) {
2623 LOGE("unable to stat mCacheFd = %d\n", (int)mCacheFd);
2624 goto giveup;
2625 }
2626
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08002627 mCacheSize = statCacheFd.st_size;
2628
2629 if (mCacheSize < sizeof(oBCCHeader) ||
2630 mCacheSize <= MaxCodeSize + MaxGlobalVarSize) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002631 LOGE("mCacheFd %d is too small to be correct\n", (int)mCacheFd);
2632 goto giveup;
2633 }
2634
Shih-wei Liao3d77c422010-11-21 19:51:59 -08002635 if (lseek(mCacheFd, 0, SEEK_SET) != 0) {
2636 LOGE("Unable to seek to 0: %s\n", strerror(errno));
2637 goto giveup;
2638 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002639
2640 // Read File Content
2641 {
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002642 // Part 1. Deal with the non-codedata section first
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08002643 off_t heuristicCodeOffset = mCacheSize - MaxCodeSize - MaxGlobalVarSize;
Loganad7e8e12010-11-22 20:43:43 +08002644 LOGE("sliao@Loader: mCacheSize=%x, heuristicCodeOffset=%llx",
2645 (unsigned int)mCacheSize,
2646 (unsigned long long int)heuristicCodeOffset);
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002647
2648 mCacheMapAddr = (char *)malloc(heuristicCodeOffset);
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002649 if (!mCacheMapAddr) {
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002650 flock(mCacheFd, LOCK_UN);
2651 LOGE("allocation failed.\n");
2652 goto bail;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002653 }
2654
2655 size_t nread = TEMP_FAILURE_RETRY1(read(mCacheFd, mCacheMapAddr,
2656 heuristicCodeOffset));
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002657 if (nread != (size_t)heuristicCodeOffset) {
2658 LOGE("read(mCacheFd) failed\n");
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002659 goto bail;
2660 }
2661
2662 mCacheHdr = reinterpret_cast<oBCCHeader *>(mCacheMapAddr);
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002663 // Sanity check
2664 if (mCacheHdr->codeOffset != (uint32_t)heuristicCodeOffset) {
2665 LOGE("assertion failed: heuristic code offset is not correct.\n");
2666 goto bail;
2667 }
Shih-wei Liao3d77c422010-11-21 19:51:59 -08002668 LOGE("sliao: mCacheHdr->cachedCodeDataAddr=%x", mCacheHdr->cachedCodeDataAddr);
2669 LOGE("mCacheHdr->rootAddr=%x", mCacheHdr->rootAddr);
2670 LOGE("mCacheHdr->initAddr=%x", mCacheHdr->initAddr);
2671 LOGE("mCacheHdr->codeOffset=%x", mCacheHdr->codeOffset);
2672 LOGE("mCacheHdr->codeSize=%x", mCacheHdr->codeSize);
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002673
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002674 // Verify the Cache File
2675 if (memcmp(mCacheHdr->magic, OBCC_MAGIC, 4) != 0) {
2676 LOGE("bad magic word\n");
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002677 goto bail;
2678 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002679
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002680 if (memcmp(mCacheHdr->magicVersion, OBCC_MAGIC_VERS, 4) != 0) {
2681 LOGE("bad oBCC version 0x%08x\n",
2682 *reinterpret_cast<uint32_t *>(mCacheHdr->magicVersion));
2683 goto bail;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002684 }
2685
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002686 if (mCacheSize < mCacheHdr->relocOffset +
2687 mCacheHdr->relocCount * sizeof(oBCCRelocEntry)) {
2688 LOGE("relocate table overflow\n");
2689 goto bail;
2690 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002691
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002692 if (mCacheSize < mCacheHdr->exportVarsOffset +
2693 mCacheHdr->exportVarsCount * sizeof(uint32_t)) {
2694 LOGE("export variables table overflow\n");
2695 goto bail;
2696 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002697
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002698 if (mCacheSize < mCacheHdr->exportFuncsOffset +
2699 mCacheHdr->exportFuncsCount * sizeof(uint32_t)) {
2700 LOGE("export functions table overflow\n");
2701 goto bail;
2702 }
2703
2704 if (mCacheSize < mCacheHdr->exportPragmasOffset +
2705 mCacheHdr->exportPragmasCount * sizeof(uint32_t)) {
2706 LOGE("export pragmas table overflow\n");
2707 goto bail;
2708 }
2709
2710 if (mCacheSize < mCacheHdr->codeOffset + mCacheHdr->codeSize) {
2711 LOGE("code cache overflow\n");
2712 goto bail;
2713 }
2714
2715 if (mCacheSize < mCacheHdr->dataOffset + mCacheHdr->dataSize) {
2716 LOGE("data (global variable) cache overflow\n");
2717 goto bail;
2718 }
2719
2720 // Part 2. Deal with the codedata section
2721 mCodeDataAddr = (char *) mmap(reinterpret_cast<void*>(BCC_CODE_ADDR),
2722 MaxCodeSize + MaxGlobalVarSize,
2723 PROT_READ | PROT_EXEC | PROT_WRITE,
2724 MAP_PRIVATE | MAP_FIXED,
2725 mCacheFd, heuristicCodeOffset);
2726 if (mCodeDataAddr != MAP_FAILED &&
2727 mCodeDataAddr ==
2728 reinterpret_cast<char *>(mCacheHdr->cachedCodeDataAddr)) {
2729 // relocate is avoidable
Loganad7e8e12010-11-22 20:43:43 +08002730 BccCodeAddrTaken = true;
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002731
2732 flock(mCacheFd, LOCK_UN);
2733 } else {
2734 mCacheMapAddr = (char *) mmap(0,
2735 mCacheSize,
2736 PROT_READ | PROT_EXEC | PROT_WRITE,
2737 MAP_PRIVATE,
2738 mCacheFd,
2739 0);
2740 if (mCacheMapAddr == MAP_FAILED) {
2741 LOGE("unable to mmap .oBBC cache: %s\n", strerror(errno));
2742 flock(mCacheFd, LOCK_UN);
2743 goto giveup;
2744 }
2745
2746 flock(mCacheFd, LOCK_UN);
2747 mCodeDataAddr = mCacheMapAddr + mCacheHdr->codeOffset;
2748 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002749 }
2750
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002751 // Relocate
2752 {
2753 mCacheDiff = mCodeDataAddr -
2754 reinterpret_cast<char *>(mCacheHdr->cachedCodeDataAddr);
2755
Loganad7e8e12010-11-22 20:43:43 +08002756 if (!BccCodeAddrTaken) { // To relocate
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002757 if (mCacheHdr->rootAddr) {
2758 mCacheHdr->rootAddr += mCacheDiff;
Logan824dd0a2010-11-20 01:45:54 +08002759 }
2760
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002761 if (mCacheHdr->initAddr) {
2762 mCacheHdr->initAddr += mCacheDiff;
Logan824dd0a2010-11-20 01:45:54 +08002763 }
2764
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002765 oBCCRelocEntry *cachedRelocTable =
2766 reinterpret_cast<oBCCRelocEntry *>(mCacheMapAddr +
2767 mCacheHdr->relocOffset);
Logan824dd0a2010-11-20 01:45:54 +08002768
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002769 std::vector<llvm::MachineRelocation> relocations;
2770
2771 // Read in the relocs
2772 for (size_t i = 0; i < mCacheHdr->relocCount; i++) {
2773 oBCCRelocEntry *entry = &cachedRelocTable[i];
2774
2775 llvm::MachineRelocation reloc =
2776 llvm::MachineRelocation::getGV((uintptr_t)entry->relocOffset,
2777 (unsigned)entry->relocType, 0, 0);
2778
2779 reloc.setResultPointer(
2780 reinterpret_cast<char *>(entry->cachedResultAddr) + mCacheDiff);
2781
2782 relocations.push_back(reloc);
Shih-wei Liaofdc568d2010-11-19 15:51:13 -08002783 }
2784
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002785 // Rewrite machine code using llvm::TargetJITInfo relocate
2786 {
2787 llvm::TargetMachine *TM = NULL;
2788 const llvm::Target *Target;
2789 std::string FeaturesStr;
2790
2791 // Create TargetMachine
2792 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
2793 if (hasError())
2794 goto bail;
2795
2796 if (!CPU.empty() || !Features.empty()) {
2797 llvm::SubtargetFeatures F;
2798 F.setCPU(CPU);
2799 for (std::vector<std::string>::const_iterator I = Features.begin(),
2800 E = Features.end(); I != E; I++)
2801 F.AddFeature(*I);
2802 FeaturesStr = F.getString();
2803 }
2804
2805 TM = Target->createTargetMachine(Triple, FeaturesStr);
2806 if (TM == NULL) {
2807 setError("Failed to create target machine implementation for the"
2808 " specified triple '" + Triple + "'");
2809 goto bail;
2810 }
2811
2812 TM->getJITInfo()->relocate(mCodeDataAddr,
2813 &relocations[0], relocations.size(),
2814 (unsigned char *)mCodeDataAddr+MaxCodeSize);
2815
2816 if (mCodeEmitter.get()) {
2817 mCodeEmitter->Disassemble(llvm::StringRef("cache"),
2818 reinterpret_cast<uint8_t*>(mCodeDataAddr),
2819 2 * 1024 /*MaxCodeSize*/,
2820 false);
2821 }
2822
2823 delete TM;
2824 }
Loganad7e8e12010-11-22 20:43:43 +08002825 } // End of if (!BccCodeAddrTaken)
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002826 }
2827
2828 return 0;
2829
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002830 bail:
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002831 if (mCacheMapAddr) {
2832 free(mCacheMapAddr);
Loganad7e8e12010-11-22 20:43:43 +08002833 mCacheMapAddr = 0;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002834 }
Loganad7e8e12010-11-22 20:43:43 +08002835
2836 if (BccCodeAddrTaken) {
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002837 if (munmap(mCodeDataAddr, MaxCodeSize + MaxGlobalVarSize) != 0) {
2838 LOGE("munmap failed: %s\n", strerror(errno));
2839 }
Loganad7e8e12010-11-22 20:43:43 +08002840 mCodeDataAddr = 0;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002841 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002842
Shih-wei Liao1f45b862010-11-21 23:22:38 -08002843 giveup:
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002844 return 1;
2845 }
2846
2847 // interace for bccCompileBC()
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002848 int compile() {
Zonr Chang932648d2010-10-13 22:23:56 +08002849 llvm::TargetData *TD = NULL;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002850
Zonr Chang932648d2010-10-13 22:23:56 +08002851 llvm::TargetMachine *TM = NULL;
2852 const llvm::Target *Target;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002853 std::string FeaturesStr;
2854
Zonr Chang932648d2010-10-13 22:23:56 +08002855 llvm::FunctionPassManager *CodeGenPasses = NULL;
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07002856
Zonr Chang932648d2010-10-13 22:23:56 +08002857 const llvm::NamedMDNode *PragmaMetadata;
2858 const llvm::NamedMDNode *ExportVarMetadata;
2859 const llvm::NamedMDNode *ExportFuncMetadata;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002860
Zonr Chang932648d2010-10-13 22:23:56 +08002861 if (mModule == NULL) // No module was loaded
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002862 return 0;
2863
Zonr Chang932648d2010-10-13 22:23:56 +08002864 // Create TargetMachine
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002865 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
Zonr Chang932648d2010-10-13 22:23:56 +08002866 if (hasError())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002867 goto on_bcc_compile_error;
2868
Zonr Chang932648d2010-10-13 22:23:56 +08002869 if (!CPU.empty() || !Features.empty()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002870 llvm::SubtargetFeatures F;
2871 F.setCPU(CPU);
Zonr Chang932648d2010-10-13 22:23:56 +08002872 for (std::vector<std::string>::const_iterator I = Features.begin(),
2873 E = Features.end();
2874 I != E;
2875 I++)
2876 F.AddFeature(*I);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002877 FeaturesStr = F.getString();
2878 }
2879
2880 TM = Target->createTargetMachine(Triple, FeaturesStr);
Zonr Chang932648d2010-10-13 22:23:56 +08002881 if (TM == NULL) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002882 setError("Failed to create target machine implementation for the"
2883 " specified triple '" + Triple + "'");
2884 goto on_bcc_compile_error;
2885 }
2886
Zonr Chang932648d2010-10-13 22:23:56 +08002887 // Create memory manager for creation of code emitter later.
2888 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002889 setError("Failed to startup memory management for further compilation");
2890 goto on_bcc_compile_error;
2891 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002892 mCodeDataAddr = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002893
Zonr Chang932648d2010-10-13 22:23:56 +08002894 // Create code emitter
2895 if (!mCodeEmitter.get()) {
2896 if (!createCodeEmitter()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002897 setError("Failed to create machine code emitter to complete"
2898 " the compilation");
2899 goto on_bcc_compile_error;
2900 }
2901 } else {
Zonr Chang932648d2010-10-13 22:23:56 +08002902 // Reuse the code emitter
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002903 mCodeEmitter->reset();
2904 }
2905
2906 mCodeEmitter->setTargetMachine(*TM);
2907 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
2908 mpSymbolLookupContext);
2909
Zonr Chang932648d2010-10-13 22:23:56 +08002910 // Get target data from Module
Shih-wei Liao77ed6142010-04-07 12:21:42 -07002911 TD = new llvm::TargetData(mModule);
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002912
Zonr Chang5d35b972010-10-23 14:36:47 +08002913 // Load named metadata
2914 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
2915 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
2916 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
2917
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002918 // Create LTO passes and run them on the mModule
2919 if (mHasLinked) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08002920 llvm::TimePassesIsEnabled = true; // TODO(all)
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002921 llvm::PassManager LTOPasses;
Zonr Chang5d35b972010-10-23 14:36:47 +08002922 LTOPasses.add(new llvm::TargetData(*TD));
2923
2924 std::vector<const char*> ExportSymbols;
2925
2926 // A workaround for getting export variable and function name. Will refine
2927 // it soon.
2928 if (ExportVarMetadata) {
2929 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
2930 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
2931 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
2932 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
2933 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
2934 llvm::StringRef ExportVarName =
2935 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
2936 ExportSymbols.push_back(ExportVarName.data());
2937 }
2938 }
2939 }
2940 }
2941
2942 if (ExportFuncMetadata) {
2943 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
2944 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
2945 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
2946 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
2947 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
2948 llvm::StringRef ExportFuncName =
2949 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
2950 ExportSymbols.push_back(ExportFuncName.data());
2951 }
2952 }
2953 }
2954 }
2955 // root() and init() are born to be exported
2956 ExportSymbols.push_back("root");
2957 ExportSymbols.push_back("init");
2958
Zonr Change5c7a542010-10-24 01:07:27 +08002959 // We now create passes list performing LTO. These are copied from
2960 // (including comments) llvm::createStandardLTOPasses().
2961
2962 // Internalize all other symbols not listed in ExportSymbols
Zonr Chang5d35b972010-10-23 14:36:47 +08002963 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
Zonr Chang6e1d6c32010-10-23 11:57:16 +08002964
Zonr Change5c7a542010-10-24 01:07:27 +08002965 // Propagate constants at call sites into the functions they call. This
2966 // opens opportunities for globalopt (and inlining) by substituting
2967 // function pointers passed as arguments to direct uses of functions.
2968 LTOPasses.add(llvm::createIPSCCPPass());
2969
2970 // Now that we internalized some globals, see if we can hack on them!
2971 LTOPasses.add(llvm::createGlobalOptimizerPass());
2972
2973 // Linking modules together can lead to duplicated global constants, only
2974 // keep one copy of each constant...
2975 LTOPasses.add(llvm::createConstantMergePass());
2976
2977 // Remove unused arguments from functions...
2978 LTOPasses.add(llvm::createDeadArgEliminationPass());
2979
2980 // Reduce the code after globalopt and ipsccp. Both can open up
2981 // significant simplification opportunities, and both can propagate
2982 // functions through function pointers. When this happens, we often have
2983 // to resolve varargs calls, etc, so let instcombine do this.
2984 LTOPasses.add(llvm::createInstructionCombiningPass());
2985
2986 // Inline small functions
2987 LTOPasses.add(llvm::createFunctionInliningPass());
2988
2989 // Remove dead EH info.
2990 LTOPasses.add(llvm::createPruneEHPass());
2991
2992 // Internalize the globals again after inlining
2993 LTOPasses.add(llvm::createGlobalOptimizerPass());
2994
2995 // Remove dead functions.
2996 LTOPasses.add(llvm::createGlobalDCEPass());
2997
2998 // If we didn't decide to inline a function, check to see if we can
2999 // transform it to pass arguments by value instead of by reference.
3000 LTOPasses.add(llvm::createArgumentPromotionPass());
3001
3002 // The IPO passes may leave cruft around. Clean up after them.
3003 LTOPasses.add(llvm::createInstructionCombiningPass());
3004 LTOPasses.add(llvm::createJumpThreadingPass());
3005
3006 // Break up allocas
3007 LTOPasses.add(llvm::createScalarReplAggregatesPass());
3008
3009 // Run a few AA driven optimizations here and now, to cleanup the code.
3010 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
3011 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
3012
3013 // Hoist loop invariants.
3014 LTOPasses.add(llvm::createLICMPass());
3015
3016 // Remove redundancies.
3017 LTOPasses.add(llvm::createGVNPass());
3018
3019 // Remove dead memcpys.
3020 LTOPasses.add(llvm::createMemCpyOptPass());
3021
3022 // Nuke dead stores.
3023 LTOPasses.add(llvm::createDeadStoreEliminationPass());
3024
3025 // Cleanup and simplify the code after the scalar optimizations.
3026 LTOPasses.add(llvm::createInstructionCombiningPass());
3027
3028 LTOPasses.add(llvm::createJumpThreadingPass());
3029
3030 // Delete basic blocks, which optimization passes may have killed.
3031 LTOPasses.add(llvm::createCFGSimplificationPass());
3032
3033 // Now that we have optimized the program, discard unreachable functions.
3034 LTOPasses.add(llvm::createGlobalDCEPass());
3035
Zonr Chang6e1d6c32010-10-23 11:57:16 +08003036 LTOPasses.run(*mModule);
3037 }
3038
Zonr Chang932648d2010-10-13 22:23:56 +08003039 // Create code-gen pass to run the code emitter
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003040 CodeGenPasses = new llvm::FunctionPassManager(mModule);
Zonr Chang932648d2010-10-13 22:23:56 +08003041 CodeGenPasses->add(TD); // Will take the ownership of TD
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003042
Zonr Chang932648d2010-10-13 22:23:56 +08003043 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
3044 *mCodeEmitter,
3045 CodeGenOptLevel)) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003046 setError("The machine code emission is not supported by BCC on target '"
3047 + Triple + "'");
3048 goto on_bcc_compile_error;
3049 }
3050
Zonr Chang932648d2010-10-13 22:23:56 +08003051 // Run the pass (the code emitter) on every non-declaration function in the
3052 // module
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003053 CodeGenPasses->doInitialization();
Zonr Chang932648d2010-10-13 22:23:56 +08003054 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
3055 I != E;
3056 I++)
3057 if (!I->isDeclaration())
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003058 CodeGenPasses->run(*I);
Shih-wei Liao066d5ef2010-05-11 03:28:39 -07003059
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003060 CodeGenPasses->doFinalization();
3061
Zonr Chang932648d2010-10-13 22:23:56 +08003062 // Copy the global address mapping from code emitter and remapping
Zonr Chang932648d2010-10-13 22:23:56 +08003063 if (ExportVarMetadata) {
3064 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
3065 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
3066 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
3067 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
3068 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003069 llvm::StringRef ExportVarName =
3070 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
Zonr Chang932648d2010-10-13 22:23:56 +08003071 CodeEmitter::global_addresses_const_iterator I, E;
3072 for (I = mCodeEmitter->global_address_begin(),
3073 E = mCodeEmitter->global_address_end();
3074 I != E;
3075 I++) {
3076 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003077 continue;
Zonr Chang932648d2010-10-13 22:23:56 +08003078 if (ExportVarName == I->first->getName()) {
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003079 mExportVars.push_back(I->second);
3080 break;
3081 }
3082 }
Zonr Chang932648d2010-10-13 22:23:56 +08003083 if (I != mCodeEmitter->global_address_end())
3084 continue; // found
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003085 }
3086 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003087 // if reaching here, we know the global variable record in metadata is
3088 // not found. So we make an empty slot
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003089 mExportVars.push_back(NULL);
3090 }
3091 assert((mExportVars.size() == ExportVarMetadata->getNumOperands()) &&
3092 "Number of slots doesn't match the number of export variables!");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003093 }
3094
Zonr Chang932648d2010-10-13 22:23:56 +08003095 if (ExportFuncMetadata) {
3096 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
3097 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
3098 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
3099 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
3100 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003101 llvm::StringRef ExportFuncName =
3102 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
3103 mExportFuncs.push_back(mCodeEmitter->lookup(ExportFuncName));
3104 }
3105 }
3106 }
3107 }
3108
Zonr Chang932648d2010-10-13 22:23:56 +08003109 // Tell code emitter now can release the memory using during the JIT since
3110 // we have done the code emission
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003111 mCodeEmitter->releaseUnnecessary();
3112
Zonr Chang932648d2010-10-13 22:23:56 +08003113 // Finally, read pragma information from the metadata node of the @Module if
3114 // any.
Zonr Chang932648d2010-10-13 22:23:56 +08003115 if (PragmaMetadata)
3116 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
3117 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
3118 if (Pragma != NULL &&
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003119 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
Zonr Chang932648d2010-10-13 22:23:56 +08003120 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
3121 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003122
Zonr Chang932648d2010-10-13 22:23:56 +08003123 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003124 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
3125 llvm::StringRef PragmaName =
3126 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
3127 llvm::StringRef PragmaValue =
3128 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
3129
Zonr Chang932648d2010-10-13 22:23:56 +08003130 mPragmas.push_back(
3131 std::make_pair(std::string(PragmaName.data(),
3132 PragmaName.size()),
3133 std::string(PragmaValue.data(),
3134 PragmaValue.size())));
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003135 }
3136 }
3137 }
3138
3139 on_bcc_compile_error:
Zonr Chang932648d2010-10-13 22:23:56 +08003140 // LOGE("on_bcc_compiler_error");
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003141 if (CodeGenPasses) {
3142 delete CodeGenPasses;
3143 } else if (TD) {
3144 delete TD;
3145 }
3146 if (TM)
3147 delete TM;
3148
Shih-wei Liao066d5ef2010-05-11 03:28:39 -07003149 if (mError.empty()) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003150 if (!mNeverCache && mCacheFd >= 0 && mCacheNew) {
3151 genCacheFile();
3152 flock(mCacheFd, LOCK_UN);
3153 }
3154
Shih-wei Liao066d5ef2010-05-11 03:28:39 -07003155 return false;
3156 }
3157
Zonr Chang932648d2010-10-13 22:23:56 +08003158 // LOGE(getErrorMessage());
Shih-wei Liao066d5ef2010-05-11 03:28:39 -07003159 return true;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003160 }
3161
Zonr Chang932648d2010-10-13 22:23:56 +08003162 // interface for bccGetScriptInfoLog()
3163 char *getErrorMessage() {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003164 return const_cast<char*>(mError.c_str());
3165 }
3166
Zonr Chang932648d2010-10-13 22:23:56 +08003167 // interface for bccGetScriptLabel()
3168 void *lookup(const char *name) {
3169 void *addr = NULL;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003170 if (!mNeverCache && mCacheFd >= 0 && !mCacheNew) {
3171 if (!strcmp(name, "root")) {
3172 addr = reinterpret_cast<void *>(mCacheHdr->rootAddr);
3173 } else if (!strcmp(name, "init")) {
3174 addr = reinterpret_cast<void *>(mCacheHdr->initAddr);
3175 }
3176 return addr;
3177 }
3178
Zonr Chang932648d2010-10-13 22:23:56 +08003179 if (mCodeEmitter.get())
3180 // Find function pointer
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003181 addr = mCodeEmitter->lookup(name);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003182 return addr;
3183 }
3184
Zonr Chang932648d2010-10-13 22:23:56 +08003185 // Interface for bccGetExportVars()
3186 void getExportVars(BCCsizei *actualVarCount,
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003187 BCCsizei maxVarCount,
Zonr Chang932648d2010-10-13 22:23:56 +08003188 BCCvoid **vars) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003189 int varCount;
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003190
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003191 if (!mNeverCache && mCacheFd >= 0 && !mCacheNew) {
3192 varCount = static_cast<int>(mCacheHdr->exportVarsCount);
3193 if (actualVarCount)
3194 *actualVarCount = varCount;
3195 if (varCount > maxVarCount)
3196 varCount = maxVarCount;
3197 if (vars) {
3198 uint32_t *cachedVars = (uint32_t *)(mCacheMapAddr +
3199 mCacheHdr->exportVarsOffset);
3200
3201 for (int i = 0; i < varCount; i++) {
3202 *vars++ = (BCCvoid *)(reinterpret_cast<char *>(*cachedVars) +
3203 mCacheDiff);
3204 cachedVars++;
3205 }
3206 }
3207 return;
3208 }
3209
3210 varCount = mExportVars.size();
Zonr Chang932648d2010-10-13 22:23:56 +08003211 if (actualVarCount)
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003212 *actualVarCount = varCount;
Zonr Chang932648d2010-10-13 22:23:56 +08003213 if (varCount > maxVarCount)
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003214 varCount = maxVarCount;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003215 if (vars) {
Zonr Chang932648d2010-10-13 22:23:56 +08003216 for (ExportVarList::const_iterator I = mExportVars.begin(),
3217 E = mExportVars.end();
3218 I != E;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003219 I++) {
Zonr Chang932648d2010-10-13 22:23:56 +08003220 *vars++ = *I;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003221 }
3222 }
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003223
3224 return;
3225 }
3226
Zonr Chang932648d2010-10-13 22:23:56 +08003227 // Interface for bccGetExportFuncs()
3228 void getExportFuncs(BCCsizei *actualFuncCount,
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003229 BCCsizei maxFuncCount,
Zonr Chang932648d2010-10-13 22:23:56 +08003230 BCCvoid **funcs) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003231 int funcCount;
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003232
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003233 if (!mNeverCache && mCacheFd >= 0 && !mCacheNew) {
3234 funcCount = static_cast<int>(mCacheHdr->exportFuncsCount);
3235 if (actualFuncCount)
3236 *actualFuncCount = funcCount;
3237 if (funcCount > maxFuncCount)
3238 funcCount = maxFuncCount;
3239 if (funcs) {
3240 uint32_t *cachedFuncs = (uint32_t *)(mCacheMapAddr +
3241 mCacheHdr->exportFuncsOffset);
3242
3243 for (int i = 0; i < funcCount; i++) {
3244 *funcs++ = (BCCvoid *)(reinterpret_cast<char *>(*cachedFuncs) +
3245 mCacheDiff);
3246 cachedFuncs++;
3247 }
3248 }
3249 return;
3250 }
3251
3252 funcCount = mExportFuncs.size();
Zonr Chang932648d2010-10-13 22:23:56 +08003253 if (actualFuncCount)
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003254 *actualFuncCount = funcCount;
Zonr Chang932648d2010-10-13 22:23:56 +08003255 if (funcCount > maxFuncCount)
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003256 funcCount = maxFuncCount;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003257 if (funcs) {
Zonr Chang932648d2010-10-13 22:23:56 +08003258 for (ExportFuncList::const_iterator I = mExportFuncs.begin(),
3259 E = mExportFuncs.end();
3260 I != E;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003261 I++) {
Zonr Chang932648d2010-10-13 22:23:56 +08003262 *funcs++ = *I;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003263 }
3264 }
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003265
3266 return;
3267 }
3268
Zonr Chang932648d2010-10-13 22:23:56 +08003269 // Interface for bccGetPragmas()
3270 void getPragmas(BCCsizei *actualStringCount,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003271 BCCsizei maxStringCount,
Zonr Chang932648d2010-10-13 22:23:56 +08003272 BCCchar **strings) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003273 int stringCount;
3274 if (!mNeverCache && mCacheFd >= 0 && !mCacheNew) {
3275 if (actualStringCount)
3276 *actualStringCount = 0; // XXX
3277 return;
3278 }
3279
3280 stringCount = mPragmas.size() * 2;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003281
Zonr Chang932648d2010-10-13 22:23:56 +08003282 if (actualStringCount)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003283 *actualStringCount = stringCount;
Zonr Chang932648d2010-10-13 22:23:56 +08003284 if (stringCount > maxStringCount)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003285 stringCount = maxStringCount;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003286 if (strings) {
Zonr Chang932648d2010-10-13 22:23:56 +08003287 for (PragmaList::const_iterator it = mPragmas.begin();
3288 stringCount > 0;
3289 stringCount -= 2, it++) {
3290 *strings++ = const_cast<BCCchar*>(it->first.c_str());
3291 *strings++ = const_cast<BCCchar*>(it->second.c_str());
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003292 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003293 }
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003294
3295 return;
3296 }
3297
Zonr Chang932648d2010-10-13 22:23:56 +08003298 // Interface for bccGetFunctions()
3299 void getFunctions(BCCsizei *actualFunctionCount,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003300 BCCsizei maxFunctionCount,
Zonr Chang932648d2010-10-13 22:23:56 +08003301 BCCchar **functions) {
3302 if (mCodeEmitter.get())
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07003303 mCodeEmitter->getFunctionNames(actualFunctionCount,
3304 maxFunctionCount,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003305 functions);
3306 else
3307 *actualFunctionCount = 0;
3308
3309 return;
3310 }
3311
Zonr Chang932648d2010-10-13 22:23:56 +08003312 // Interface for bccGetFunctionBinary()
3313 void getFunctionBinary(BCCchar *function,
3314 BCCvoid **base,
3315 BCCsizei *length) {
3316 if (mCodeEmitter.get()) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003317 mCodeEmitter->getFunctionBinary(function, base, length);
3318 } else {
3319 *base = NULL;
3320 *length = 0;
3321 }
3322 return;
3323 }
3324
Zonr Chang932648d2010-10-13 22:23:56 +08003325 inline const llvm::Module *getModule() const {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003326 return mModule;
3327 }
3328
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003329 ~Compiler() {
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08003330 if (mCodeDataAddr != 0 && mCodeDataAddr != MAP_FAILED) {
3331 if (munmap(mCodeDataAddr, MaxCodeSize + MaxGlobalVarSize) < 0) {
3332 LOGE("munmap failed while releasing mCodeDataAddr\n");
3333 }
Shih-wei Liao1f45b862010-11-21 23:22:38 -08003334 if (mCacheMapAddr) {
3335 free(mCacheMapAddr);
3336 }
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08003337 }
Shih-wei Liao7f941bb2010-11-19 01:40:16 -08003338
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003339 delete mModule;
Zonr Chang932648d2010-10-13 22:23:56 +08003340 // llvm::llvm_shutdown();
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003341 delete mContext;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003342 return;
3343 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003344
3345 private:
3346 // Note: loader() and genCacheFile() go hand in hand
3347 void genCacheFile() {
3348 if (lseek(mCacheFd, 0, SEEK_SET) != 0) {
3349 LOGE("Unable to seek to 0: %s\n", strerror(errno));
3350 return;
3351 }
3352
3353 bool codeOffsetNeedPadding = false;
3354
3355 uint32_t offset = sizeof(oBCCHeader);
3356
3357 // BCC Cache File Header
3358 oBCCHeader *hdr = (oBCCHeader *)malloc(sizeof(oBCCHeader));
3359
3360 if (!hdr) {
3361 LOGE("Unable to allocate oBCCHeader.\n");
3362 return;
3363 }
3364
3365 // Magic Words
3366 memcpy(hdr->magic, OBCC_MAGIC, 4);
3367 memcpy(hdr->magicVersion, OBCC_MAGIC_VERS, 4);
3368
3369 // Timestamp
3370 hdr->sourceWhen = 0; // TODO(all)
3371 hdr->rslibWhen = 0; // TODO(all)
3372 hdr->libRSWhen = 0; // TODO(all)
3373 hdr->libbccWhen = 0; // TODO(all)
3374
3375 // Current Memory Address (Saved for Recalculation)
3376 hdr->cachedCodeDataAddr = reinterpret_cast<uint32_t>(mCodeDataAddr);
3377 hdr->rootAddr = reinterpret_cast<uint32_t>(lookup("root"));
3378 hdr->initAddr = reinterpret_cast<uint32_t>(lookup("init"));
3379
3380 // Relocation Table Offset and Entry Count
3381 hdr->relocOffset = sizeof(oBCCHeader);
Logan824dd0a2010-11-20 01:45:54 +08003382 hdr->relocCount = mCodeEmitter->getCachingRelocations().size();
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003383
Logan824dd0a2010-11-20 01:45:54 +08003384 offset += hdr->relocCount * (sizeof(oBCCRelocEntry));
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003385
3386 // Export Variable Table Offset and Entry Count
3387 hdr->exportVarsOffset = offset;
3388 hdr->exportVarsCount = mExportVars.size();
3389
3390 offset += hdr->exportVarsCount * sizeof(uint32_t);
3391
3392 // Export Function Table Offset and Entry Count
3393 hdr->exportFuncsOffset = offset;
3394 hdr->exportFuncsCount = mExportFuncs.size();
3395
3396 offset += hdr->exportFuncsCount * sizeof(uint32_t);
3397
3398 // Export Pragmas Table Offset and Entry Count
3399 hdr->exportPragmasOffset = offset;
3400 hdr->exportPragmasCount = 0; // TODO(all): mPragmas.size();
3401
3402 offset += hdr->exportPragmasCount * sizeof(uint32_t);
3403
3404 // Code Offset and Size
3405
Shih-wei Liao1f45b862010-11-21 23:22:38 -08003406 //#ifdef BCC_CODE_ADDR
3407 { // Always pad to the page boundary for now
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003408 long pagesize = sysconf(_SC_PAGESIZE);
3409
3410 if (offset % pagesize > 0) {
3411 codeOffsetNeedPadding = true;
3412 offset += pagesize - (offset % pagesize);
3413 }
3414 }
Shih-wei Liao1f45b862010-11-21 23:22:38 -08003415 /*#else
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003416 if (offset & 0x07) { // Ensure that offset aligned to 64-bit (8 byte).
3417 codeOffsetNeedPadding = true;
3418 offset += 0x08 - (offset & 0x07);
3419 }
Shih-wei Liao1f45b862010-11-21 23:22:38 -08003420 #endif*/
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003421
3422 hdr->codeOffset = offset;
3423 hdr->codeSize = MaxCodeSize;
3424
3425 offset += hdr->codeSize;
3426
3427 // Data (Global Variable) Offset and Size
3428 hdr->dataOffset = offset;
3429 hdr->dataSize = MaxGlobalVarSize;
3430
3431 offset += hdr->dataSize;
3432
3433 // Checksum
3434 hdr->checksum = 0; // Set Field checksum. TODO(all)
3435
3436 // Write Header
3437 sysWriteFully(mCacheFd, reinterpret_cast<char const *>(hdr),
3438 sizeof(oBCCHeader), "Write oBCC header");
3439
Logan824dd0a2010-11-20 01:45:54 +08003440 // Write Relocation Entry Table
3441 {
3442 size_t allocSize = hdr->relocCount * sizeof(oBCCRelocEntry);
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003443
Logan824dd0a2010-11-20 01:45:54 +08003444 oBCCRelocEntry const*records = &mCodeEmitter->getCachingRelocations()[0];
3445
3446 sysWriteFully(mCacheFd, reinterpret_cast<char const *>(records),
3447 allocSize, "Write Relocation Entries");
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003448 }
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003449
3450 // Write Export Variables Table
3451 {
3452 uint32_t *record, *ptr;
3453
3454 record = (uint32_t *)calloc(hdr->exportVarsCount, sizeof(uint32_t));
3455 ptr = record;
3456
3457 if (!record) {
3458 goto bail;
3459 }
3460
3461 for (ExportVarList::const_iterator I = mExportVars.begin(),
3462 E = mExportVars.end(); I != E; I++) {
3463 *ptr++ = reinterpret_cast<uint32_t>(*I);
3464 }
3465
3466 sysWriteFully(mCacheFd, reinterpret_cast<char const *>(record),
3467 hdr->exportVarsCount * sizeof(uint32_t),
3468 "Write ExportVars");
3469
3470 free(record);
3471 }
3472
3473 // Write Export Functions Table
3474 {
3475 uint32_t *record, *ptr;
3476
3477 record = (uint32_t *)calloc(hdr->exportFuncsCount, sizeof(uint32_t));
3478 ptr = record;
3479
3480 if (!record) {
3481 goto bail;
3482 }
3483
3484 for (ExportFuncList::const_iterator I = mExportFuncs.begin(),
3485 E = mExportFuncs.end(); I != E; I++) {
3486 *ptr++ = reinterpret_cast<uint32_t>(*I);
3487 }
3488
3489 sysWriteFully(mCacheFd, reinterpret_cast<char const *>(record),
3490 hdr->exportFuncsCount * sizeof(uint32_t),
3491 "Write ExportFuncs");
3492
3493 free(record);
3494 }
3495
3496
3497 // TODO(all): Write Export Pragmas Table
3498#if 0
3499#else
3500 // Note: As long as we have comment out export pragmas table code,
3501 // we have to seek the position to correct offset.
3502
3503 lseek(mCacheFd, hdr->codeOffset, SEEK_SET);
3504#endif
3505
3506 if (codeOffsetNeedPadding) {
3507 // requires additional padding
3508 lseek(mCacheFd, hdr->codeOffset, SEEK_SET);
3509 }
3510
3511 // Write Generated Code and Global Variable
3512 sysWriteFully(mCacheFd, mCodeDataAddr, MaxCodeSize + MaxGlobalVarSize,
3513 "Write code and global variable");
3514
3515 goto close_return;
3516
3517 bail:
3518 if (ftruncate(mCacheFd, 0) != 0) {
3519 LOGW("Warning: unable to truncate cache file: %s\n", strerror(errno));
3520 }
3521
3522 close_return:
3523 free(hdr);
3524 close(mCacheFd);
3525 mCacheFd = -1;
3526 return;
3527 }
3528
3529 // OpenCacheFile() returns fd of the cache file.
3530 // Input:
3531 // BCCchar *resName: Used to genCacheFileName()
3532 // bool createIfMissing: If false, turn off caching
3533 // Output:
3534 // returns fd: If -1: Failed
3535 // mCacheNew: If true, the returned fd is new. Otherwise, the fd is the
3536 // cache file's file descriptor
3537 // Note: openCacheFile() will check the cache file's validity,
3538 // such as Magic number, sourceWhen... dependencies.
3539 int openCacheFile(const BCCchar *resName, bool createIfMissing) {
3540 int fd, cc;
3541 struct stat fdStat, fileStat;
3542 bool readOnly = false;
3543
3544 char *cacheFileName = genCacheFileName(resName, ".oBCC");
3545
3546 mCacheNew = false;
3547
3548 retry:
3549 /*
3550 * Try to open the cache file. If we've been asked to,
3551 * create it if it doesn't exist.
3552 */
3553 fd = createIfMissing ? open(cacheFileName, O_CREAT|O_RDWR, 0644) : -1;
3554 if (fd < 0) {
3555 fd = open(cacheFileName, O_RDONLY, 0);
3556 if (fd < 0) {
3557 if (createIfMissing) {
Shih-wei Liao30a51502010-11-22 03:23:30 -08003558 LOGW("Can't open bcc-cache '%s': %s\n",
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003559 cacheFileName, strerror(errno));
Shih-wei Liao30a51502010-11-22 03:23:30 -08003560 mNeverCache = true;
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003561 }
3562 return fd;
3563 }
3564 readOnly = true;
3565 }
3566
3567 /*
3568 * Grab an exclusive lock on the cache file. If somebody else is
3569 * working on it, we'll block here until they complete.
3570 */
3571 LOGV("bcc: locking cache file %s (fd=%d, boot=%d)\n",
3572 cacheFileName, fd);
3573
3574 cc = flock(fd, LOCK_EX | LOCK_NB);
3575 if (cc != 0) {
3576 LOGD("bcc: sleeping on flock(%s)\n", cacheFileName);
3577 cc = flock(fd, LOCK_EX);
3578 }
3579
3580 if (cc != 0) {
3581 LOGE("Can't lock bcc cache '%s': %d\n", cacheFileName, cc);
3582 close(fd);
3583 return -1;
3584 }
3585 LOGV("bcc: locked cache file\n");
3586
3587 /*
3588 * Check to see if the fd we opened and locked matches the file in
3589 * the filesystem. If they don't, then somebody else unlinked ours
3590 * and created a new file, and we need to use that one instead. (If
3591 * we caught them between the unlink and the create, we'll get an
3592 * ENOENT from the file stat.)
3593 */
3594 cc = fstat(fd, &fdStat);
3595 if (cc != 0) {
3596 LOGE("Can't stat open file '%s'\n", cacheFileName);
3597 LOGV("bcc: unlocking cache file %s\n", cacheFileName);
3598 goto close_fail;
3599 }
3600 cc = stat(cacheFileName, &fileStat);
3601 if (cc != 0 ||
3602 fdStat.st_dev != fileStat.st_dev || fdStat.st_ino != fileStat.st_ino) {
3603 LOGD("bcc: our open cache file is stale; sleeping and retrying\n");
3604 LOGV("bcc: unlocking cache file %s\n", cacheFileName);
3605 flock(fd, LOCK_UN);
3606 close(fd);
3607 usleep(250 * 1000); // if something is hosed, don't peg machine
3608 goto retry;
3609 }
3610
3611 /*
3612 * We have the correct file open and locked. If the file size is zero,
3613 * then it was just created by us, and we want to fill in some fields
3614 * in the "bcc" header and set "mCacheNew". Otherwise, we want to
3615 * verify that the fields in the header match our expectations, and
3616 * reset the file if they don't.
3617 */
3618 if (fdStat.st_size == 0) {
3619 if (readOnly) { // The device is readOnly --> close_fail
3620 LOGW("bcc: file has zero length and isn't writable\n");
3621 goto close_fail;
3622 }
3623 /*cc = createEmptyHeader(fd);
3624 if (cc != 0)
3625 goto close_fail;
3626 */
3627 mCacheNew = true;
3628 LOGV("bcc: successfully initialized new cache file\n");
3629 } else {
3630 // Calculate sourceWhen
3631 // XXX
3632 uint32_t sourceWhen = 0;
3633 uint32_t rslibWhen = 0;
3634 uint32_t libRSWhen = 0;
3635 uint32_t libbccWhen = 0;
3636 if (!checkHeaderAndDependencies(fd,
3637 sourceWhen,
3638 rslibWhen,
3639 libRSWhen,
3640 libbccWhen)) {
3641 // If checkHeaderAndDependencies returns 0: FAILED
3642 // Will truncate the file and retry to createIfMissing the file
3643
3644 if (readOnly) { // Shouldn't be readonly.
3645 /*
3646 * We could unlink and rewrite the file if we own it or
3647 * the "sticky" bit isn't set on the directory. However,
3648 * we're not able to truncate it, which spoils things. So,
3649 * give up now.
3650 */
3651 if (createIfMissing) {
3652 LOGW("Cached file %s is stale and not writable\n",
3653 cacheFileName);
3654 }
3655 goto close_fail;
3656 }
3657
3658 /*
3659 * If we truncate the existing file before unlinking it, any
3660 * process that has it mapped will fail when it tries to touch
3661 * the pages? Probably OK because we use MAP_PRIVATE.
3662 */
3663 LOGD("oBCC file is stale or bad; removing and retrying (%s)\n",
3664 cacheFileName);
3665 if (ftruncate(fd, 0) != 0) {
3666 LOGW("Warning: unable to truncate cache file '%s': %s\n",
3667 cacheFileName, strerror(errno));
3668 /* keep going */
3669 }
3670 if (unlink(cacheFileName) != 0) {
3671 LOGW("Warning: unable to remove cache file '%s': %d %s\n",
3672 cacheFileName, errno, strerror(errno));
3673 /* keep going; permission failure should probably be fatal */
3674 }
3675 LOGV("bcc: unlocking cache file %s\n", cacheFileName);
3676 flock(fd, LOCK_UN);
3677 close(fd);
3678 goto retry;
3679 } else {
3680 // Got cacheFile! Good to go.
3681 LOGV("Good cache file\n");
3682 }
3683 }
3684
3685 assert(fd >= 0);
3686 return fd;
3687
3688 close_fail:
3689 flock(fd, LOCK_UN);
3690 close(fd);
3691 return -1;
3692 } // End of openCacheFile()
3693
3694 char *genCacheFileName(const char *fileName, const char *subFileName) {
3695 char nameBuf[512];
3696 static const char kCachePath[] = "bcc-cache";
3697 char absoluteFile[sizeof(nameBuf)];
3698 const size_t kBufLen = sizeof(nameBuf) - 1;
3699 const char *dataRoot;
3700 char *cp;
3701
3702 // Get the absolute path of the raw/***.bc file.
3703 absoluteFile[0] = '\0';
3704 if (fileName[0] != '/') {
3705 /*
3706 * Generate the absolute path. This doesn't do everything it
3707 * should, e.g. if filename is "./out/whatever" it doesn't crunch
3708 * the leading "./" out, but it'll do.
3709 */
3710 if (getcwd(absoluteFile, kBufLen) == NULL) {
3711 LOGE("Can't get CWD while opening raw/***.bc file\n");
3712 return NULL;
3713 }
3714 // TODO(srhines): strncat() is a bit dangerous
3715 strncat(absoluteFile, "/", kBufLen);
3716 }
3717 strncat(absoluteFile, fileName, kBufLen);
3718
3719 if (subFileName != NULL) {
3720 strncat(absoluteFile, "/", kBufLen);
3721 strncat(absoluteFile, subFileName, kBufLen);
3722 }
3723
3724 /* Turn the path into a flat filename by replacing
3725 * any slashes after the first one with '@' characters.
3726 */
3727 cp = absoluteFile + 1;
3728 while (*cp != '\0') {
3729 if (*cp == '/') {
3730 *cp = '@';
3731 }
3732 cp++;
3733 }
3734
3735 /* Build the name of the cache directory.
3736 */
3737 dataRoot = getenv("ANDROID_DATA");
3738 if (dataRoot == NULL)
3739 dataRoot = "/data";
3740 snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCachePath);
3741
3742 /* Tack on the file name for the actual cache file path.
3743 */
3744 strncat(nameBuf, absoluteFile, kBufLen);
3745
3746 LOGV("Cache file for '%s' '%s' is '%s'\n", fileName, subFileName, nameBuf);
3747 return strdup(nameBuf);
3748 }
3749
3750 /*
3751 * Read the oBCC header, verify it, then read the dependent section
3752 * and verify that data as well.
3753 *
3754 * On successful return, the file will be seeked immediately past the
3755 * oBCC header.
3756 */
3757 bool checkHeaderAndDependencies(int fd,
3758 uint32_t sourceWhen,
3759 uint32_t rslibWhen,
3760 uint32_t libRSWhen,
3761 uint32_t libbccWhen) {
3762 ssize_t actual;
3763 oBCCHeader optHdr;
3764 uint32_t val;
3765 uint8_t const *magic, *magicVer;
3766
3767 /*
3768 * Start at the start. The "bcc" header, when present, will always be
3769 * the first thing in the file.
3770 */
3771 if (lseek(fd, 0, SEEK_SET) != 0) {
3772 LOGE("bcc: failed to seek to start of file: %s\n", strerror(errno));
3773 goto bail;
3774 }
3775
3776 /*
3777 * Read and do trivial verification on the bcc header. The header is
3778 * always in host byte order.
3779 */
3780 actual = read(fd, &optHdr, sizeof(optHdr));
3781 if (actual < 0) {
3782 LOGE("bcc: failed reading bcc header: %s\n", strerror(errno));
3783 goto bail;
3784 } else if (actual != sizeof(optHdr)) {
3785 LOGE("bcc: failed reading bcc header (got %d of %zd)\n",
3786 (int) actual, sizeof(optHdr));
3787 goto bail;
3788 }
3789
3790 magic = optHdr.magic;
3791 if (memcmp(magic, OBCC_MAGIC, 4) != 0) {
3792 /* not an oBCC file, or previous attempt was interrupted */
3793 LOGD("bcc: incorrect opt magic number (0x%02x %02x %02x %02x)\n",
3794 magic[0], magic[1], magic[2], magic[3]);
3795 goto bail;
3796 }
3797
3798 magicVer = optHdr.magicVersion;
3799 if (memcmp(magic+4, OBCC_MAGIC_VERS, 4) != 0) {
3800 LOGW("bcc: stale oBCC version (0x%02x %02x %02x %02x)\n",
3801 magicVer[0], magicVer[1], magicVer[2], magicVer[3]);
3802 goto bail;
3803 }
3804
3805 /*
3806 * Do the header flags match up with what we want?
3807 *
3808 * This is useful because it allows us to automatically regenerate
3809 * a file when settings change (e.g. verification is now mandatory),
3810 * but can cause difficulties if the thing we depend upon
3811 * were handled differently than the current options specify.
3812 *
3813 * So, for now, we essentially ignore "expectVerify" and "expectOpt"
3814 * by limiting the match mask.
3815 *
3816 * The only thing we really can't handle is incorrect byte-ordering.
3817 */
3818
3819 val = optHdr.sourceWhen;
3820 if (val && (val != sourceWhen)) {
3821 LOGI("bcc: source file mod time mismatch (%08x vs %08x)\n",
3822 val, sourceWhen);
3823 goto bail;
3824 }
3825 val = optHdr.rslibWhen;
3826 if (val && (val != rslibWhen)) {
3827 LOGI("bcc: rslib file mod time mismatch (%08x vs %08x)\n",
3828 val, rslibWhen);
3829 goto bail;
3830 }
3831 val = optHdr.libRSWhen;
3832 if (val && (val != libRSWhen)) {
3833 LOGI("bcc: libRS file mod time mismatch (%08x vs %08x)\n",
3834 val, libRSWhen);
3835 goto bail;
3836 }
3837 val = optHdr.libbccWhen;
3838 if (val && (val != libbccWhen)) {
3839 LOGI("bcc: libbcc file mod time mismatch (%08x vs %08x)\n",
3840 val, libbccWhen);
3841 goto bail;
3842 }
3843
3844 return true;
3845
3846 bail:
3847 return false;
3848 }
3849
Zonr Chang932648d2010-10-13 22:23:56 +08003850};
3851// End of Class Compiler
3852////////////////////////////////////////////////////////////////////////////////
3853
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003854
3855bool Compiler::GlobalInitialized = false;
3856
Loganad7e8e12010-11-22 20:43:43 +08003857bool Compiler::BccCodeAddrTaken = false;
3858
Zonr Chang932648d2010-10-13 22:23:56 +08003859// Code generation optimization level for the compiler
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003860llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
3861
3862std::string Compiler::Triple;
3863
3864std::string Compiler::CPU;
3865
3866std::vector<std::string> Compiler::Features;
3867
Zonr Chang932648d2010-10-13 22:23:56 +08003868// The named of metadata node that pragma resides (should be synced with
3869// slang.cpp)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003870const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
3871
Zonr Chang932648d2010-10-13 22:23:56 +08003872// The named of metadata node that export variable name resides (should be
3873// synced with slang_rs_metadata.h)
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07003874const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
3875
Zonr Chang932648d2010-10-13 22:23:56 +08003876// The named of metadata node that export function name resides (should be
3877// synced with slang_rs_metadata.h)
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07003878const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
3879
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003880struct BCCscript {
Zonr Chang932648d2010-10-13 22:23:56 +08003881 //////////////////////////////////////////////////////////////////////////////
3882 // Part I. Compiler
3883 //////////////////////////////////////////////////////////////////////////////
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003884 Compiler compiler;
3885
Zonr Chang932648d2010-10-13 22:23:56 +08003886 void registerSymbolCallback(BCCSymbolLookupFn pFn, BCCvoid *pContext) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003887 compiler.registerSymbolCallback(pFn, pContext);
3888 }
3889
Zonr Chang932648d2010-10-13 22:23:56 +08003890 //////////////////////////////////////////////////////////////////////////////
3891 // Part II. Logistics & Error handling
3892 //////////////////////////////////////////////////////////////////////////////
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003893 BCCscript() {
3894 bccError = BCC_NO_ERROR;
3895 }
3896
3897 ~BCCscript() {
3898 }
3899
3900 void setError(BCCenum error) {
3901 if (bccError == BCC_NO_ERROR && error != BCC_NO_ERROR) {
3902 bccError = error;
3903 }
3904 }
3905
3906 BCCenum getError() {
3907 BCCenum result = bccError;
3908 bccError = BCC_NO_ERROR;
3909 return result;
3910 }
3911
3912 BCCenum bccError;
3913};
3914
3915
3916extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003917BCCscript *bccCreateScript() {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003918 return new BCCscript();
3919}
3920
3921extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003922BCCenum bccGetError(BCCscript *script) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003923 return script->getError();
3924}
3925
3926extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003927void bccDeleteScript(BCCscript *script) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003928 delete script;
3929}
3930
3931extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003932void bccRegisterSymbolCallback(BCCscript *script,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003933 BCCSymbolLookupFn pFn,
Zonr Chang932648d2010-10-13 22:23:56 +08003934 BCCvoid *pContext) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003935 script->registerSymbolCallback(pFn, pContext);
3936}
3937
3938extern "C"
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003939int bccReadModule(BCCscript *script,
Zonr Changdbee68b2010-10-22 05:02:16 +08003940 BCCvoid *module) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003941 return script->compiler.readModule(reinterpret_cast<llvm::Module*>(module));
Zonr Changdbee68b2010-10-22 05:02:16 +08003942}
3943
3944extern "C"
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003945int bccReadBC(BCCscript *script,
3946 const BCCchar *bitcode,
3947 BCCint size,
3948 const BCCchar *resName) {
3949 return script->compiler.readBC(bitcode, size, resName);
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003950}
3951
3952extern "C"
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003953void bccLinkBC(BCCscript *script,
Zonr Chang97f5e612010-10-22 20:38:26 +08003954 const BCCchar *bitcode,
3955 BCCint size) {
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003956 script->compiler.linkBC(bitcode, size);
Zonr Chang97f5e612010-10-22 20:38:26 +08003957}
3958
3959extern "C"
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003960void bccLoadBinary(BCCscript *script) {
3961 int result = script->compiler.loader();
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07003962 if (result)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003963 script->setError(BCC_INVALID_OPERATION);
3964}
3965
3966extern "C"
Shih-wei Liao7c5a5f72010-11-08 01:59:13 -08003967void bccCompileBC(BCCscript *script) {
3968 {
3969#if defined(__arm__)
3970 android::StopWatch compileTimer("RenderScript compile time");
3971#endif
3972 int result = script->compiler.compile();
3973 if (result)
3974 script->setError(BCC_INVALID_OPERATION);
3975 }
3976}
3977
3978extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003979void bccGetScriptInfoLog(BCCscript *script,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003980 BCCsizei maxLength,
Zonr Chang932648d2010-10-13 22:23:56 +08003981 BCCsizei *length,
3982 BCCchar *infoLog) {
3983 char *message = script->compiler.getErrorMessage();
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003984 int messageLength = strlen(message) + 1;
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07003985 if (length)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07003986 *length = messageLength;
3987
3988 if (infoLog && maxLength > 0) {
3989 int trimmedLength = maxLength < messageLength ? maxLength : messageLength;
3990 memcpy(infoLog, message, trimmedLength);
3991 infoLog[trimmedLength] = 0;
3992 }
3993}
3994
3995extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08003996void bccGetScriptLabel(BCCscript *script,
3997 const BCCchar *name,
3998 BCCvoid **address) {
3999 void *value = script->compiler.lookup(name);
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07004000 if (value)
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004001 *address = value;
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07004002 else
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004003 script->setError(BCC_INVALID_VALUE);
4004}
4005
4006extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08004007void bccGetExportVars(BCCscript *script,
4008 BCCsizei *actualVarCount,
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07004009 BCCsizei maxVarCount,
Zonr Chang932648d2010-10-13 22:23:56 +08004010 BCCvoid **vars) {
Shih-wei Liaoabd1e3d2010-04-28 01:47:00 -07004011 script->compiler.getExportVars(actualVarCount, maxVarCount, vars);
4012}
4013
4014extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08004015void bccGetExportFuncs(BCCscript *script,
4016 BCCsizei *actualFuncCount,
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07004017 BCCsizei maxFuncCount,
Zonr Chang932648d2010-10-13 22:23:56 +08004018 BCCvoid **funcs) {
Shih-wei Liao6bfd5422010-05-07 05:20:22 -07004019 script->compiler.getExportFuncs(actualFuncCount, maxFuncCount, funcs);
4020}
4021
4022extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08004023void bccGetPragmas(BCCscript *script,
4024 BCCsizei *actualStringCount,
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07004025 BCCsizei maxStringCount,
Zonr Chang932648d2010-10-13 22:23:56 +08004026 BCCchar **strings) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004027 script->compiler.getPragmas(actualStringCount, maxStringCount, strings);
4028}
4029
4030extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08004031void bccGetFunctions(BCCscript *script,
4032 BCCsizei *actualFunctionCount,
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07004033 BCCsizei maxFunctionCount,
Zonr Chang932648d2010-10-13 22:23:56 +08004034 BCCchar **functions) {
Shih-wei Liao3cf39d12010-04-29 19:30:51 -07004035 script->compiler.getFunctions(actualFunctionCount,
4036 maxFunctionCount,
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004037 functions);
4038}
4039
4040extern "C"
Zonr Chang932648d2010-10-13 22:23:56 +08004041void bccGetFunctionBinary(BCCscript *script,
4042 BCCchar *function,
4043 BCCvoid **base,
4044 BCCsizei *length) {
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004045 script->compiler.getFunctionBinary(function, base, length);
4046}
4047
4048struct BCCtype {
Zonr Chang932648d2010-10-13 22:23:56 +08004049 const Compiler *compiler;
4050 const llvm::Type *t;
Shih-wei Liao77ed6142010-04-07 12:21:42 -07004051};
4052
Zonr Chang932648d2010-10-13 22:23:56 +08004053} // namespace bcc