blob: f89399a974fc798cd722f53d55e402bd4c55ac7d [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 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-inl.h"
Steve Blockd0582a62009-12-15 09:54:21 +000032#include "compiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000033#include "debug.h"
34#include "oprofile-agent.h"
35#include "prettyprinter.h"
36#include "register-allocator-inl.h"
37#include "rewriter.h"
38#include "runtime.h"
39#include "scopeinfo.h"
40#include "stub-cache.h"
Steve Block6ded16b2010-05-10 14:33:55 +010041#include "virtual-frame-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43namespace v8 {
44namespace internal {
45
Andrei Popescu31002712010-02-23 13:46:05 +000046#define __ ACCESS_MASM(masm_)
47
48#ifdef DEBUG
49
50Comment::Comment(MacroAssembler* masm, const char* msg)
51 : masm_(masm), msg_(msg) {
52 __ RecordComment(msg);
53}
54
55
56Comment::~Comment() {
57 if (msg_[0] == '[') __ RecordComment("]");
58}
59
60#endif // DEBUG
61
62#undef __
63
Steve Blocka7e24c12009-10-30 11:49:00 +000064
65CodeGenerator* CodeGeneratorScope::top_ = NULL;
66
67
Steve Blocka7e24c12009-10-30 11:49:00 +000068void CodeGenerator::ProcessDeferred() {
69 while (!deferred_.is_empty()) {
70 DeferredCode* code = deferred_.RemoveLast();
71 ASSERT(masm_ == code->masm());
72 // Record position of deferred code stub.
73 masm_->RecordStatementPosition(code->statement_position());
74 if (code->position() != RelocInfo::kNoPosition) {
75 masm_->RecordPosition(code->position());
76 }
77 // Generate the code.
78 Comment cmnt(masm_, code->comment());
79 masm_->bind(code->entry_label());
80 code->SaveRegisters();
81 code->Generate();
82 code->RestoreRegisters();
83 masm_->jmp(code->exit_label());
84 }
85}
86
87
88void CodeGenerator::SetFrame(VirtualFrame* new_frame,
89 RegisterFile* non_frame_registers) {
90 RegisterFile saved_counts;
91 if (has_valid_frame()) {
92 frame_->DetachFromCodeGenerator();
93 // The remaining register reference counts are the non-frame ones.
94 allocator_->SaveTo(&saved_counts);
95 }
96
97 if (new_frame != NULL) {
98 // Restore the non-frame register references that go with the new frame.
99 allocator_->RestoreFrom(non_frame_registers);
100 new_frame->AttachToCodeGenerator();
101 }
102
103 frame_ = new_frame;
104 saved_counts.CopyTo(non_frame_registers);
105}
106
107
108void CodeGenerator::DeleteFrame() {
109 if (has_valid_frame()) {
110 frame_->DetachFromCodeGenerator();
111 frame_ = NULL;
112 }
113}
114
115
Andrei Popescu31002712010-02-23 13:46:05 +0000116void CodeGenerator::MakeCodePrologue(CompilationInfo* info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000117#ifdef DEBUG
118 bool print_source = false;
119 bool print_ast = false;
Steve Block3ce2e202009-11-05 08:53:23 +0000120 bool print_json_ast = false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000121 const char* ftype;
122
123 if (Bootstrapper::IsActive()) {
124 print_source = FLAG_print_builtin_source;
125 print_ast = FLAG_print_builtin_ast;
Steve Block3ce2e202009-11-05 08:53:23 +0000126 print_json_ast = FLAG_print_builtin_json_ast;
Steve Blocka7e24c12009-10-30 11:49:00 +0000127 ftype = "builtin";
128 } else {
129 print_source = FLAG_print_source;
130 print_ast = FLAG_print_ast;
Steve Block3ce2e202009-11-05 08:53:23 +0000131 print_json_ast = FLAG_print_json_ast;
Steve Blocka7e24c12009-10-30 11:49:00 +0000132 ftype = "user-defined";
133 }
134
135 if (FLAG_trace_codegen || print_source || print_ast) {
136 PrintF("*** Generate code for %s function: ", ftype);
Andrei Popescu31002712010-02-23 13:46:05 +0000137 info->function()->name()->ShortPrint();
Steve Blocka7e24c12009-10-30 11:49:00 +0000138 PrintF(" ***\n");
139 }
140
141 if (print_source) {
Andrei Popescu31002712010-02-23 13:46:05 +0000142 PrintF("--- Source from AST ---\n%s\n",
143 PrettyPrinter().PrintProgram(info->function()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000144 }
145
146 if (print_ast) {
Andrei Popescu31002712010-02-23 13:46:05 +0000147 PrintF("--- AST ---\n%s\n",
148 AstPrinter().PrintProgram(info->function()));
Steve Block3ce2e202009-11-05 08:53:23 +0000149 }
150
151 if (print_json_ast) {
152 JsonAstBuilder builder;
Andrei Popescu31002712010-02-23 13:46:05 +0000153 PrintF("%s", builder.BuildProgram(info->function()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000154 }
155#endif // DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000156}
Steve Blocka7e24c12009-10-30 11:49:00 +0000157
Steve Blocka7e24c12009-10-30 11:49:00 +0000158
Andrei Popescu31002712010-02-23 13:46:05 +0000159Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm,
Steve Block3ce2e202009-11-05 08:53:23 +0000160 Code::Flags flags,
Andrei Popescu31002712010-02-23 13:46:05 +0000161 CompilationInfo* info) {
Steve Block3ce2e202009-11-05 08:53:23 +0000162 // Allocate and install the code.
Steve Blocka7e24c12009-10-30 11:49:00 +0000163 CodeDesc desc;
Steve Block3ce2e202009-11-05 08:53:23 +0000164 masm->GetCode(&desc);
Andrei Popescu31002712010-02-23 13:46:05 +0000165 ZoneScopeInfo sinfo(info->scope());
Steve Block3ce2e202009-11-05 08:53:23 +0000166 Handle<Code> code =
167 Factory::NewCode(desc, &sinfo, flags, masm->CodeObject());
Steve Blocka7e24c12009-10-30 11:49:00 +0000168
Steve Blocka7e24c12009-10-30 11:49:00 +0000169#ifdef ENABLE_DISASSEMBLER
Steve Block3ce2e202009-11-05 08:53:23 +0000170 bool print_code = Bootstrapper::IsActive()
171 ? FLAG_print_builtin_code
172 : FLAG_print_code;
Steve Blocka7e24c12009-10-30 11:49:00 +0000173 if (print_code) {
174 // Print the source code if available.
Andrei Popescu31002712010-02-23 13:46:05 +0000175 Handle<Script> script = info->script();
176 FunctionLiteral* function = info->function();
Steve Blocka7e24c12009-10-30 11:49:00 +0000177 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
178 PrintF("--- Raw source ---\n");
179 StringInputBuffer stream(String::cast(script->source()));
Andrei Popescu31002712010-02-23 13:46:05 +0000180 stream.Seek(function->start_position());
Steve Block3ce2e202009-11-05 08:53:23 +0000181 // fun->end_position() points to the last character in the stream. We
Steve Blocka7e24c12009-10-30 11:49:00 +0000182 // need to compensate by adding one to calculate the length.
Andrei Popescu31002712010-02-23 13:46:05 +0000183 int source_len =
184 function->end_position() - function->start_position() + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +0000185 for (int i = 0; i < source_len; i++) {
186 if (stream.has_more()) PrintF("%c", stream.GetNext());
187 }
188 PrintF("\n\n");
189 }
190 PrintF("--- Code ---\n");
Andrei Popescu31002712010-02-23 13:46:05 +0000191 code->Disassemble(*function->name()->ToCString());
Steve Blocka7e24c12009-10-30 11:49:00 +0000192 }
193#endif // ENABLE_DISASSEMBLER
194
195 if (!code.is_null()) {
196 Counters::total_compiled_code_size.Increment(code->instruction_size());
197 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000198 return code;
199}
200
201
Steve Block3ce2e202009-11-05 08:53:23 +0000202// Generate the code. Takes a function literal, generates code for it, assemble
203// all the pieces into a Code object. This function is only to be called by
204// the compiler.cc code.
Andrei Popescu31002712010-02-23 13:46:05 +0000205Handle<Code> CodeGenerator::MakeCode(CompilationInfo* info) {
206 Handle<Script> script = info->script();
Leon Clarked91b9f72010-01-27 17:25:45 +0000207 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
208 int len = String::cast(script->source())->length();
209 Counters::total_old_codegen_source_size.Increment(len);
210 }
Andrei Popescu31002712010-02-23 13:46:05 +0000211 MakeCodePrologue(info);
Steve Block3ce2e202009-11-05 08:53:23 +0000212 // Generate code.
213 const int kInitialBufferSize = 4 * KB;
Leon Clarke4515c472010-02-03 11:58:03 +0000214 MacroAssembler masm(NULL, kInitialBufferSize);
Andrei Popescu31002712010-02-23 13:46:05 +0000215 CodeGenerator cgen(&masm);
Steve Block3ce2e202009-11-05 08:53:23 +0000216 CodeGeneratorScope scope(&cgen);
Andrei Popescu402d9372010-02-26 13:31:12 +0000217 cgen.Generate(info);
Steve Block3ce2e202009-11-05 08:53:23 +0000218 if (cgen.HasStackOverflow()) {
219 ASSERT(!Top::has_pending_exception());
220 return Handle<Code>::null();
221 }
222
223 InLoopFlag in_loop = (cgen.loop_nesting() != 0) ? IN_LOOP : NOT_IN_LOOP;
224 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION, in_loop);
Steve Block6ded16b2010-05-10 14:33:55 +0100225 return MakeCodeEpilogue(cgen.masm(), flags, info);
Steve Block3ce2e202009-11-05 08:53:23 +0000226}
227
228
Steve Blocka7e24c12009-10-30 11:49:00 +0000229#ifdef ENABLE_LOGGING_AND_PROFILING
230
231bool CodeGenerator::ShouldGenerateLog(Expression* type) {
232 ASSERT(type != NULL);
Steve Block6ded16b2010-05-10 14:33:55 +0100233 if (!Logger::is_logging() && !CpuProfiler::is_profiling()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000234 Handle<String> name = Handle<String>::cast(type->AsLiteral()->handle());
235 if (FLAG_log_regexp) {
236 static Vector<const char> kRegexp = CStrVector("regexp");
237 if (name->IsEqualTo(kRegexp))
238 return true;
239 }
240 return false;
241}
242
243#endif
244
245
Steve Blocka7e24c12009-10-30 11:49:00 +0000246Handle<Code> CodeGenerator::ComputeCallInitialize(
247 int argc,
248 InLoopFlag in_loop) {
249 if (in_loop == IN_LOOP) {
250 // Force the creation of the corresponding stub outside loops,
251 // because it may be used when clearing the ICs later - it is
252 // possible for a series of IC transitions to lose the in-loop
253 // information, and the IC clearing code can't generate a stub
254 // that it needs so we need to ensure it is generated already.
255 ComputeCallInitialize(argc, NOT_IN_LOOP);
256 }
257 CALL_HEAP_FUNCTION(StubCache::ComputeCallInitialize(argc, in_loop), Code);
258}
259
260
261void CodeGenerator::ProcessDeclarations(ZoneList<Declaration*>* declarations) {
262 int length = declarations->length();
263 int globals = 0;
264 for (int i = 0; i < length; i++) {
265 Declaration* node = declarations->at(i);
266 Variable* var = node->proxy()->var();
267 Slot* slot = var->slot();
268
269 // If it was not possible to allocate the variable at compile
270 // time, we need to "declare" it at runtime to make sure it
271 // actually exists in the local context.
272 if ((slot != NULL && slot->type() == Slot::LOOKUP) || !var->is_global()) {
273 VisitDeclaration(node);
274 } else {
275 // Count global variables and functions for later processing
276 globals++;
277 }
278 }
279
280 // Return in case of no declared global functions or variables.
281 if (globals == 0) return;
282
283 // Compute array of global variable and function declarations.
284 Handle<FixedArray> array = Factory::NewFixedArray(2 * globals, TENURED);
285 for (int j = 0, i = 0; i < length; i++) {
286 Declaration* node = declarations->at(i);
287 Variable* var = node->proxy()->var();
288 Slot* slot = var->slot();
289
290 if ((slot != NULL && slot->type() == Slot::LOOKUP) || !var->is_global()) {
291 // Skip - already processed.
292 } else {
293 array->set(j++, *(var->name()));
294 if (node->fun() == NULL) {
295 if (var->mode() == Variable::CONST) {
296 // In case this is const property use the hole.
297 array->set_the_hole(j++);
298 } else {
299 array->set_undefined(j++);
300 }
301 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100302 Handle<SharedFunctionInfo> function =
303 Compiler::BuildFunctionInfo(node->fun(), script(), this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000304 // Check for stack-overflow exception.
305 if (HasStackOverflow()) return;
306 array->set(j++, *function);
307 }
308 }
309 }
310
311 // Invoke the platform-dependent code generator to do the actual
312 // declaration the global variables and functions.
313 DeclareGlobals(array);
314}
315
316
Steve Block6ded16b2010-05-10 14:33:55 +0100317// List of special runtime calls which are generated inline. For some of these
318// functions the code will be generated inline, and for others a call to a code
319// stub will be inlined.
Steve Blocka7e24c12009-10-30 11:49:00 +0000320
Steve Block6ded16b2010-05-10 14:33:55 +0100321#define INLINE_RUNTIME_ENTRY(Name, argc, ressize) \
322 {&CodeGenerator::Generate##Name, "_" #Name, argc}, \
323
Steve Blocka7e24c12009-10-30 11:49:00 +0000324CodeGenerator::InlineRuntimeLUT CodeGenerator::kInlineRuntimeLUT[] = {
Steve Block6ded16b2010-05-10 14:33:55 +0100325 INLINE_RUNTIME_FUNCTION_LIST(INLINE_RUNTIME_ENTRY)
Steve Blocka7e24c12009-10-30 11:49:00 +0000326};
327
Steve Block6ded16b2010-05-10 14:33:55 +0100328#undef INLINE_RUNTIME_ENTRY
Steve Blocka7e24c12009-10-30 11:49:00 +0000329
330CodeGenerator::InlineRuntimeLUT* CodeGenerator::FindInlineRuntimeLUT(
331 Handle<String> name) {
332 const int entries_count =
333 sizeof(kInlineRuntimeLUT) / sizeof(InlineRuntimeLUT);
334 for (int i = 0; i < entries_count; i++) {
335 InlineRuntimeLUT* entry = &kInlineRuntimeLUT[i];
336 if (name->IsEqualTo(CStrVector(entry->name))) {
337 return entry;
338 }
339 }
340 return NULL;
341}
342
343
344bool CodeGenerator::CheckForInlineRuntimeCall(CallRuntime* node) {
345 ZoneList<Expression*>* args = node->arguments();
346 Handle<String> name = node->name();
347 if (name->length() > 0 && name->Get(0) == '_') {
348 InlineRuntimeLUT* entry = FindInlineRuntimeLUT(name);
349 if (entry != NULL) {
350 ((*this).*(entry->method))(args);
351 return true;
352 }
353 }
354 return false;
355}
356
357
358bool CodeGenerator::PatchInlineRuntimeEntry(Handle<String> name,
359 const CodeGenerator::InlineRuntimeLUT& new_entry,
360 CodeGenerator::InlineRuntimeLUT* old_entry) {
361 InlineRuntimeLUT* entry = FindInlineRuntimeLUT(name);
362 if (entry == NULL) return false;
363 if (old_entry != NULL) {
364 old_entry->name = entry->name;
365 old_entry->method = entry->method;
366 }
367 entry->name = new_entry.name;
368 entry->method = new_entry.method;
369 return true;
370}
371
372
Steve Block6ded16b2010-05-10 14:33:55 +0100373int CodeGenerator::InlineRuntimeCallArgumentsCount(Handle<String> name) {
374 CodeGenerator::InlineRuntimeLUT* f =
375 CodeGenerator::FindInlineRuntimeLUT(name);
376 if (f != NULL) return f->nargs;
377 return -1;
378}
379
380
Steve Block3ce2e202009-11-05 08:53:23 +0000381// Simple condition analysis. ALWAYS_TRUE and ALWAYS_FALSE represent a
382// known result for the test expression, with no side effects.
383CodeGenerator::ConditionAnalysis CodeGenerator::AnalyzeCondition(
384 Expression* cond) {
385 if (cond == NULL) return ALWAYS_TRUE;
386
387 Literal* lit = cond->AsLiteral();
388 if (lit == NULL) return DONT_KNOW;
389
390 if (lit->IsTrue()) {
391 return ALWAYS_TRUE;
392 } else if (lit->IsFalse()) {
393 return ALWAYS_FALSE;
394 }
395
396 return DONT_KNOW;
397}
398
399
400void CodeGenerator::RecordPositions(MacroAssembler* masm, int pos) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000401 if (pos != RelocInfo::kNoPosition) {
Steve Block3ce2e202009-11-05 08:53:23 +0000402 masm->RecordStatementPosition(pos);
403 masm->RecordPosition(pos);
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 }
405}
406
407
408void CodeGenerator::CodeForFunctionPosition(FunctionLiteral* fun) {
Steve Block3ce2e202009-11-05 08:53:23 +0000409 if (FLAG_debug_info) RecordPositions(masm(), fun->start_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000410}
411
412
413void CodeGenerator::CodeForReturnPosition(FunctionLiteral* fun) {
Steve Block3ce2e202009-11-05 08:53:23 +0000414 if (FLAG_debug_info) RecordPositions(masm(), fun->end_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000415}
416
417
418void CodeGenerator::CodeForStatementPosition(Statement* stmt) {
Steve Block3ce2e202009-11-05 08:53:23 +0000419 if (FLAG_debug_info) RecordPositions(masm(), stmt->statement_pos());
Steve Blocka7e24c12009-10-30 11:49:00 +0000420}
421
Steve Blockd0582a62009-12-15 09:54:21 +0000422void CodeGenerator::CodeForDoWhileConditionPosition(DoWhileStatement* stmt) {
423 if (FLAG_debug_info) RecordPositions(masm(), stmt->condition_position());
424}
Steve Blocka7e24c12009-10-30 11:49:00 +0000425
426void CodeGenerator::CodeForSourcePosition(int pos) {
427 if (FLAG_debug_info && pos != RelocInfo::kNoPosition) {
428 masm()->RecordPosition(pos);
429 }
430}
431
432
Leon Clarkee46be812010-01-19 14:06:41 +0000433const char* GenericUnaryOpStub::GetName() {
434 switch (op_) {
435 case Token::SUB:
436 return overwrite_
437 ? "GenericUnaryOpStub_SUB_Overwrite"
438 : "GenericUnaryOpStub_SUB_Alloc";
439 case Token::BIT_NOT:
440 return overwrite_
441 ? "GenericUnaryOpStub_BIT_NOT_Overwrite"
442 : "GenericUnaryOpStub_BIT_NOT_Alloc";
443 default:
444 UNREACHABLE();
445 return "<unknown>";
446 }
447}
448
449
Steve Blocka7e24c12009-10-30 11:49:00 +0000450void ArgumentsAccessStub::Generate(MacroAssembler* masm) {
451 switch (type_) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000452 case READ_ELEMENT: GenerateReadElement(masm); break;
453 case NEW_OBJECT: GenerateNewObject(masm); break;
454 }
455}
456
457
Leon Clarke4515c472010-02-03 11:58:03 +0000458int CEntryStub::MinorKey() {
459 ASSERT(result_size_ <= 2);
460#ifdef _WIN64
461 return ExitFrameModeBits::encode(mode_)
462 | IndirectResultBits::encode(result_size_ > 1);
463#else
464 return ExitFrameModeBits::encode(mode_);
465#endif
466}
467
468
Steve Blockd0582a62009-12-15 09:54:21 +0000469bool ApiGetterEntryStub::GetCustomCache(Code** code_out) {
470 Object* cache = info()->load_stub_cache();
471 if (cache->IsUndefined()) {
472 return false;
473 } else {
474 *code_out = Code::cast(cache);
475 return true;
476 }
477}
478
479
480void ApiGetterEntryStub::SetCustomCache(Code* value) {
481 info()->set_load_stub_cache(value);
482}
483
484
Steve Blocka7e24c12009-10-30 11:49:00 +0000485} } // namespace v8::internal