SlideShare ist ein Scribd-Unternehmen logo
1 von 35
HipHop Compiler for PHP
  Transforming PHP into C++

       HipHop Compiler Team
          Facebook, Inc.
            May 2010



                              Facebook 2010 (confidential)
PHP is easy to read

<?php

function   tally($count) {
  $sum =   0;
 for ($i   = 0; $i< $count; ++$i) {
    $sum   += $i;
  }
  return   $sum;
}

print tally(10) . “n”;

                                      Facebook 2010 (confidential)
PHP syntax is similar to C++/Java

 <?php

 class Tool extends Object {
   public $name;

     public use($target) {}
 }

 $tool = new Tool();
 $tool->name = „hammer‟;
 $tool->use($nail);

                               Facebook 2010 (confidential)
PHP Statements and Expressions

  FunctionStatement,
  ClassStatement,
  InterfaceStatement,   ExpressionList,
  ClassVariable,        AssignmentExpression,
  ClassConstant,        SimpleVariable,
  MethodStatement,      DynamicVariable,
  StatementList,        StaticMemberExpression,
  BlockStatement,       ArrayElementExpression,
  IfBranchStatement,    DynamicFunctionCall,
  IfStatement,          SimpleFunctionCall,
  WhileStatement,       ScalarExpression,
  DoStatement,          ObjectPropertyExpression,
  ForStatement,         ObjectMethodExpression,
  SwitchStatement,      ListAssignment,
  CaseStatement,        NewObjectExpression,
  BreakStatement,       UnaryOpExpression,
  ContinueStatement,    IncludeExpression,
  ReturnStatement,      BinaryOpExpression,
  GlobalStatement,      QOpExpression,
  StaticStatement,      ArrayPairExpression,
  EchoStatement,        ClassConstantExpression,
  UnsetStatement,       ParameterExpression,
  ExpStatement,         ModifierExpression,
  ForEachStatement,     ConstantExpression,
  CatchStatement,       EncapsListExpression,
  TryStatement,
  ThrowStatement,
                                                  Facebook 2010 (confidential)
PHP is weakly typed

<?php

$a   =   12345;
$a   =   “hello”;
$a   =   array(12345, “hello”, array());
$a   =   new Object();

$c = $a + $b; // integer or array
$c = $a . $b; // implicit casting to strings



                                           Facebook 2010 (confidential)
Core PHP library is small


- Most are in functional style
- ~200 to 500 basic functions

<?php

$len = strlen(“hello”);    // C library
$ret = curl_exec($curl);   // open source




                                     Facebook 2010 (confidential)
PHP is easy to debug

<?php

function tally($count) {
  $sum = 0;
  for ($i = 0; $i< $count; ++$i) {
    $sum += $i;
var_dump($sum);
  }
  return $sum;
}


                                     Facebook 2010 (confidential)
PHP is easy to learn


 easy to read
 easy to write
 easy to debug


      Hello, World!
                            Facebook 2010 (confidential)
PHP is slow 

     http://shootout.alioth.debian.org/u64q/benchmark.ph
                      p?test=all&lang=all
50

40

30

20                                                                     CPU

10

0
     C++    Java    C#    Erlang   Python   Perl      PHP


                                                   Facebook 2010 (confidential)
Why is Zend Engine slow?

 Byte-code interpreter

 Dynamic symbol lookups

  functions, variables, constants
  class methods, properties, constants

 Weakly typing
  zval
  array()
                                     Facebook 2010 (confidential)
Transforming PHP into C++

 g++ is a native code compiler

 static binding

   functions, variables, constants
   class methods, properties, constants

 type inference
   integers, strings, arrays, objects, variants
   struct, vector, map, array
                                      Facebook 2010 (confidential)
Static Binding – Function Calls


<?php
$ret = foo($a);

// C++
Variant v_ret;
Variant v_a;

v_ret = f_foo(v_a);



                         Facebook 2010 (confidential)
Dynamic Function Calls

<?php
$func = „foo‟;
$ret = $func($a);

// C++
Variant v_ret;
Variant v_a;
String v_func;

V_func = “foo”;
v_ret = invoke(v_func, CREATE_VECTOR1(v_a));
                                    Facebook 2010 (confidential)
Function Invoke Table



Variant invoke(CStrReffunc, CArrRefparams) {
  int64 hash = hash_string(func);
  switch (hash) {
  case 1234:
    if (func == “foo”) return foo(params[0])
  }
  throw FatalError(“function not found”);
}


                                    Facebook 2010 (confidential)
Re-declared Functions

<?php
if ($condition) {
  function foo($a) { return $a + 1;}
} else {
  function foo($a) { return $a + 2;}
}
$ret = foo($a);

// C++
if (v_condition) {
g->i_foo = i_foo$$0;
} else {
g->i_foo = i_foo$$1;
}
g->i_foo(v_a);

                                       Facebook 2010 (confidential)
Volatile Functions

<?php
if (!function_exists(„foo‟)) {
bar($a);
} else {
foo($a);
}
function foo($a) {}

// C++
if (f_function_exists(“foo”)) {
f_bar(v_a);
} else {
f_foo(v_a);
}
g->declareFunction(“foo”);

                                  Facebook 2010 (confidential)
Static Binding – Variables

<?php
$foo = „hello‟;
function foo($a) {
global $foo;
  $bar = $foo . $a;
  return $bar;
}

// C++
String f_foo(CStrRefv_a) {
  Variant &gv_foo = g->GV(foo);
  String v_bar;
v_bar = concat(toString(gv_foo), v_a);
  return v_bar;
}

                                         Facebook 2010 (confidential)
GlobalVariables Class


class GlobalVariables : public SystemGlobals {
public:
 // Direct Global Variables
Variant gv_foo;


 // Indirect Global Variables for large compilation
enum _gv_enums {
gv_foo,
 }
Variant gv[1];
};


                                             Facebook 2010 (confidential)
Dynamic Variables

<?php
function foo() {
  $b = 10;
  $a = 'b';
echo($$a);
}

void f_foo() {
 class VariableTable: public RVariableTable {
 public:
   int64 &v_b; String &v_a;
   VariableTable(int64 &r_b, String &r_a) : v_b(r_b), v_a(r_a) {}
   virtual Variant getImpl(const char *s) {
     // hash – switch – strcmp
   }
 } variableTable(v_b, v_a);

echo(variableTable.get("b”));
}

                                                           Facebook 2010 (confidential)
Static Binding – Constants



<?php
define(„FOO‟, „hello‟);
echo FOO;

// C++
echo(“hello” /* FOO */);




                           Facebook 2010 (confidential)
Dynamic Constants

<?php
if ($condition) {
define(„FOO‟, „hello‟);
} else {
define(„FOO‟, „world‟);
}
echo FOO;

// C++
if (v_condition) {
g->declareConstant("FOO", g->k_FOO, "hello”);
} else {
g->declareConstant("FOO", g->k_FOO, "world”);
}
echo(toString(g->k_FOO));

                                                Facebook 2010 (confidential)
Static Binding with Classes

 Class methods

 Class properties

 Class constants

 Re-declared classes

 Deriving from re-declared classes

 Volatile classes



                                      Facebook 2010 (confidential)
Summary - Dynamic Symbol Lookup
     Problem is nicely solved 

 Rule of 90-10

 Dynamic binding is a general form of static
  binding
 Generated code is a super-set of static
  binding and dynamic binding



                                    Facebook 2010 (confidential)
Problem 2. Weakly Typing

 Type Inference

 Runtime Type Info (RTTI)-Guided Optimization

 Type Hints

 Strongly Typed Collection Classes




                                      Facebook 2010 (confidential)
Type Coercions


                 Variant



Double      String     Array   Object



Integer



Boolean

                                  Facebook 2010 (confidential)
Type Inference Example



<?php
$a = 10;
$a = „string‟;


Variant v_a;



                       Facebook 2010 (confidential)
Why is strong type faster?

$a = $b + $c;

if (is_integer($b) &&is_integer($c)) {
  $a = (int)$b + (int)$c;
} else if (is_array($b) &&is_array($c)) {
  $a = array_merge((array)$b + (array)$c);
} else {
  …
}

int64 v_a = v_b + v_c;
                                    Facebook 2010 (confidential)
Type Inference Blockers

<?php
function foo() {
  if ($success) return 10; // integer
  return false; // doh‟
}

$arr[$a] = 10; // doh‟

++$a; // $a can be a string actually!

$a = $a + 1; // $a can become a double, ouch!

                                    Facebook 2010 (confidential)
RTTI-Guided Optimization

<?php
function foo($x) {
  ...
}


foo(10);
foo(„test‟);


void foo(Variantx) {
  ...
}

                        Facebook 2010 (confidential)
Type Specialization Method 1


template<typename T>
void foo(Tx) {
  // generate code with generic T (tough!)
}

-Pros: smaller generated code
-Cons: no type propagation




                                    Facebook 2010 (confidential)
Type Specialization Method 2


void   foo(int64 x) {
  //   generate code assuming x is integer
}
void   foo(Variantx) {
  //   generate code assuming x is variant
}

-Pros: type propagation
-Cons: variant case is not optimized


                                       Facebook 2010 (confidential)
Type Specialization Method 3

void foo(int64 x) {
    // generate code assuming x is integer
}
void foo(Variantx) {
    if (is_integer(x)) {
        foo(x.toInt64()); return;
    }
    // generate code assuming x is variant
}


-Pros: optimized for integer case
-Cons: large code size


                                             Facebook 2010 (confidential)
Type Hints

<?php
function foo(int$a) {
string $b;
}

class bar {
  public array $c;
}

bar $d;


                           Facebook 2010 (confidential)
Strongly Typed Collection Classes

 That omnipotent “array” in PHP 

 Swapping out underlying implementation:
   Array escalation
   PHP classes:
     Vector
     Set
     Map: un-ordered
     Then Array: ordered map
                                 Facebook 2010 (confidential)
Compiler Friendly Scripting Language


If all problems described here are
  considered when designing a new
  scripting language, will it run
  faster than Java?



                             Facebook 2010 (confidential)

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
An Introduction to Object-Oriented Programming (DrupalCamp London 2015)
An Introduction to Object-Oriented Programming (DrupalCamp London 2015)An Introduction to Object-Oriented Programming (DrupalCamp London 2015)
An Introduction to Object-Oriented Programming (DrupalCamp London 2015)
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Why you-dont-need-design-patterns-in-python
Why you-dont-need-design-patterns-in-pythonWhy you-dont-need-design-patterns-in-python
Why you-dont-need-design-patterns-in-python
 
lab4_php
lab4_phplab4_php
lab4_php
 
Php questions and answers
Php questions and answersPhp questions and answers
Php questions and answers
 
November 2009 - JSR-299 Context & Dependency Injection
November 2009 - JSR-299 Context & Dependency InjectionNovember 2009 - JSR-299 Context & Dependency Injection
November 2009 - JSR-299 Context & Dependency Injection
 
Climbing the Abstract Syntax Tree (Forum PHP 2017)
Climbing the Abstract Syntax Tree (Forum PHP 2017)Climbing the Abstract Syntax Tree (Forum PHP 2017)
Climbing the Abstract Syntax Tree (Forum PHP 2017)
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
 
Climbing the Abstract Syntax Tree (PHP UK 2018)
Climbing the Abstract Syntax Tree (PHP UK 2018)Climbing the Abstract Syntax Tree (PHP UK 2018)
Climbing the Abstract Syntax Tree (PHP UK 2018)
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
Climbing the Abstract Syntax Tree (PHP Russia 2019)
Climbing the Abstract Syntax Tree (PHP Russia 2019)Climbing the Abstract Syntax Tree (PHP Russia 2019)
Climbing the Abstract Syntax Tree (PHP Russia 2019)
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
Climbing the Abstract Syntax Tree (Midwest PHP 2020)
Climbing the Abstract Syntax Tree (Midwest PHP 2020)Climbing the Abstract Syntax Tree (Midwest PHP 2020)
Climbing the Abstract Syntax Tree (Midwest PHP 2020)
 
The one thing to list everything
The one thing to list everythingThe one thing to list everything
The one thing to list everything
 
Climbing the Abstract Syntax Tree (DPC 2017)
Climbing the Abstract Syntax Tree (DPC 2017)Climbing the Abstract Syntax Tree (DPC 2017)
Climbing the Abstract Syntax Tree (DPC 2017)
 

Andere mochten auch

Andere mochten auch (20)

TAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith AdamsTAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith Adams
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHop
 
Hacking
HackingHacking
Hacking
 
Hiphop - PHP
Hiphop - PHPHiphop - PHP
Hiphop - PHP
 
Are you ready to be hacked?
Are you ready to be hacked?Are you ready to be hacked?
Are you ready to be hacked?
 
HHVM and Hack: A quick introduction
HHVM and Hack: A quick introductionHHVM and Hack: A quick introduction
HHVM and Hack: A quick introduction
 
Life As A Fraudster: Carding 101
Life As A Fraudster: Carding 101Life As A Fraudster: Carding 101
Life As A Fraudster: Carding 101
 
Hello world program
Hello world programHello world program
Hello world program
 
Whats app Sniffer - How To Hack Whatsapp Messages
Whats app Sniffer - How To Hack Whatsapp Messages Whats app Sniffer - How To Hack Whatsapp Messages
Whats app Sniffer - How To Hack Whatsapp Messages
 
C language in hindi (cलेग्वेज इन हिंदी )
C language  in hindi (cलेग्वेज इन हिंदी )C language  in hindi (cलेग्वेज इन हिंदी )
C language in hindi (cलेग्वेज इन हिंदी )
 
Broiler Production by Dr. Farooq Sarwar
Broiler Production by Dr. Farooq SarwarBroiler Production by Dr. Farooq Sarwar
Broiler Production by Dr. Farooq Sarwar
 
Whatsapp project work
Whatsapp project workWhatsapp project work
Whatsapp project work
 
關於履歷表, 我想說的其實是...
關於履歷表, 我想說的其實是...關於履歷表, 我想說的其實是...
關於履歷表, 我想說的其實是...
 
Indian Army
Indian ArmyIndian Army
Indian Army
 
Whatsapp PPT Presentation
Whatsapp PPT PresentationWhatsapp PPT Presentation
Whatsapp PPT Presentation
 
How to become a data scientist in 6 months
How to become a data scientist in 6 monthsHow to become a data scientist in 6 months
How to become a data scientist in 6 months
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
whatsapp ppt
whatsapp pptwhatsapp ppt
whatsapp ppt
 
Want to keep your IT career? Never stop learning
Want to keep your IT career? Never stop learningWant to keep your IT career? Never stop learning
Want to keep your IT career? Never stop learning
 
Deep C
Deep CDeep C
Deep C
 

Ähnlich wie Hiphop php

OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
thinkphp
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 

Ähnlich wie Hiphop php (20)

OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
OOP
OOPOOP
OOP
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Hiphop php

  • 1. HipHop Compiler for PHP Transforming PHP into C++ HipHop Compiler Team Facebook, Inc. May 2010 Facebook 2010 (confidential)
  • 2. PHP is easy to read <?php function tally($count) { $sum = 0; for ($i = 0; $i< $count; ++$i) { $sum += $i; } return $sum; } print tally(10) . “n”; Facebook 2010 (confidential)
  • 3. PHP syntax is similar to C++/Java <?php class Tool extends Object { public $name; public use($target) {} } $tool = new Tool(); $tool->name = „hammer‟; $tool->use($nail); Facebook 2010 (confidential)
  • 4. PHP Statements and Expressions FunctionStatement, ClassStatement, InterfaceStatement, ExpressionList, ClassVariable, AssignmentExpression, ClassConstant, SimpleVariable, MethodStatement, DynamicVariable, StatementList, StaticMemberExpression, BlockStatement, ArrayElementExpression, IfBranchStatement, DynamicFunctionCall, IfStatement, SimpleFunctionCall, WhileStatement, ScalarExpression, DoStatement, ObjectPropertyExpression, ForStatement, ObjectMethodExpression, SwitchStatement, ListAssignment, CaseStatement, NewObjectExpression, BreakStatement, UnaryOpExpression, ContinueStatement, IncludeExpression, ReturnStatement, BinaryOpExpression, GlobalStatement, QOpExpression, StaticStatement, ArrayPairExpression, EchoStatement, ClassConstantExpression, UnsetStatement, ParameterExpression, ExpStatement, ModifierExpression, ForEachStatement, ConstantExpression, CatchStatement, EncapsListExpression, TryStatement, ThrowStatement, Facebook 2010 (confidential)
  • 5. PHP is weakly typed <?php $a = 12345; $a = “hello”; $a = array(12345, “hello”, array()); $a = new Object(); $c = $a + $b; // integer or array $c = $a . $b; // implicit casting to strings Facebook 2010 (confidential)
  • 6. Core PHP library is small - Most are in functional style - ~200 to 500 basic functions <?php $len = strlen(“hello”); // C library $ret = curl_exec($curl); // open source Facebook 2010 (confidential)
  • 7. PHP is easy to debug <?php function tally($count) { $sum = 0; for ($i = 0; $i< $count; ++$i) { $sum += $i; var_dump($sum); } return $sum; } Facebook 2010 (confidential)
  • 8. PHP is easy to learn  easy to read  easy to write  easy to debug Hello, World! Facebook 2010 (confidential)
  • 9. PHP is slow  http://shootout.alioth.debian.org/u64q/benchmark.ph p?test=all&lang=all 50 40 30 20 CPU 10 0 C++ Java C# Erlang Python Perl PHP Facebook 2010 (confidential)
  • 10. Why is Zend Engine slow?  Byte-code interpreter  Dynamic symbol lookups  functions, variables, constants  class methods, properties, constants  Weakly typing  zval  array() Facebook 2010 (confidential)
  • 11. Transforming PHP into C++  g++ is a native code compiler  static binding  functions, variables, constants  class methods, properties, constants  type inference  integers, strings, arrays, objects, variants  struct, vector, map, array Facebook 2010 (confidential)
  • 12. Static Binding – Function Calls <?php $ret = foo($a); // C++ Variant v_ret; Variant v_a; v_ret = f_foo(v_a); Facebook 2010 (confidential)
  • 13. Dynamic Function Calls <?php $func = „foo‟; $ret = $func($a); // C++ Variant v_ret; Variant v_a; String v_func; V_func = “foo”; v_ret = invoke(v_func, CREATE_VECTOR1(v_a)); Facebook 2010 (confidential)
  • 14. Function Invoke Table Variant invoke(CStrReffunc, CArrRefparams) { int64 hash = hash_string(func); switch (hash) { case 1234: if (func == “foo”) return foo(params[0]) } throw FatalError(“function not found”); } Facebook 2010 (confidential)
  • 15. Re-declared Functions <?php if ($condition) { function foo($a) { return $a + 1;} } else { function foo($a) { return $a + 2;} } $ret = foo($a); // C++ if (v_condition) { g->i_foo = i_foo$$0; } else { g->i_foo = i_foo$$1; } g->i_foo(v_a); Facebook 2010 (confidential)
  • 16. Volatile Functions <?php if (!function_exists(„foo‟)) { bar($a); } else { foo($a); } function foo($a) {} // C++ if (f_function_exists(“foo”)) { f_bar(v_a); } else { f_foo(v_a); } g->declareFunction(“foo”); Facebook 2010 (confidential)
  • 17. Static Binding – Variables <?php $foo = „hello‟; function foo($a) { global $foo; $bar = $foo . $a; return $bar; } // C++ String f_foo(CStrRefv_a) { Variant &gv_foo = g->GV(foo); String v_bar; v_bar = concat(toString(gv_foo), v_a); return v_bar; } Facebook 2010 (confidential)
  • 18. GlobalVariables Class class GlobalVariables : public SystemGlobals { public: // Direct Global Variables Variant gv_foo; // Indirect Global Variables for large compilation enum _gv_enums { gv_foo, } Variant gv[1]; }; Facebook 2010 (confidential)
  • 19. Dynamic Variables <?php function foo() { $b = 10; $a = 'b'; echo($$a); } void f_foo() { class VariableTable: public RVariableTable { public: int64 &v_b; String &v_a; VariableTable(int64 &r_b, String &r_a) : v_b(r_b), v_a(r_a) {} virtual Variant getImpl(const char *s) { // hash – switch – strcmp } } variableTable(v_b, v_a); echo(variableTable.get("b”)); } Facebook 2010 (confidential)
  • 20. Static Binding – Constants <?php define(„FOO‟, „hello‟); echo FOO; // C++ echo(“hello” /* FOO */); Facebook 2010 (confidential)
  • 21. Dynamic Constants <?php if ($condition) { define(„FOO‟, „hello‟); } else { define(„FOO‟, „world‟); } echo FOO; // C++ if (v_condition) { g->declareConstant("FOO", g->k_FOO, "hello”); } else { g->declareConstant("FOO", g->k_FOO, "world”); } echo(toString(g->k_FOO)); Facebook 2010 (confidential)
  • 22. Static Binding with Classes  Class methods  Class properties  Class constants  Re-declared classes  Deriving from re-declared classes  Volatile classes Facebook 2010 (confidential)
  • 23. Summary - Dynamic Symbol Lookup Problem is nicely solved   Rule of 90-10  Dynamic binding is a general form of static binding  Generated code is a super-set of static binding and dynamic binding Facebook 2010 (confidential)
  • 24. Problem 2. Weakly Typing  Type Inference  Runtime Type Info (RTTI)-Guided Optimization  Type Hints  Strongly Typed Collection Classes Facebook 2010 (confidential)
  • 25. Type Coercions Variant Double String Array Object Integer Boolean Facebook 2010 (confidential)
  • 26. Type Inference Example <?php $a = 10; $a = „string‟; Variant v_a; Facebook 2010 (confidential)
  • 27. Why is strong type faster? $a = $b + $c; if (is_integer($b) &&is_integer($c)) { $a = (int)$b + (int)$c; } else if (is_array($b) &&is_array($c)) { $a = array_merge((array)$b + (array)$c); } else { … } int64 v_a = v_b + v_c; Facebook 2010 (confidential)
  • 28. Type Inference Blockers <?php function foo() { if ($success) return 10; // integer return false; // doh‟ } $arr[$a] = 10; // doh‟ ++$a; // $a can be a string actually! $a = $a + 1; // $a can become a double, ouch! Facebook 2010 (confidential)
  • 29. RTTI-Guided Optimization <?php function foo($x) { ... } foo(10); foo(„test‟); void foo(Variantx) { ... } Facebook 2010 (confidential)
  • 30. Type Specialization Method 1 template<typename T> void foo(Tx) { // generate code with generic T (tough!) } -Pros: smaller generated code -Cons: no type propagation Facebook 2010 (confidential)
  • 31. Type Specialization Method 2 void foo(int64 x) { // generate code assuming x is integer } void foo(Variantx) { // generate code assuming x is variant } -Pros: type propagation -Cons: variant case is not optimized Facebook 2010 (confidential)
  • 32. Type Specialization Method 3 void foo(int64 x) { // generate code assuming x is integer } void foo(Variantx) { if (is_integer(x)) { foo(x.toInt64()); return; } // generate code assuming x is variant } -Pros: optimized for integer case -Cons: large code size Facebook 2010 (confidential)
  • 33. Type Hints <?php function foo(int$a) { string $b; } class bar { public array $c; } bar $d; Facebook 2010 (confidential)
  • 34. Strongly Typed Collection Classes  That omnipotent “array” in PHP   Swapping out underlying implementation:  Array escalation  PHP classes:  Vector  Set  Map: un-ordered  Then Array: ordered map Facebook 2010 (confidential)
  • 35. Compiler Friendly Scripting Language If all problems described here are considered when designing a new scripting language, will it run faster than Java? Facebook 2010 (confidential)