1 // Copyright 2010 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
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.
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.
28 #ifndef V8_ARM_CODEGEN_ARM_H_
29 #define V8_ARM_CODEGEN_ARM_H_
34 // Forward declarations
35 class CompilationInfo;
37 class RegisterAllocator;
40 enum InitState { CONST_INIT, NOT_CONST_INIT };
41 enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
44 // -------------------------------------------------------------------------
47 // A reference is a C++ stack-allocated object that puts a
48 // reference on the virtual frame. The reference may be consumed
49 // by GetValue, TakeValue, SetValue, and Codegen::UnloadReference.
50 // When the lifetime (scope) of a valid reference ends, it must have
51 // been consumed, and be in state UNLOADED.
52 class Reference BASE_EMBEDDED {
54 // The values of the types is important, see size().
55 enum Type { UNLOADED = -2, ILLEGAL = -1, SLOT = 0, NAMED = 1, KEYED = 2 };
56 Reference(CodeGenerator* cgen,
57 Expression* expression,
58 bool persist_after_get = false);
61 Expression* expression() const { return expression_; }
62 Type type() const { return type_; }
63 void set_type(Type value) {
64 ASSERT_EQ(ILLEGAL, type_);
69 ASSERT_NE(ILLEGAL, type_);
70 ASSERT_NE(UNLOADED, type_);
73 // The size the reference takes up on the stack.
75 return (type_ < SLOT) ? 0 : type_;
78 bool is_illegal() const { return type_ == ILLEGAL; }
79 bool is_slot() const { return type_ == SLOT; }
80 bool is_property() const { return type_ == NAMED || type_ == KEYED; }
81 bool is_unloaded() const { return type_ == UNLOADED; }
83 // Return the name. Only valid for named property references.
84 Handle<String> GetName();
86 // Generate code to push the value of the reference on top of the
87 // expression stack. The reference is expected to be already on top of
88 // the expression stack, and it is consumed by the call unless the
89 // reference is for a compound assignment.
90 // If the reference is not consumed, it is left in place under its value.
93 // Generate code to pop a reference, push the value of the reference,
94 // and then spill the stack frame.
95 inline void GetValueAndSpill();
97 // Generate code to store the value on top of the expression stack in the
98 // reference. The reference is expected to be immediately below the value
99 // on the expression stack. The value is stored in the location specified
100 // by the reference, and is left on top of the stack, after the reference
101 // is popped from beneath it (unloaded).
102 void SetValue(InitState init_state);
105 CodeGenerator* cgen_;
106 Expression* expression_;
108 // Keep the reference on the stack after get, so it can be used by set later.
109 bool persist_after_get_;
113 // -------------------------------------------------------------------------
114 // Code generation state
116 // The state is passed down the AST by the code generator (and back up, in
117 // the form of the state of the label pair). It is threaded through the
118 // call stack. Constructing a state implicitly pushes it on the owning code
119 // generator's stack of states, and destroying one implicitly pops it.
121 class CodeGenState BASE_EMBEDDED {
123 // Create an initial code generator state. Destroying the initial state
124 // leaves the code generator with a NULL state.
125 explicit CodeGenState(CodeGenerator* owner);
127 // Create a code generator state based on a code generator's current
128 // state. The new state has its own pair of branch labels.
129 CodeGenState(CodeGenerator* owner,
130 JumpTarget* true_target,
131 JumpTarget* false_target);
133 // Destroy a code generator state and restore the owning code generator's
137 JumpTarget* true_target() const { return true_target_; }
138 JumpTarget* false_target() const { return false_target_; }
141 CodeGenerator* owner_;
142 JumpTarget* true_target_;
143 JumpTarget* false_target_;
144 CodeGenState* previous_;
148 // -------------------------------------------------------------------------
151 class CodeGenerator: public AstVisitor {
153 // Takes a function literal, generates code for it. This function should only
154 // be called by compiler.cc.
155 static Handle<Code> MakeCode(CompilationInfo* info);
157 // Printing of AST, etc. as requested by flags.
158 static void MakeCodePrologue(CompilationInfo* info);
160 // Allocate and install the code.
161 static Handle<Code> MakeCodeEpilogue(MacroAssembler* masm,
163 CompilationInfo* info);
165 #ifdef ENABLE_LOGGING_AND_PROFILING
166 static bool ShouldGenerateLog(Expression* type);
169 static void SetFunctionInfo(Handle<JSFunction> fun,
170 FunctionLiteral* lit,
172 Handle<Script> script);
174 static void RecordPositions(MacroAssembler* masm, int pos);
177 MacroAssembler* masm() { return masm_; }
178 VirtualFrame* frame() const { return frame_; }
179 inline Handle<Script> script();
181 bool has_valid_frame() const { return frame_ != NULL; }
183 // Set the virtual frame to be new_frame, with non-frame register
184 // reference counts given by non_frame_registers. The non-frame
185 // register reference counts of the old frame are returned in
186 // non_frame_registers.
187 void SetFrame(VirtualFrame* new_frame, RegisterFile* non_frame_registers);
191 RegisterAllocator* allocator() const { return allocator_; }
193 CodeGenState* state() { return state_; }
194 void set_state(CodeGenState* state) { state_ = state; }
196 void AddDeferred(DeferredCode* code) { deferred_.Add(code); }
198 static const int kUnknownIntValue = -1;
200 // If the name is an inline runtime function call return the number of
201 // expected arguments. Otherwise return -1.
202 static int InlineRuntimeCallArgumentsCount(Handle<String> name);
205 // Construction/Destruction
206 explicit CodeGenerator(MacroAssembler* masm);
209 inline bool is_eval();
210 inline Scope* scope();
212 // Generating deferred code.
213 void ProcessDeferred();
216 bool has_cc() const { return cc_reg_ != al; }
217 JumpTarget* true_target() const { return state_->true_target(); }
218 JumpTarget* false_target() const { return state_->false_target(); }
220 // We don't track loop nesting level on ARM yet.
221 int loop_nesting() const { return 0; }
224 void VisitStatements(ZoneList<Statement*>* statements);
226 #define DEF_VISIT(type) \
227 void Visit##type(type* node);
228 AST_NODE_LIST(DEF_VISIT)
231 // Visit a statement and then spill the virtual frame if control flow can
232 // reach the end of the statement (ie, it does not exit via break,
233 // continue, return, or throw). This function is used temporarily while
234 // the code generator is being transformed.
235 inline void VisitAndSpill(Statement* statement);
237 // Visit a list of statements and then spill the virtual frame if control
238 // flow can reach the end of the list.
239 inline void VisitStatementsAndSpill(ZoneList<Statement*>* statements);
241 // Main code generation function
242 void Generate(CompilationInfo* info);
244 // The following are used by class Reference.
245 void LoadReference(Reference* ref);
246 void UnloadReference(Reference* ref);
248 static MemOperand ContextOperand(Register context, int index) {
249 return MemOperand(context, Context::SlotOffset(index));
252 MemOperand SlotOperand(Slot* slot, Register tmp);
254 MemOperand ContextSlotOperandCheckExtensions(Slot* slot,
260 static MemOperand GlobalObject() {
261 return ContextOperand(cp, Context::GLOBAL_INDEX);
264 void LoadCondition(Expression* x,
265 JumpTarget* true_target,
266 JumpTarget* false_target,
268 void Load(Expression* expr);
270 void LoadGlobalReceiver(Register scratch);
272 // Generate code to push the value of an expression on top of the frame
273 // and then spill the frame fully to memory. This function is used
274 // temporarily while the code generator is being transformed.
275 inline void LoadAndSpill(Expression* expression);
277 // Call LoadCondition and then spill the virtual frame unless control flow
278 // cannot reach the end of the expression (ie, by emitting only
279 // unconditional jumps to the control targets).
280 inline void LoadConditionAndSpill(Expression* expression,
281 JumpTarget* true_target,
282 JumpTarget* false_target,
285 // Read a value from a slot and leave it on top of the expression stack.
286 void LoadFromSlot(Slot* slot, TypeofState typeof_state);
287 // Store the value on top of the stack to a slot.
288 void StoreToSlot(Slot* slot, InitState init_state);
289 // Load a keyed property, leaving it in r0. The receiver and key are
290 // passed on the stack, and remain there.
291 void EmitKeyedLoad(bool is_global);
293 void LoadFromGlobalSlotCheckExtensions(Slot* slot,
294 TypeofState typeof_state,
299 // Special code for typeof expressions: Unfortunately, we must
300 // be careful when loading the expression in 'typeof'
301 // expressions. We are not allowed to throw reference errors for
302 // non-existing properties of the global object, so we must make it
303 // look like an explicit property access, instead of an access
304 // through the context chain.
305 void LoadTypeofExpression(Expression* x);
307 void ToBoolean(JumpTarget* true_target, JumpTarget* false_target);
309 void GenericBinaryOperation(Token::Value op,
310 OverwriteMode overwrite_mode,
311 int known_rhs = kUnknownIntValue);
312 void Comparison(Condition cc,
315 bool strict = false);
317 void SmiOperation(Token::Value op,
318 Handle<Object> value,
322 void CallWithArguments(ZoneList<Expression*>* arguments,
323 CallFunctionFlags flags,
327 void Branch(bool if_true, JumpTarget* target);
330 struct InlineRuntimeLUT {
331 void (CodeGenerator::*method)(ZoneList<Expression*>*);
336 static InlineRuntimeLUT* FindInlineRuntimeLUT(Handle<String> name);
337 bool CheckForInlineRuntimeCall(CallRuntime* node);
338 static bool PatchInlineRuntimeEntry(Handle<String> name,
339 const InlineRuntimeLUT& new_entry,
340 InlineRuntimeLUT* old_entry);
342 static Handle<Code> ComputeLazyCompile(int argc);
343 void ProcessDeclarations(ZoneList<Declaration*>* declarations);
345 static Handle<Code> ComputeCallInitialize(int argc, InLoopFlag in_loop);
347 // Declare global variables and functions in the given array of
349 void DeclareGlobals(Handle<FixedArray> pairs);
351 // Instantiate the function based on the shared function info.
352 void InstantiateFunction(Handle<SharedFunctionInfo> function_info);
354 // Support for type checks.
355 void GenerateIsSmi(ZoneList<Expression*>* args);
356 void GenerateIsNonNegativeSmi(ZoneList<Expression*>* args);
357 void GenerateIsArray(ZoneList<Expression*>* args);
358 void GenerateIsRegExp(ZoneList<Expression*>* args);
359 void GenerateIsObject(ZoneList<Expression*>* args);
360 void GenerateIsFunction(ZoneList<Expression*>* args);
361 void GenerateIsUndetectableObject(ZoneList<Expression*>* args);
363 // Support for construct call checks.
364 void GenerateIsConstructCall(ZoneList<Expression*>* args);
366 // Support for arguments.length and arguments[?].
367 void GenerateArgumentsLength(ZoneList<Expression*>* args);
368 void GenerateArguments(ZoneList<Expression*>* args);
370 // Support for accessing the class and value fields of an object.
371 void GenerateClassOf(ZoneList<Expression*>* args);
372 void GenerateValueOf(ZoneList<Expression*>* args);
373 void GenerateSetValueOf(ZoneList<Expression*>* args);
375 // Fast support for charCodeAt(n).
376 void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
378 // Fast support for string.charAt(n) and string[n].
379 void GenerateCharFromCode(ZoneList<Expression*>* args);
381 // Fast support for object equality testing.
382 void GenerateObjectEquals(ZoneList<Expression*>* args);
384 void GenerateLog(ZoneList<Expression*>* args);
386 // Fast support for Math.random().
387 void GenerateRandomPositiveSmi(ZoneList<Expression*>* args);
389 // Fast support for StringAdd.
390 void GenerateStringAdd(ZoneList<Expression*>* args);
392 // Fast support for SubString.
393 void GenerateSubString(ZoneList<Expression*>* args);
395 // Fast support for StringCompare.
396 void GenerateStringCompare(ZoneList<Expression*>* args);
398 // Support for direct calls from JavaScript to native RegExp code.
399 void GenerateRegExpExec(ZoneList<Expression*>* args);
401 // Fast support for number to string.
402 void GenerateNumberToString(ZoneList<Expression*>* args);
404 // Fast call to math functions.
405 void GenerateMathPow(ZoneList<Expression*>* args);
406 void GenerateMathSin(ZoneList<Expression*>* args);
407 void GenerateMathCos(ZoneList<Expression*>* args);
408 void GenerateMathSqrt(ZoneList<Expression*>* args);
410 // Simple condition analysis.
411 enum ConditionAnalysis {
416 ConditionAnalysis AnalyzeCondition(Expression* cond);
418 // Methods used to indicate which source code is generated for. Source
419 // positions are collected by the assembler and emitted with the relocation
421 void CodeForFunctionPosition(FunctionLiteral* fun);
422 void CodeForReturnPosition(FunctionLiteral* fun);
423 void CodeForStatementPosition(Statement* node);
424 void CodeForDoWhileConditionPosition(DoWhileStatement* stmt);
425 void CodeForSourcePosition(int pos);
428 // True if the registers are valid for entry to a block.
429 bool HasValidEntryRegisters();
432 List<DeferredCode*> deferred_;
435 MacroAssembler* masm_; // to generate code
437 CompilationInfo* info_;
439 // Code generation state
440 VirtualFrame* frame_;
441 RegisterAllocator* allocator_;
443 CodeGenState* state_;
446 BreakTarget function_return_;
448 // True if the function return is shadowed (ie, jumping to the target
449 // function_return_ does not jump to the true function return, but rather
450 // to some unlinking code).
451 bool function_return_is_shadowed_;
453 static InlineRuntimeLUT kInlineRuntimeLUT[];
455 friend class VirtualFrame;
456 friend class JumpTarget;
457 friend class Reference;
458 friend class FastCodeGenerator;
459 friend class FullCodeGenerator;
460 friend class FullCodeGenSyntaxChecker;
462 DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
466 class GenericBinaryOpStub : public CodeStub {
468 GenericBinaryOpStub(Token::Value op,
470 int constant_rhs = CodeGenerator::kUnknownIntValue)
473 constant_rhs_(constant_rhs),
474 specialized_on_rhs_(RhsIsOneWeWantToOptimizeFor(op, constant_rhs)),
481 bool specialized_on_rhs_;
484 static const int kMaxKnownRhs = 0x40000000;
486 // Minor key encoding in 16 bits.
487 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
488 class OpBits: public BitField<Token::Value, 2, 6> {};
489 class KnownIntBits: public BitField<int, 8, 8> {};
491 Major MajorKey() { return GenericBinaryOp; }
493 // Encode the parameters in a unique 16 bit value.
494 return OpBits::encode(op_)
495 | ModeBits::encode(mode_)
496 | KnownIntBits::encode(MinorKeyForKnownInt());
499 void Generate(MacroAssembler* masm);
500 void HandleNonSmiBitwiseOp(MacroAssembler* masm);
502 static bool RhsIsOneWeWantToOptimizeFor(Token::Value op, int constant_rhs) {
503 if (constant_rhs == CodeGenerator::kUnknownIntValue) return false;
504 if (op == Token::DIV) return constant_rhs >= 2 && constant_rhs <= 3;
505 if (op == Token::MOD) {
506 if (constant_rhs <= 1) return false;
507 if (constant_rhs <= 10) return true;
508 if (constant_rhs <= kMaxKnownRhs && IsPowerOf2(constant_rhs)) return true;
514 int MinorKeyForKnownInt() {
515 if (!specialized_on_rhs_) return 0;
516 if (constant_rhs_ <= 10) return constant_rhs_ + 1;
517 ASSERT(IsPowerOf2(constant_rhs_));
519 int d = constant_rhs_;
520 while ((d & 1) == 0) {
527 const char* GetName();
531 if (!specialized_on_rhs_) {
532 PrintF("GenericBinaryOpStub (%s)\n", Token::String(op_));
534 PrintF("GenericBinaryOpStub (%s by %d)\n",
543 class StringStubBase: public CodeStub {
545 // Generate code for copying characters using a simple loop. This should only
546 // be used in places where the number of characters is small and the
547 // additional setup and checking in GenerateCopyCharactersLong adds too much
548 // overhead. Copying of overlapping regions is not supported.
549 // Dest register ends at the position after the last character written.
550 void GenerateCopyCharacters(MacroAssembler* masm,
557 // Generate code for copying a large number of characters. This function
558 // is allowed to spend extra time setting up conditions to make copying
559 // faster. Copying of overlapping regions is not supported.
560 // Dest register ends at the position after the last character written.
561 void GenerateCopyCharactersLong(MacroAssembler* masm,
573 // Probe the symbol table for a two character string. If the string is
574 // not found by probing a jump to the label not_found is performed. This jump
575 // does not guarantee that the string is not in the symbol table. If the
576 // string is found the code falls through with the string in register r0.
577 // Contents of both c1 and c2 registers are modified. At the exit c1 is
578 // guaranteed to contain halfword with low and high bytes equal to
579 // initial contents of c1 and c2 respectively.
580 void GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
590 // Generate string hash.
591 void GenerateHashInit(MacroAssembler* masm,
595 void GenerateHashAddCharacter(MacroAssembler* masm,
599 void GenerateHashGetHash(MacroAssembler* masm,
604 // Flag that indicates how to generate code for the stub StringAddStub.
605 enum StringAddFlags {
606 NO_STRING_ADD_FLAGS = 0,
607 NO_STRING_CHECK_IN_STUB = 1 << 0 // Omit string check in stub.
611 class StringAddStub: public StringStubBase {
613 explicit StringAddStub(StringAddFlags flags) {
614 string_check_ = ((flags & NO_STRING_CHECK_IN_STUB) == 0);
618 Major MajorKey() { return StringAdd; }
619 int MinorKey() { return string_check_ ? 0 : 1; }
621 void Generate(MacroAssembler* masm);
623 // Should the stub check whether arguments are strings?
628 class SubStringStub: public StringStubBase {
633 Major MajorKey() { return SubString; }
634 int MinorKey() { return 0; }
636 void Generate(MacroAssembler* masm);
641 class StringCompareStub: public CodeStub {
643 StringCompareStub() { }
645 // Compare two flat ASCII strings and returns result in r0.
646 // Does not use the stack.
647 static void GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
656 Major MajorKey() { return StringCompare; }
657 int MinorKey() { return 0; }
659 void Generate(MacroAssembler* masm);
663 class NumberToStringStub: public CodeStub {
665 NumberToStringStub() { }
667 // Generate code to do a lookup in the number string cache. If the number in
668 // the register object is found in the cache the generated code falls through
669 // with the result in the result register. The object and the result register
670 // can be the same. If the number is not found in the cache the code jumps to
671 // the label not_found with only the content of register object unchanged.
672 static void GenerateLookupNumberStringCache(MacroAssembler* masm,
681 Major MajorKey() { return NumberToString; }
682 int MinorKey() { return 0; }
684 void Generate(MacroAssembler* masm);
686 const char* GetName() { return "NumberToStringStub"; }
690 PrintF("NumberToStringStub\n");
696 } } // namespace v8::internal
698 #endif // V8_ARM_CODEGEN_ARM_H_