Enhance the MacroAssembler and LinkBuffer to support pointer profiling.
[WebKit-https.git] / Source / JavaScriptCore / jit / JITMathIC.h
1 /*
2  * Copyright (C) 2016-2018 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 #pragma once
27
28 #if ENABLE(JIT)
29
30 #include "ArithProfile.h"
31 #include "CCallHelpers.h"
32 #include "JITAddGenerator.h"
33 #include "JITMathICInlineResult.h"
34 #include "JITMulGenerator.h"
35 #include "JITNegGenerator.h"
36 #include "JITSubGenerator.h"
37 #include "LinkBuffer.h"
38 #include "Repatch.h"
39
40 namespace JSC {
41
42 class LinkBuffer;
43
44 struct MathICGenerationState {
45     MacroAssembler::Label fastPathStart;
46     MacroAssembler::Label fastPathEnd;
47     MacroAssembler::Label slowPathStart;
48     MacroAssembler::Call slowPathCall;
49     MacroAssembler::JumpList slowPathJumps;
50     bool shouldSlowPathRepatch;
51 };
52
53 #define ENABLE_MATH_IC_STATS 0
54
55 template <typename GeneratorType, bool(*isProfileEmpty)(ArithProfile&)>
56 class JITMathIC {
57     WTF_MAKE_FAST_ALLOCATED;
58 public:
59     JITMathIC(ArithProfile* arithProfile)
60         : m_arithProfile(arithProfile)
61     {
62     }
63
64     CodeLocationLabel doneLocation() { return m_inlineStart.labelAtOffset(m_inlineSize); }
65     CodeLocationLabel slowPathStartLocation() { return m_inlineStart.labelAtOffset(m_deltaFromStartToSlowPathStart); }
66     CodeLocationCall slowPathCallLocation() { return m_inlineStart.callAtOffset(m_deltaFromStartToSlowPathCallLocation); }
67     
68     bool generateInline(CCallHelpers& jit, MathICGenerationState& state, bool shouldEmitProfiling = true)
69     {
70 #if CPU(ARM_TRADITIONAL)
71         // FIXME: Remove this workaround once the proper fixes are landed.
72         // [ARM] Disable Inline Caching on ARMv7 traditional until proper fix
73         // https://bugs.webkit.org/show_bug.cgi?id=159759
74         return false;
75 #endif
76
77         state.fastPathStart = jit.label();
78         size_t startSize = jit.m_assembler.buffer().codeSize();
79
80         if (m_arithProfile) {
81             if (isProfileEmpty(*m_arithProfile)) {
82                 // It looks like the MathIC has yet to execute. We don't want to emit code in this
83                 // case for a couple reasons. First, the operation may never execute, so if we don't emit
84                 // code, it's a win. Second, if the operation does execute, we can emit better code
85                 // once we have an idea about the types.
86                 state.slowPathJumps.append(jit.patchableJump());
87                 size_t inlineSize = jit.m_assembler.buffer().codeSize() - startSize;
88                 ASSERT_UNUSED(inlineSize, static_cast<ptrdiff_t>(inlineSize) <= MacroAssembler::patchableJumpSize());
89                 state.shouldSlowPathRepatch = true;
90                 state.fastPathEnd = jit.label();
91                 ASSERT(!m_generateFastPathOnRepatch); // We should have gathered some observed type info about the types before trying to regenerate again.
92                 m_generateFastPathOnRepatch = true;
93                 return true;
94             }
95         }
96
97         JITMathICInlineResult result = m_generator.generateInline(jit, state, m_arithProfile);
98
99         switch (result) {
100         case JITMathICInlineResult::GeneratedFastPath: {
101             size_t inlineSize = jit.m_assembler.buffer().codeSize() - startSize;
102             if (static_cast<ptrdiff_t>(inlineSize) < MacroAssembler::patchableJumpSize()) {
103                 size_t nopsToEmitInBytes = MacroAssembler::patchableJumpSize() - inlineSize;
104                 jit.emitNops(nopsToEmitInBytes);
105             }
106             state.shouldSlowPathRepatch = true;
107             state.fastPathEnd = jit.label();
108             return true;
109         }
110         case JITMathICInlineResult::GenerateFullSnippet: {
111             MacroAssembler::JumpList endJumpList;
112             bool result = m_generator.generateFastPath(jit, endJumpList, state.slowPathJumps, m_arithProfile, shouldEmitProfiling);
113             if (result) {
114                 state.fastPathEnd = jit.label();
115                 state.shouldSlowPathRepatch = false;
116                 endJumpList.link(&jit);
117                 return true;
118             }
119             return false;
120         }
121         case JITMathICInlineResult::DontGenerate: {
122             return false;
123         }
124         default:
125             ASSERT_NOT_REACHED();
126         }
127
128         return false;
129     }
130
131     void generateOutOfLine(CodeBlock* codeBlock, FunctionPtr callReplacement)
132     {
133         auto linkJumpToOutOfLineSnippet = [&] () {
134             CCallHelpers jit(codeBlock);
135             auto jump = jit.jump();
136             // We don't need a nop sled here because nobody should be jumping into the middle of an IC.
137             bool needsBranchCompaction = false;
138             RELEASE_ASSERT(jit.m_assembler.buffer().codeSize() <= static_cast<size_t>(m_inlineSize));
139             LinkBuffer linkBuffer(jit, m_inlineStart.dataLocation(), jit.m_assembler.buffer().codeSize(), JITCompilationMustSucceed, needsBranchCompaction);
140             RELEASE_ASSERT(linkBuffer.isValid());
141             linkBuffer.link(jump, CodeLocationLabel(m_code.code()));
142             FINALIZE_CODE(linkBuffer, NoPtrTag, "JITMathIC: linking constant jump to out of line stub");
143         };
144
145         auto replaceCall = [&] () {
146             ftlThunkAwareRepatchCall(codeBlock, slowPathCallLocation(), callReplacement);
147         };
148
149         bool shouldEmitProfiling = !JITCode::isOptimizingJIT(codeBlock->jitType());
150
151         if (m_generateFastPathOnRepatch) {
152
153             CCallHelpers jit(codeBlock);
154             MathICGenerationState generationState;
155             bool generatedInline = generateInline(jit, generationState, shouldEmitProfiling);
156
157             // We no longer want to try to regenerate the fast path.
158             m_generateFastPathOnRepatch = false;
159
160             if (generatedInline) {
161                 auto jumpToDone = jit.jump();
162
163                 LinkBuffer linkBuffer(jit, codeBlock, JITCompilationCanFail);
164                 if (!linkBuffer.didFailToAllocate()) {
165                     linkBuffer.link(generationState.slowPathJumps, slowPathStartLocation());
166                     linkBuffer.link(jumpToDone, doneLocation());
167
168                     m_code = FINALIZE_CODE_FOR(
169                         codeBlock, linkBuffer, NoPtrTag, "JITMathIC: generating out of line fast IC snippet");
170
171                     if (!generationState.shouldSlowPathRepatch) {
172                         // We won't need to regenerate, so we can wire the slow path call
173                         // to a non repatching variant.
174                         replaceCall();
175                     }
176
177                     linkJumpToOutOfLineSnippet();
178
179                     return;
180                 }
181             }
182             
183             // We weren't able to generate an out of line fast path.
184             // We just generate the snippet in its full generality.
185         }
186
187         // We rewire to the alternate regardless of whether or not we can allocate the out of line path
188         // because if we fail allocating the out of line path, we don't want to waste time trying to
189         // allocate it in the future.
190         replaceCall();
191
192         {
193             CCallHelpers jit(codeBlock);
194
195             MacroAssembler::JumpList endJumpList; 
196             MacroAssembler::JumpList slowPathJumpList; 
197
198             bool emittedFastPath = m_generator.generateFastPath(jit, endJumpList, slowPathJumpList, m_arithProfile, shouldEmitProfiling);
199             if (!emittedFastPath)
200                 return;
201             endJumpList.append(jit.jump());
202
203             LinkBuffer linkBuffer(jit, codeBlock, JITCompilationCanFail);
204             if (linkBuffer.didFailToAllocate())
205                 return;
206
207             linkBuffer.link(endJumpList, doneLocation());
208             linkBuffer.link(slowPathJumpList, slowPathStartLocation());
209
210             m_code = FINALIZE_CODE_FOR(
211                 codeBlock, linkBuffer, NoPtrTag, "JITMathIC: generating out of line IC snippet");
212         }
213
214         linkJumpToOutOfLineSnippet();
215     }
216
217     void finalizeInlineCode(const MathICGenerationState& state, LinkBuffer& linkBuffer)
218     {
219         CodeLocationLabel start = linkBuffer.locationOf(state.fastPathStart, NoPtrTag);
220         m_inlineStart = start;
221
222         m_inlineSize = MacroAssembler::differenceBetweenCodePtr(
223             start, linkBuffer.locationOf(state.fastPathEnd, NoPtrTag));
224         ASSERT(m_inlineSize > 0);
225
226         m_deltaFromStartToSlowPathCallLocation = MacroAssembler::differenceBetweenCodePtr(
227             start, linkBuffer.locationOf(state.slowPathCall));
228         m_deltaFromStartToSlowPathStart = MacroAssembler::differenceBetweenCodePtr(
229             start, linkBuffer.locationOf(state.slowPathStart, SlowPathPtrTag));
230     }
231
232     ArithProfile* arithProfile() const { return m_arithProfile; }
233
234 #if ENABLE(MATH_IC_STATS)
235     size_t m_generatedCodeSize { 0 };
236     size_t codeSize() const
237     {
238         size_t result = m_generatedCodeSize;
239         if (m_code)
240             result += m_code.size();
241         return result;
242     }
243 #endif
244
245     ArithProfile* m_arithProfile;
246     MacroAssemblerCodeRef m_code;
247     CodeLocationLabel m_inlineStart;
248     int32_t m_inlineSize;
249     int32_t m_deltaFromStartToSlowPathCallLocation;
250     int32_t m_deltaFromStartToSlowPathStart;
251     bool m_generateFastPathOnRepatch { false };
252     GeneratorType m_generator;
253 };
254
255 inline bool isBinaryProfileEmpty(ArithProfile& arithProfile)
256 {
257     return arithProfile.lhsObservedType().isEmpty() || arithProfile.rhsObservedType().isEmpty();
258 }
259 template <typename GeneratorType>
260 class JITBinaryMathIC : public JITMathIC<GeneratorType, isBinaryProfileEmpty> {
261 public:
262     JITBinaryMathIC(ArithProfile* arithProfile)
263         : JITMathIC<GeneratorType, isBinaryProfileEmpty>(arithProfile)
264     {
265     }
266 };
267
268 typedef JITBinaryMathIC<JITAddGenerator> JITAddIC;
269 typedef JITBinaryMathIC<JITMulGenerator> JITMulIC;
270 typedef JITBinaryMathIC<JITSubGenerator> JITSubIC;
271
272
273 inline bool isUnaryProfileEmpty(ArithProfile& arithProfile)
274 {
275     return arithProfile.lhsObservedType().isEmpty();
276 }
277 template <typename GeneratorType>
278 class JITUnaryMathIC : public JITMathIC<GeneratorType, isUnaryProfileEmpty> {
279 public:
280     JITUnaryMathIC(ArithProfile* arithProfile)
281         : JITMathIC<GeneratorType, isUnaryProfileEmpty>(arithProfile)
282     {
283     }
284 };
285
286 typedef JITUnaryMathIC<JITNegGenerator> JITNegIC;
287
288 } // namespace JSC
289
290 #endif // ENABLE(JIT)