913cadc57e2524ad7414cbcde7600d8b5fe60c58
[WebKit-https.git] / Source / JavaScriptCore / dfg / DFGPlan.cpp
1 /*
2  * Copyright (C) 2013, 2014 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 "DFGPlan.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "DFGArgumentsSimplificationPhase.h"
32 #include "DFGBackwardsPropagationPhase.h"
33 #include "DFGByteCodeParser.h"
34 #include "DFGCFAPhase.h"
35 #include "DFGCFGSimplificationPhase.h"
36 #include "DFGCPSRethreadingPhase.h"
37 #include "DFGCSEPhase.h"
38 #include "DFGConstantFoldingPhase.h"
39 #include "DFGCriticalEdgeBreakingPhase.h"
40 #include "DFGDCEPhase.h"
41 #include "DFGFailedFinalizer.h"
42 #include "DFGFixupPhase.h"
43 #include "DFGGraphSafepoint.h"
44 #include "DFGIntegerCheckCombiningPhase.h"
45 #include "DFGInvalidationPointInjectionPhase.h"
46 #include "DFGJITCompiler.h"
47 #include "DFGLICMPhase.h"
48 #include "DFGLivenessAnalysisPhase.h"
49 #include "DFGLoopPreHeaderCreationPhase.h"
50 #include "DFGOSRAvailabilityAnalysisPhase.h"
51 #include "DFGOSREntrypointCreationPhase.h"
52 #include "DFGObjectAllocationSinkingPhase.h"
53 #include "DFGPhantomCanonicalizationPhase.h"
54 #include "DFGPhantomRemovalPhase.h"
55 #include "DFGPredictionInjectionPhase.h"
56 #include "DFGPredictionPropagationPhase.h"
57 #include "DFGPutLocalSinkingPhase.h"
58 #include "DFGResurrectionForValidationPhase.h"
59 #include "DFGSSAConversionPhase.h"
60 #include "DFGSSALoweringPhase.h"
61 #include "DFGStackLayoutPhase.h"
62 #include "DFGStaticExecutionCountEstimationPhase.h"
63 #include "DFGStoreBarrierElisionPhase.h"
64 #include "DFGStrengthReductionPhase.h"
65 #include "DFGStructureRegistrationPhase.h"
66 #include "DFGTierUpCheckInjectionPhase.h"
67 #include "DFGTypeCheckHoistingPhase.h"
68 #include "DFGUnificationPhase.h"
69 #include "DFGValidate.h"
70 #include "DFGVirtualRegisterAllocationPhase.h"
71 #include "DFGWatchpointCollectionPhase.h"
72 #include "Debugger.h"
73 #include "JSCInlines.h"
74 #include "OperandsInlines.h"
75 #include "ProfilerDatabase.h"
76 #include <wtf/CurrentTime.h>
77
78 #if ENABLE(FTL_JIT)
79 #include "FTLCapabilities.h"
80 #include "FTLCompile.h"
81 #include "FTLFail.h"
82 #include "FTLLink.h"
83 #include "FTLLowerDFGToLLVM.h"
84 #include "FTLState.h"
85 #include "InitializeLLVM.h"
86 #endif
87
88 namespace JSC { namespace DFG {
89
90 static void dumpAndVerifyGraph(Graph& graph, const char* text)
91 {
92     GraphDumpMode modeForFinalValidate = DumpGraph;
93     if (verboseCompilationEnabled(graph.m_plan.mode)) {
94         dataLog(text, "\n");
95         graph.dump();
96         modeForFinalValidate = DontDumpGraph;
97     }
98     if (validationEnabled())
99         validate(graph, modeForFinalValidate);
100 }
101
102 static Profiler::CompilationKind profilerCompilationKindForMode(CompilationMode mode)
103 {
104     switch (mode) {
105     case InvalidCompilationMode:
106         RELEASE_ASSERT_NOT_REACHED();
107         return Profiler::DFG;
108     case DFGMode:
109         return Profiler::DFG;
110     case FTLMode:
111         return Profiler::FTL;
112     case FTLForOSREntryMode:
113         return Profiler::FTLForOSREntry;
114     }
115     RELEASE_ASSERT_NOT_REACHED();
116     return Profiler::DFG;
117 }
118
119 Plan::Plan(PassRefPtr<CodeBlock> passedCodeBlock, CodeBlock* profiledDFGCodeBlock,
120     CompilationMode mode, unsigned osrEntryBytecodeIndex,
121     const Operands<JSValue>& mustHandleValues)
122     : vm(*passedCodeBlock->vm())
123     , codeBlock(passedCodeBlock)
124     , profiledDFGCodeBlock(profiledDFGCodeBlock)
125     , mode(mode)
126     , osrEntryBytecodeIndex(osrEntryBytecodeIndex)
127     , mustHandleValues(mustHandleValues)
128     , compilation(codeBlock->vm()->m_perBytecodeProfiler ? adoptRef(new Profiler::Compilation(codeBlock->vm()->m_perBytecodeProfiler->ensureBytecodesFor(codeBlock.get()), profilerCompilationKindForMode(mode))) : 0)
129     , inlineCallFrames(adoptRef(new InlineCallFrameSet()))
130     , identifiers(codeBlock.get())
131     , weakReferences(codeBlock.get())
132     , willTryToTierUp(false)
133     , stage(Preparing)
134 {
135 }
136
137 Plan::~Plan()
138 {
139 }
140
141 bool Plan::reportCompileTimes() const
142 {
143     return Options::reportCompileTimes()
144         || (Options::reportFTLCompileTimes() && isFTL(mode));
145 }
146
147 void Plan::compileInThread(LongLivedState& longLivedState, ThreadData* threadData)
148 {
149     this->threadData = threadData;
150     
151     double before = 0;
152     CString codeBlockName;
153     if (reportCompileTimes()) {
154         before = currentTimeMS();
155         codeBlockName = toCString(*codeBlock);
156     }
157     
158     SamplingRegion samplingRegion("DFG Compilation (Plan)");
159     CompilationScope compilationScope;
160
161     if (logCompilationChanges(mode))
162         dataLog("DFG(Plan) compiling ", *codeBlock, " with ", mode, ", number of instructions = ", codeBlock->instructionCount(), "\n");
163
164     CompilationPath path = compileInThreadImpl(longLivedState);
165
166     RELEASE_ASSERT(path == CancelPath || finalizer);
167     RELEASE_ASSERT((path == CancelPath) == (stage == Cancelled));
168     
169     if (reportCompileTimes()) {
170         const char* pathName;
171         switch (path) {
172         case FailPath:
173             pathName = "N/A (fail)";
174             break;
175         case DFGPath:
176             pathName = "DFG";
177             break;
178         case FTLPath:
179             pathName = "FTL";
180             break;
181         case CancelPath:
182             pathName = "Cancelled";
183             break;
184         default:
185             RELEASE_ASSERT_NOT_REACHED();
186 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
187             pathName = "";
188 #endif
189             break;
190         }
191         double now = currentTimeMS();
192         dataLog("Optimized ", codeBlockName, " using ", mode, " with ", pathName, " into ", finalizer ? finalizer->codeSize() : 0, " bytes in ", now - before, " ms");
193         if (path == FTLPath)
194             dataLog(" (DFG: ", beforeFTL - before, ", LLVM: ", now - beforeFTL, ")");
195         dataLog(".\n");
196     }
197 }
198
199 Plan::CompilationPath Plan::compileInThreadImpl(LongLivedState& longLivedState)
200 {
201     if (verboseCompilationEnabled(mode) && osrEntryBytecodeIndex != UINT_MAX) {
202         dataLog("\n");
203         dataLog("Compiler must handle OSR entry from bc#", osrEntryBytecodeIndex, " with values: ", mustHandleValues, "\n");
204         dataLog("\n");
205     }
206     
207     Graph dfg(vm, *this, longLivedState);
208     
209     if (!parse(dfg)) {
210         finalizer = adoptPtr(new FailedFinalizer(*this));
211         return FailPath;
212     }
213     
214     // By this point the DFG bytecode parser will have potentially mutated various tables
215     // in the CodeBlock. This is a good time to perform an early shrink, which is more
216     // powerful than a late one. It's safe to do so because we haven't generated any code
217     // that references any of the tables directly, yet.
218     codeBlock->shrinkToFit(CodeBlock::EarlyShrink);
219
220     if (validationEnabled())
221         validate(dfg);
222     
223     performCPSRethreading(dfg);
224     performUnification(dfg);
225     performPredictionInjection(dfg);
226     
227     performStaticExecutionCountEstimation(dfg);
228     
229     if (mode == FTLForOSREntryMode) {
230         bool result = performOSREntrypointCreation(dfg);
231         if (!result) {
232             finalizer = adoptPtr(new FailedFinalizer(*this));
233             return FailPath;
234         }
235         performCPSRethreading(dfg);
236     }
237     
238     if (validationEnabled())
239         validate(dfg);
240     
241     performBackwardsPropagation(dfg);
242     performPredictionPropagation(dfg);
243     performFixup(dfg);
244     performStructureRegistration(dfg);
245     performInvalidationPointInjection(dfg);
246     performTypeCheckHoisting(dfg);
247     
248     dfg.m_fixpointState = FixpointNotConverged;
249     
250     // For now we're back to avoiding a fixpoint. Note that we've ping-ponged on this decision
251     // many times. For maximum throughput, it's best to fixpoint. But the throughput benefit is
252     // small and not likely to show up in FTL anyway. On the other hand, not fixpointing means
253     // that the compiler compiles more quickly. We want the third tier to compile quickly, which
254     // not fixpointing accomplishes; and the fourth tier shouldn't need a fixpoint.
255     if (validationEnabled())
256         validate(dfg);
257         
258     performStrengthReduction(dfg);
259     performLocalCSE(dfg);
260     performArgumentsSimplification(dfg);
261     performCPSRethreading(dfg);
262     performCFA(dfg);
263     performConstantFolding(dfg);
264     bool changed = false;
265     changed |= performCFGSimplification(dfg);
266     changed |= performLocalCSE(dfg);
267     
268     if (validationEnabled())
269         validate(dfg);
270     
271     performCPSRethreading(dfg);
272     if (changed) {
273         performCFA(dfg);
274         performConstantFolding(dfg);
275     }
276     
277     // If we're doing validation, then run some analyses, to give them an opportunity
278     // to self-validate. Now is as good a time as any to do this.
279     if (validationEnabled()) {
280         dfg.m_dominators.computeIfNecessary(dfg);
281         dfg.m_naturalLoops.computeIfNecessary(dfg);
282         dfg.m_prePostNumbering.computeIfNecessary(dfg);
283     }
284
285     switch (mode) {
286     case DFGMode: {
287         dfg.m_fixpointState = FixpointConverged;
288     
289         performTierUpCheckInjection(dfg);
290
291         performStoreBarrierElision(dfg);
292         performPhantomRemoval(dfg);
293         performCPSRethreading(dfg);
294         performDCE(dfg);
295         performStackLayout(dfg);
296         performVirtualRegisterAllocation(dfg);
297         performWatchpointCollection(dfg);
298         dumpAndVerifyGraph(dfg, "Graph after optimization:");
299         
300         JITCompiler dataFlowJIT(dfg);
301         if (codeBlock->codeType() == FunctionCode) {
302             dataFlowJIT.compileFunction();
303             dataFlowJIT.linkFunction();
304         } else {
305             dataFlowJIT.compile();
306             dataFlowJIT.link();
307         }
308         
309         return DFGPath;
310     }
311     
312     case FTLMode:
313     case FTLForOSREntryMode: {
314 #if ENABLE(FTL_JIT)
315         if (FTL::canCompile(dfg) == FTL::CannotCompile) {
316             finalizer = adoptPtr(new FailedFinalizer(*this));
317             return FailPath;
318         }
319         
320         performPhantomRemoval(dfg); // Reduce the graph size a bit.
321         performCriticalEdgeBreaking(dfg);
322         performLoopPreHeaderCreation(dfg);
323         performCPSRethreading(dfg);
324         performSSAConversion(dfg);
325         performSSALowering(dfg);
326         performPutLocalSinking(dfg);
327         performGlobalCSE(dfg);
328         performLivenessAnalysis(dfg);
329         performCFA(dfg);
330         performConstantFolding(dfg);
331         performPhantomCanonicalization(dfg); // Reduce the graph size a lot.
332         changed = false;
333         changed |= performStrengthReduction(dfg);
334         if (Options::enableObjectAllocationSinking()) {
335             changed |= performCriticalEdgeBreaking(dfg);
336             changed |= performObjectAllocationSinking(dfg);
337         }
338         if (changed) {
339             // State-at-tail and state-at-head will be invalid if we did strength reduction since
340             // it might increase live ranges.
341             performLivenessAnalysis(dfg);
342             performCFA(dfg);
343             performConstantFolding(dfg);
344         }
345         performLICM(dfg);
346         performPhantomCanonicalization(dfg);
347         performIntegerCheckCombining(dfg);
348         performGlobalCSE(dfg);
349         
350         // At this point we're not allowed to do any further code motion because our reasoning
351         // about code motion assumes that it's OK to insert GC points in random places.
352         dfg.m_fixpointState = FixpointConverged;
353         
354         performStoreBarrierElision(dfg);
355         performPhantomCanonicalization(dfg);
356         performLivenessAnalysis(dfg);
357         performCFA(dfg);
358         if (Options::validateFTLOSRExitLiveness())
359             performResurrectionForValidation(dfg);
360         performDCE(dfg); // We rely on this to kill dead code that won't be recognized as dead by LLVM.
361         performStackLayout(dfg);
362         performLivenessAnalysis(dfg);
363         performOSRAvailabilityAnalysis(dfg);
364         performWatchpointCollection(dfg);
365         
366         dumpAndVerifyGraph(dfg, "Graph just before FTL lowering:");
367         
368         bool haveLLVM;
369         Safepoint::Result safepointResult;
370         {
371             GraphSafepoint safepoint(dfg, safepointResult);
372             haveLLVM = initializeLLVM();
373         }
374         if (safepointResult.didGetCancelled())
375             return CancelPath;
376         
377         if (!haveLLVM) {
378             finalizer = adoptPtr(new FailedFinalizer(*this));
379             return FailPath;
380         }
381             
382         FTL::State state(dfg);
383         FTL::lowerDFGToLLVM(state);
384         
385         if (reportCompileTimes())
386             beforeFTL = currentTimeMS();
387         
388         if (Options::llvmAlwaysFailsBeforeCompile()) {
389             FTL::fail(state);
390             return FTLPath;
391         }
392         
393         FTL::compile(state, safepointResult);
394         if (safepointResult.didGetCancelled())
395             return CancelPath;
396         
397         if (Options::llvmAlwaysFailsBeforeLink()) {
398             FTL::fail(state);
399             return FTLPath;
400         }
401
402         if (state.jitCode->stackmaps.stackSize() > Options::llvmMaxStackSize()) {
403             FTL::fail(state);
404             return FTLPath;
405         }
406
407         FTL::link(state);
408         return FTLPath;
409 #else
410         RELEASE_ASSERT_NOT_REACHED();
411         return FailPath;
412 #endif // ENABLE(FTL_JIT)
413     }
414         
415     default:
416         RELEASE_ASSERT_NOT_REACHED();
417         return FailPath;
418     }
419 }
420
421 bool Plan::isStillValid()
422 {
423     CodeBlock* replacement = codeBlock->replacement();
424     if (!replacement)
425         return false;
426     // FIXME: This is almost certainly not necessary. There's no way for the baseline
427     // code to be replaced during a compilation, except if we delete the plan, in which
428     // case we wouldn't be here.
429     // https://bugs.webkit.org/show_bug.cgi?id=132707
430     if (codeBlock->alternative() != replacement->baselineVersion())
431         return false;
432     if (!watchpoints.areStillValid())
433         return false;
434     return true;
435 }
436
437 void Plan::reallyAdd(CommonData* commonData)
438 {
439     watchpoints.reallyAdd(codeBlock.get(), *commonData);
440     identifiers.reallyAdd(vm, commonData);
441     weakReferences.reallyAdd(vm, commonData);
442     transitions.reallyAdd(vm, commonData);
443     writeBarriers.trigger(vm);
444 }
445
446 void Plan::notifyCompiling()
447 {
448     stage = Compiling;
449 }
450
451 void Plan::notifyCompiled()
452 {
453     stage = Compiled;
454 }
455
456 void Plan::notifyReady()
457 {
458     callback->compilationDidBecomeReadyAsynchronously(codeBlock.get());
459     stage = Ready;
460 }
461
462 CompilationResult Plan::finalizeWithoutNotifyingCallback()
463 {
464     if (!isStillValid())
465         return CompilationInvalidated;
466
467     bool result;
468     if (codeBlock->codeType() == FunctionCode)
469         result = finalizer->finalizeFunction();
470     else
471         result = finalizer->finalize();
472     
473     if (!result)
474         return CompilationFailed;
475     
476     reallyAdd(codeBlock->jitCode()->dfgCommon());
477     
478     return CompilationSuccessful;
479 }
480
481 void Plan::finalizeAndNotifyCallback()
482 {
483     callback->compilationDidComplete(codeBlock.get(), finalizeWithoutNotifyingCallback());
484 }
485
486 CompilationKey Plan::key()
487 {
488     return CompilationKey(codeBlock->alternative(), mode);
489 }
490
491 void Plan::checkLivenessAndVisitChildren(SlotVisitor& visitor, CodeBlockSet& codeBlocks)
492 {
493     if (!isKnownToBeLiveDuringGC())
494         return;
495     
496     for (unsigned i = mustHandleValues.size(); i--;)
497         visitor.appendUnbarrieredValue(&mustHandleValues[i]);
498     
499     codeBlocks.mark(codeBlock->alternative());
500     codeBlocks.mark(codeBlock.get());
501     codeBlocks.mark(profiledDFGCodeBlock.get());
502     
503     weakReferences.visitChildren(visitor);
504     writeBarriers.visitChildren(visitor);
505     transitions.visitChildren(visitor);
506 }
507
508 bool Plan::isKnownToBeLiveDuringGC()
509 {
510     if (stage == Cancelled)
511         return false;
512     if (!Heap::isMarked(codeBlock->ownerExecutable()))
513         return false;
514     if (!codeBlock->alternative()->isKnownToBeLiveDuringGC())
515         return false;
516     if (!!profiledDFGCodeBlock && !profiledDFGCodeBlock->isKnownToBeLiveDuringGC())
517         return false;
518     return true;
519 }
520
521 void Plan::cancel()
522 {
523     codeBlock = nullptr;
524     profiledDFGCodeBlock = nullptr;
525     mustHandleValues.clear();
526     compilation = nullptr;
527     finalizer.clear();
528     inlineCallFrames = nullptr;
529     watchpoints = DesiredWatchpoints();
530     identifiers = DesiredIdentifiers();
531     weakReferences = DesiredWeakReferences();
532     writeBarriers = DesiredWriteBarriers();
533     transitions = DesiredTransitions();
534     callback = nullptr;
535     stage = Cancelled;
536 }
537
538 } } // namespace JSC::DFG
539
540 #endif // ENABLE(DFG_JIT)
541