326d20d4477bb203e5aa096757cf6ce404ac1c27
[WebKit-https.git] / Source / JavaScriptCore / assembler / LinkBuffer.cpp
1 /*
2  * Copyright (C) 2012-2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "LinkBuffer.h"
28
29 #if ENABLE(ASSEMBLER)
30
31 #include "CodeBlock.h"
32 #include "JITCode.h"
33 #include "JSCInlines.h"
34 #include "Options.h"
35 #include "VM.h"
36 #include <wtf/CompilationThread.h>
37
38 namespace JSC {
39
40 bool shouldDumpDisassemblyFor(CodeBlock* codeBlock)
41 {
42     if (JITCode::isOptimizingJIT(codeBlock->jitType()) && Options::dumpDFGDisassembly())
43         return true;
44     return Options::dumpDisassembly();
45 }
46
47 LinkBuffer::CodeRef LinkBuffer::finalizeCodeWithoutDisassembly()
48 {
49     performFinalization();
50     
51     ASSERT(m_didAllocate);
52     if (m_executableMemory)
53         return CodeRef(m_executableMemory);
54     
55     return CodeRef::createSelfManagedCodeRef(MacroAssemblerCodePtr(m_code));
56 }
57
58 LinkBuffer::CodeRef LinkBuffer::finalizeCodeWithDisassembly(const char* format, ...)
59 {
60     CodeRef result = finalizeCodeWithoutDisassembly();
61
62     if (m_alreadyDisassembled)
63         return result;
64     
65     StringPrintStream out;
66     out.printf("Generated JIT code for ");
67     va_list argList;
68     va_start(argList, format);
69     out.vprintf(format, argList);
70     va_end(argList);
71     out.printf(":\n");
72
73     out.printf("    Code at [%p, %p):\n", result.code().executableAddress(), static_cast<char*>(result.code().executableAddress()) + result.size());
74     
75     CString header = out.toCString();
76     
77     if (Options::asyncDisassembly()) {
78         disassembleAsynchronously(header, result, m_size, "    ");
79         return result;
80     }
81     
82     dataLog(header);
83     disassemble(result.code(), m_size, "    ", WTF::dataFile());
84     
85     return result;
86 }
87
88 #if ENABLE(BRANCH_COMPACTION)
89 static ALWAYS_INLINE void recordLinkOffsets(AssemblerData& assemblerData, int32_t regionStart, int32_t regionEnd, int32_t offset)
90 {
91     int32_t ptr = regionStart / sizeof(int32_t);
92     const int32_t end = regionEnd / sizeof(int32_t);
93     int32_t* offsets = reinterpret_cast_ptr<int32_t*>(assemblerData.buffer());
94     while (ptr < end)
95         offsets[ptr++] = offset;
96 }
97
98 template <typename InstructionType>
99 void LinkBuffer::copyCompactAndLinkCode(MacroAssembler& macroAssembler, void* ownerUID, JITCompilationEffort effort)
100 {
101     allocate(macroAssembler, ownerUID, effort);
102     const size_t initialSize = macroAssembler.m_assembler.codeSize();
103     if (didFailToAllocate())
104         return;
105
106     Vector<LinkRecord, 0, UnsafeVectorOverflow>& jumpsToLink = macroAssembler.jumpsToLink();
107     m_assemblerStorage = macroAssembler.m_assembler.buffer().releaseAssemblerData();
108     uint8_t* inData = reinterpret_cast<uint8_t*>(m_assemblerStorage.buffer());
109
110     AssemblerData outBuffer(m_size);
111
112     uint8_t* outData = reinterpret_cast<uint8_t*>(outBuffer.buffer());
113     uint8_t* codeOutData = reinterpret_cast<uint8_t*>(m_code);
114
115     int readPtr = 0;
116     int writePtr = 0;
117     unsigned jumpCount = jumpsToLink.size();
118     if (m_shouldPerformBranchCompaction) {
119         for (unsigned i = 0; i < jumpCount; ++i) {
120             int offset = readPtr - writePtr;
121             ASSERT(!(offset & 1));
122                 
123             // Copy the instructions from the last jump to the current one.
124             size_t regionSize = jumpsToLink[i].from() - readPtr;
125             InstructionType* copySource = reinterpret_cast_ptr<InstructionType*>(inData + readPtr);
126             InstructionType* copyEnd = reinterpret_cast_ptr<InstructionType*>(inData + readPtr + regionSize);
127             InstructionType* copyDst = reinterpret_cast_ptr<InstructionType*>(outData + writePtr);
128             ASSERT(!(regionSize % 2));
129             ASSERT(!(readPtr % 2));
130             ASSERT(!(writePtr % 2));
131             while (copySource != copyEnd)
132                 *copyDst++ = *copySource++;
133             recordLinkOffsets(m_assemblerStorage, readPtr, jumpsToLink[i].from(), offset);
134             readPtr += regionSize;
135             writePtr += regionSize;
136                 
137             // Calculate absolute address of the jump target, in the case of backwards
138             // branches we need to be precise, forward branches we are pessimistic
139             const uint8_t* target;
140             if (jumpsToLink[i].to() >= jumpsToLink[i].from())
141                 target = codeOutData + jumpsToLink[i].to() - offset; // Compensate for what we have collapsed so far
142             else
143                 target = codeOutData + jumpsToLink[i].to() - executableOffsetFor(jumpsToLink[i].to());
144                 
145             JumpLinkType jumpLinkType = MacroAssembler::computeJumpType(jumpsToLink[i], codeOutData + writePtr, target);
146             // Compact branch if we can...
147             if (MacroAssembler::canCompact(jumpsToLink[i].type())) {
148                 // Step back in the write stream
149                 int32_t delta = MacroAssembler::jumpSizeDelta(jumpsToLink[i].type(), jumpLinkType);
150                 if (delta) {
151                     writePtr -= delta;
152                     recordLinkOffsets(m_assemblerStorage, jumpsToLink[i].from() - delta, readPtr, readPtr - writePtr);
153                 }
154             }
155             jumpsToLink[i].setFrom(writePtr);
156         }
157     } else {
158         if (!ASSERT_DISABLED) {
159             for (unsigned i = 0; i < jumpCount; ++i)
160                 ASSERT(!MacroAssembler::canCompact(jumpsToLink[i].type()));
161         }
162     }
163     // Copy everything after the last jump
164     memcpy(outData + writePtr, inData + readPtr, initialSize - readPtr);
165     recordLinkOffsets(m_assemblerStorage, readPtr, initialSize, readPtr - writePtr);
166         
167     for (unsigned i = 0; i < jumpCount; ++i) {
168         uint8_t* location = codeOutData + jumpsToLink[i].from();
169         uint8_t* target = codeOutData + jumpsToLink[i].to() - executableOffsetFor(jumpsToLink[i].to());
170         MacroAssembler::link(jumpsToLink[i], outData + jumpsToLink[i].from(), location, target);
171     }
172
173     jumpsToLink.clear();
174
175     size_t compactSize = writePtr + initialSize - readPtr;
176     if (m_executableMemory) {
177         m_size = compactSize;
178         m_executableMemory->shrink(m_size);
179     } else {
180         size_t nopSizeInBytes = initialSize - compactSize;
181         bool isCopyingToExecutableMemory = false;
182         MacroAssembler::AssemblerType_T::fillNops(outData + compactSize, nopSizeInBytes, isCopyingToExecutableMemory);
183     }
184
185     performJITMemcpy(m_code, outData, m_size);
186
187 #if DUMP_LINK_STATISTICS
188     dumpLinkStatistics(m_code, initialSize, m_size);
189 #endif
190 #if DUMP_CODE
191     dumpCode(m_code, m_size);
192 #endif
193 }
194 #endif
195
196
197 void LinkBuffer::linkCode(MacroAssembler& macroAssembler, void* ownerUID, JITCompilationEffort effort)
198 {
199 #if !ENABLE(BRANCH_COMPACTION)
200 #if defined(ASSEMBLER_HAS_CONSTANT_POOL) && ASSEMBLER_HAS_CONSTANT_POOL
201     macroAssembler.m_assembler.buffer().flushConstantPool(false);
202 #endif
203     allocate(macroAssembler, ownerUID, effort);
204     if (!m_didAllocate)
205         return;
206     ASSERT(m_code);
207     AssemblerBuffer& buffer = macroAssembler.m_assembler.buffer();
208 #if CPU(ARM_TRADITIONAL)
209     macroAssembler.m_assembler.prepareExecutableCopy(m_code);
210 #endif
211     performJITMemcpy(m_code, buffer.data(), buffer.codeSize());
212 #if CPU(MIPS)
213     macroAssembler.m_assembler.relocateJumps(buffer.data(), m_code);
214 #endif
215 #elif CPU(ARM_THUMB2)
216     copyCompactAndLinkCode<uint16_t>(macroAssembler, ownerUID, effort);
217 #elif CPU(ARM64)
218     copyCompactAndLinkCode<uint32_t>(macroAssembler, ownerUID, effort);
219 #endif // !ENABLE(BRANCH_COMPACTION)
220
221     m_linkTasks = WTFMove(macroAssembler.m_linkTasks);
222 }
223
224 void LinkBuffer::allocate(MacroAssembler& macroAssembler, void* ownerUID, JITCompilationEffort effort)
225 {
226     size_t initialSize = macroAssembler.m_assembler.codeSize();
227     if (m_code) {
228         if (initialSize > m_size)
229             return;
230         
231         size_t nopsToFillInBytes = m_size - initialSize;
232         macroAssembler.emitNops(nopsToFillInBytes);
233         m_didAllocate = true;
234         return;
235     }
236     
237     ASSERT(m_vm != nullptr);
238     m_executableMemory = m_vm->executableAllocator.allocate(*m_vm, initialSize, ownerUID, effort);
239     if (!m_executableMemory)
240         return;
241     m_code = m_executableMemory->start();
242     m_size = initialSize;
243     m_didAllocate = true;
244 }
245
246 void LinkBuffer::performFinalization()
247 {
248     for (auto& task : m_linkTasks)
249         task->run(*this);
250
251 #ifndef NDEBUG
252     ASSERT(!isCompilationThread());
253     ASSERT(!m_completed);
254     ASSERT(isValid());
255     m_completed = true;
256 #endif
257     
258     MacroAssembler::cacheFlush(code(), m_size);
259 }
260
261 #if DUMP_LINK_STATISTICS
262 void LinkBuffer::dumpLinkStatistics(void* code, size_t initializeSize, size_t finalSize)
263 {
264     static unsigned linkCount = 0;
265     static unsigned totalInitialSize = 0;
266     static unsigned totalFinalSize = 0;
267     linkCount++;
268     totalInitialSize += initialSize;
269     totalFinalSize += finalSize;
270     dataLogF("link %p: orig %u, compact %u (delta %u, %.2f%%)\n", 
271             code, static_cast<unsigned>(initialSize), static_cast<unsigned>(finalSize),
272             static_cast<unsigned>(initialSize - finalSize),
273             100.0 * (initialSize - finalSize) / initialSize);
274     dataLogF("\ttotal %u: orig %u, compact %u (delta %u, %.2f%%)\n", 
275             linkCount, totalInitialSize, totalFinalSize, totalInitialSize - totalFinalSize,
276             100.0 * (totalInitialSize - totalFinalSize) / totalInitialSize);
277 }
278 #endif
279
280 #if DUMP_CODE
281 void LinkBuffer::dumpCode(void* code, size_t size)
282 {
283 #if CPU(ARM_THUMB2)
284     // Dump the generated code in an asm file format that can be assembled and then disassembled
285     // for debugging purposes. For example, save this output as jit.s:
286     //   gcc -arch armv7 -c jit.s
287     //   otool -tv jit.o
288     static unsigned codeCount = 0;
289     unsigned short* tcode = static_cast<unsigned short*>(code);
290     size_t tsize = size / sizeof(short);
291     char nameBuf[128];
292     snprintf(nameBuf, sizeof(nameBuf), "_jsc_jit%u", codeCount++);
293     dataLogF("\t.syntax unified\n"
294             "\t.section\t__TEXT,__text,regular,pure_instructions\n"
295             "\t.globl\t%s\n"
296             "\t.align 2\n"
297             "\t.code 16\n"
298             "\t.thumb_func\t%s\n"
299             "# %p\n"
300             "%s:\n", nameBuf, nameBuf, code, nameBuf);
301         
302     for (unsigned i = 0; i < tsize; i++)
303         dataLogF("\t.short\t0x%x\n", tcode[i]);
304 #elif CPU(ARM_TRADITIONAL)
305     //   gcc -c jit.s
306     //   objdump -D jit.o
307     static unsigned codeCount = 0;
308     unsigned int* tcode = static_cast<unsigned int*>(code);
309     size_t tsize = size / sizeof(unsigned int);
310     char nameBuf[128];
311     snprintf(nameBuf, sizeof(nameBuf), "_jsc_jit%u", codeCount++);
312     dataLogF("\t.globl\t%s\n"
313             "\t.align 4\n"
314             "\t.code 32\n"
315             "\t.text\n"
316             "# %p\n"
317             "%s:\n", nameBuf, code, nameBuf);
318
319     for (unsigned i = 0; i < tsize; i++)
320         dataLogF("\t.long\t0x%x\n", tcode[i]);
321 #endif
322 }
323 #endif
324
325 } // namespace JSC
326
327 #endif // ENABLE(ASSEMBLER)
328
329