v8  3.25.30(node0.11.13)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
codegen.cc
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 #include "v8.h"
29 
30 #include "bootstrapper.h"
31 #include "codegen.h"
32 #include "compiler.h"
33 #include "cpu-profiler.h"
34 #include "debug.h"
35 #include "prettyprinter.h"
36 #include "rewriter.h"
37 #include "runtime.h"
38 #include "stub-cache.h"
39 
40 namespace v8 {
41 namespace internal {
42 
43 #define __ ACCESS_MASM(masm_)
44 
45 #ifdef DEBUG
46 
47 Comment::Comment(MacroAssembler* masm, const char* msg)
48  : masm_(masm), msg_(msg) {
49  __ RecordComment(msg);
50 }
51 
52 
53 Comment::~Comment() {
54  if (msg_[0] == '[') __ RecordComment("]");
55 }
56 
57 #endif // DEBUG
58 
59 #undef __
60 
61 
62 void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) {
63  bool print_source = false;
64  bool print_ast = false;
65  const char* ftype;
66 
67  if (info->isolate()->bootstrapper()->IsActive()) {
68  print_source = FLAG_print_builtin_source;
69  print_ast = FLAG_print_builtin_ast;
70  ftype = "builtin";
71  } else {
72  print_source = FLAG_print_source;
73  print_ast = FLAG_print_ast;
74  ftype = "user-defined";
75  }
76 
77  if (FLAG_trace_codegen || print_source || print_ast) {
78  PrintF("[generating %s code for %s function: ", kind, ftype);
79  if (info->IsStub()) {
80  const char* name =
81  CodeStub::MajorName(info->code_stub()->MajorKey(), true);
82  PrintF("%s", name == NULL ? "<unknown>" : name);
83  } else {
84  PrintF("%s", info->function()->debug_name()->ToCString().get());
85  }
86  PrintF("]\n");
87  }
88 
89 #ifdef DEBUG
90  if (!info->IsStub() && print_source) {
91  PrintF("--- Source from AST ---\n%s\n",
92  PrettyPrinter(info->zone()).PrintProgram(info->function()));
93  }
94 
95  if (!info->IsStub() && print_ast) {
96  PrintF("--- AST ---\n%s\n",
97  AstPrinter(info->zone()).PrintProgram(info->function()));
98  }
99 #endif // DEBUG
100 }
101 
102 
103 Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm,
106  Isolate* isolate = info->isolate();
107 
108  // Allocate and install the code.
109  CodeDesc desc;
110  bool is_crankshafted =
111  Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION ||
112  info->IsStub();
113  masm->GetCode(&desc);
115  isolate->factory()->NewCode(desc, flags, masm->CodeObject(),
116  false, is_crankshafted,
117  info->prologue_offset());
118  isolate->counters()->total_compiled_code_size()->Increment(
119  code->instruction_size());
120  isolate->heap()->IncrementCodeGeneratedBytes(is_crankshafted,
121  code->instruction_size());
122  return code;
123 }
124 
125 
126 void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) {
127 #ifdef ENABLE_DISASSEMBLER
128  AllowDeferredHandleDereference allow_deference_for_print_code;
129  bool print_code = info->isolate()->bootstrapper()->IsActive()
130  ? FLAG_print_builtin_code
131  : (FLAG_print_code ||
132  (info->IsStub() && FLAG_print_code_stubs) ||
133  (info->IsOptimizing() && FLAG_print_opt_code));
134  if (print_code) {
135  // Print the source code if available.
136  FunctionLiteral* function = info->function();
137  bool print_source = code->kind() == Code::OPTIMIZED_FUNCTION ||
138  code->kind() == Code::FUNCTION;
139 
140  CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer());
141  if (print_source) {
142  Handle<Script> script = info->script();
143  if (!script->IsUndefined() && !script->source()->IsUndefined()) {
144  PrintF(tracing_scope.file(), "--- Raw source ---\n");
146  StringCharacterStream stream(String::cast(script->source()),
147  &op,
148  function->start_position());
149  // fun->end_position() points to the last character in the stream. We
150  // need to compensate by adding one to calculate the length.
151  int source_len =
152  function->end_position() - function->start_position() + 1;
153  for (int i = 0; i < source_len; i++) {
154  if (stream.HasMore()) {
155  PrintF(tracing_scope.file(), "%c", stream.GetNext());
156  }
157  }
158  PrintF(tracing_scope.file(), "\n\n");
159  }
160  }
161  if (info->IsOptimizing()) {
162  if (FLAG_print_unopt_code) {
163  PrintF(tracing_scope.file(), "--- Unoptimized code ---\n");
164  info->closure()->shared()->code()->Disassemble(
165  function->debug_name()->ToCString().get(), tracing_scope.file());
166  }
167  PrintF(tracing_scope.file(), "--- Optimized code ---\n");
168  PrintF(tracing_scope.file(),
169  "optimization_id = %d\n", info->optimization_id());
170  } else {
171  PrintF(tracing_scope.file(), "--- Code ---\n");
172  }
173  if (print_source) {
174  PrintF(tracing_scope.file(),
175  "source_position = %d\n", function->start_position());
176  }
177  if (info->IsStub()) {
178  CodeStub::Major major_key = info->code_stub()->MajorKey();
179  code->Disassemble(CodeStub::MajorName(major_key, false),
180  tracing_scope.file());
181  } else {
182  code->Disassemble(function->debug_name()->ToCString().get(),
183  tracing_scope.file());
184  }
185  PrintF(tracing_scope.file(), "--- End code ---\n");
186  }
187 #endif // ENABLE_DISASSEMBLER
188 }
189 
190 
191 bool CodeGenerator::ShouldGenerateLog(Isolate* isolate, Expression* type) {
192  ASSERT(type != NULL);
193  if (!isolate->logger()->is_logging() &&
194  !isolate->cpu_profiler()->is_profiling()) {
195  return false;
196  }
197  Handle<String> name = Handle<String>::cast(type->AsLiteral()->value());
198  if (FLAG_log_regexp) {
199  if (name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("regexp")))
200  return true;
201  }
202  return false;
203 }
204 
205 
206 bool CodeGenerator::RecordPositions(MacroAssembler* masm,
207  int pos,
208  bool right_here) {
209  if (pos != RelocInfo::kNoPosition) {
210  masm->positions_recorder()->RecordStatementPosition(pos);
211  masm->positions_recorder()->RecordPosition(pos);
212  if (right_here) {
213  return masm->positions_recorder()->WriteRecordedPositions();
214  }
215  }
216  return false;
217 }
218 
219 
220 void ArgumentsAccessStub::Generate(MacroAssembler* masm) {
221  switch (type_) {
222  case READ_ELEMENT:
223  GenerateReadElement(masm);
224  break;
225  case NEW_SLOPPY_FAST:
226  GenerateNewSloppyFast(masm);
227  break;
228  case NEW_SLOPPY_SLOW:
229  GenerateNewSloppySlow(masm);
230  break;
231  case NEW_STRICT:
232  GenerateNewStrict(masm);
233  break;
234  }
235 }
236 
237 
238 int CEntryStub::MinorKey() {
239  int result = (save_doubles_ == kSaveFPRegs) ? 1 : 0;
240  ASSERT(result_size_ == 1 || result_size_ == 2);
241 #ifdef _WIN64
242  return result | ((result_size_ == 1) ? 0 : 2);
243 #else
244  return result;
245 #endif
246 }
247 
248 
249 } } // namespace v8::internal
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter NULL
void PrintF(const char *format,...)
Definition: v8utils.cc:40
CodeTracer * GetCodeTracer()
Definition: isolate.cc:2229
bool is_logging()
Definition: log.h:354
Handle< Script > script() const
Definition: compiler.h:83
Bootstrapper * bootstrapper()
Definition: isolate.h:858
uint32_t Flags
Definition: objects.h:5184
Isolate * isolate() const
Definition: compiler.h:67
#define ASSERT(condition)
Definition: checks.h:329
bool IsOptimizing() const
Definition: compiler.h:231
Factory * factory()
Definition: isolate.h:995
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in name
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in only print modified registers Don t break for ASM_UNIMPLEMENTED_BREAK macros print stack trace when an illegal exception is thrown randomize hashes to avoid predictable hash Fixed seed to use to hash property Print the time it takes to deserialize the snapshot testing_bool_flag testing_int_flag string flag tmp file in which to serialize heap Print the time it takes to lazily compile hydrogen code stubs concurrent_recompilation concurrent_sweeping Print usage including flags
void GetCode(CodeDesc *desc)
FunctionLiteral * function() const
Definition: compiler.h:77
#define __
Definition: codegen.cc:43
#define STATIC_ASCII_VECTOR(x)
Definition: utils.h:570
Handle< JSFunction > closure() const
Definition: compiler.h:81
HydrogenCodeStub * code_stub() const
Definition: compiler.h:84
void IncrementCodeGeneratedBytes(bool is_crankshafted, int size)
Definition: heap.h:1734
CpuProfiler * cpu_profiler() const
Definition: isolate.h:984
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra code(assertions) for debugging") DEFINE_bool(code_comments
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function info
Handle< Code > NewCode(const CodeDesc &desc, Code::Flags flags, Handle< Object > self_reference, bool immovable=false, bool crankshafted=false, int prologue_offset=Code::kPrologueOffsetNotSet)
Definition: factory.cc:1291
Counters * counters()
Definition: isolate.h:859
PositionsRecorder * positions_recorder()
Logger * logger()
Definition: isolate.h:868
int optimization_id() const
Definition: compiler.h:328
int prologue_offset() const
Definition: compiler.h:283
Comment(MacroAssembler *, const char *)