diff
stringlengths
41
2.03M
msg
stringlengths
1
1.5k
repo
stringlengths
5
40
sha
stringlengths
40
40
time
stringlengths
20
20
mmm a / folly / sorted_vector_types . h <nl> ppp b / folly / sorted_vector_types . h <nl> class sorted_vector_set : detail : : growth_policy_wrapper < GrowthPolicy > { <nl> explicit EBO ( const Compare & c , const Allocator & alloc ) noexcept ( <nl> std : : is_nothrow_default_constructible < Container > : : value ) <nl> : Compare ( c ) , cont_ ( alloc ) { } <nl> + EBO ( const EBO & other , const Allocator & alloc ) <nl> + noexcept ( std : : is_nothrow_constructible < <nl> + Container , <nl> + const Container & , <nl> + const Allocator & > : : value ) <nl> + : Compare ( static_cast < const Compare & > ( other ) ) , <nl> + cont_ ( other . cont_ , alloc ) { } <nl> EBO ( EBO & & other , const Allocator & alloc ) <nl> noexcept ( std : : is_nothrow_constructible < <nl> Container , <nl> Container & & , <nl> const Allocator & > : : value ) <nl> - : Compare ( ) , cont_ ( std : : move ( other . cont_ ) , alloc ) { } <nl> + : Compare ( static_cast < Compare & & > ( other ) ) , <nl> + cont_ ( std : : move ( other . cont_ ) , alloc ) { } <nl> EBO ( const Compare & c , Container & & cont ) <nl> noexcept ( std : : is_nothrow_move_constructible < Container > : : value ) <nl> : Compare ( c ) , cont_ ( std : : move ( cont ) ) { } <nl> class sorted_vector_map : detail : : growth_policy_wrapper < GrowthPolicy > { <nl> explicit EBO ( const value_compare & c , const Allocator & alloc ) noexcept ( <nl> std : : is_nothrow_default_constructible < Container > : : value ) <nl> : value_compare ( c ) , cont_ ( alloc ) { } <nl> + EBO ( const EBO & other , const Allocator & alloc ) <nl> + noexcept ( std : : is_nothrow_constructible < <nl> + Container , <nl> + const Container & , <nl> + const Allocator & > : : value ) <nl> + : value_compare ( static_cast < const value_compare & > ( other ) ) , <nl> + cont_ ( other . cont_ , alloc ) { } <nl> EBO ( EBO & & other , const Allocator & alloc ) <nl> noexcept ( std : : is_nothrow_constructible < <nl> Container , <nl> Container & & , <nl> const Allocator & > : : value ) <nl> - : value_compare ( Compare ( ) ) , cont_ ( std : : move ( other . cont_ ) , alloc ) { } <nl> + : value_compare ( static_cast < value_compare & & > ( other ) ) , <nl> + cont_ ( std : : move ( other . cont_ ) , alloc ) { } <nl> EBO ( const Compare & c , Container & & cont ) <nl> noexcept ( std : : is_nothrow_move_constructible < Container > : : value ) <nl> : value_compare ( c ) , cont_ ( std : : move ( cont ) ) { } <nl> mmm a / folly / test / sorted_vector_test . cpp <nl> ppp b / folly / test / sorted_vector_test . cpp <nl> TEST ( SortedVectorTypes , TestPmrAllocatorSimple ) { <nl> EXPECT_THROW ( m . emplace ( 42 , 42 ) , std : : bad_alloc ) ; <nl> } <nl> <nl> + TEST ( SortedVectorTypes , TestPmrCopyConstructSameAlloc ) { <nl> + namespace pmr = folly : : pmr ; <nl> + <nl> + set_default_resource ( null_memory_resource ( ) ) ; <nl> + <nl> + test_resource r ; <nl> + polymorphic_allocator < std : : byte > a1 ( & r ) , a2 ( & r ) ; <nl> + EXPECT_EQ ( a1 , a2 ) ; <nl> + <nl> + { <nl> + pmr : : sorted_vector_set < int > s1 ( a1 ) ; <nl> + s1 . emplace ( 42 ) ; <nl> + <nl> + pmr : : sorted_vector_set < int > s2 ( s1 , a2 ) ; <nl> + EXPECT_EQ ( s1 . get_allocator ( ) , s2 . get_allocator ( ) ) ; <nl> + EXPECT_EQ ( s2 . count ( 42 ) , 1 ) ; <nl> + } <nl> + <nl> + { <nl> + pmr : : sorted_vector_map < int , int > m1 ( a1 ) ; <nl> + m1 . emplace ( 42 , 42 ) ; <nl> + <nl> + pmr : : sorted_vector_map < int , int > m2 ( m1 , a2 ) ; <nl> + EXPECT_EQ ( m1 . get_allocator ( ) , m2 . get_allocator ( ) ) ; <nl> + EXPECT_EQ ( m2 . at ( 42 ) , 42 ) ; <nl> + } <nl> + } <nl> + <nl> + TEST ( SortedVectorTypes , TestPmrCopyConstructDifferentAlloc ) { <nl> + namespace pmr = folly : : pmr ; <nl> + <nl> + set_default_resource ( null_memory_resource ( ) ) ; <nl> + <nl> + test_resource r1 , r2 ; <nl> + polymorphic_allocator < std : : byte > a1 ( & r1 ) , a2 ( & r2 ) ; <nl> + EXPECT_NE ( a1 , a2 ) ; <nl> + <nl> + { <nl> + pmr : : sorted_vector_set < int > s1 ( a1 ) ; <nl> + s1 . emplace ( 42 ) ; <nl> + <nl> + pmr : : sorted_vector_set < int > s2 ( s1 , a2 ) ; <nl> + EXPECT_NE ( s1 . get_allocator ( ) , s2 . get_allocator ( ) ) ; <nl> + EXPECT_EQ ( s2 . count ( 42 ) , 1 ) ; <nl> + } <nl> + <nl> + { <nl> + pmr : : sorted_vector_map < int , int > m1 ( a1 ) ; <nl> + m1 . emplace ( 42 , 42 ) ; <nl> + <nl> + pmr : : sorted_vector_map < int , int > m2 ( m1 , a2 ) ; <nl> + EXPECT_NE ( m1 . get_allocator ( ) , m2 . get_allocator ( ) ) ; <nl> + EXPECT_EQ ( m2 . at ( 42 ) , 42 ) ; <nl> + } <nl> + } <nl> + <nl> TEST ( SortedVectorTypes , TestPmrMoveConstructSameAlloc ) { <nl> namespace pmr = folly : : pmr ; <nl> <nl> TEST ( SortedVectorTypes , TestPmrMoveConstructSameAlloc ) { <nl> auto d = s1 . data ( ) ; <nl> <nl> pmr : : sorted_vector_set < int > s2 ( std : : move ( s1 ) , a2 ) ; <nl> + EXPECT_EQ ( s1 . get_allocator ( ) , s2 . get_allocator ( ) ) ; <nl> EXPECT_EQ ( s2 . data ( ) , d ) ; <nl> + EXPECT_EQ ( s2 . count ( 42 ) , 1 ) ; <nl> } <nl> <nl> { <nl> TEST ( SortedVectorTypes , TestPmrMoveConstructSameAlloc ) { <nl> auto d = m1 . data ( ) ; <nl> <nl> pmr : : sorted_vector_map < int , int > m2 ( std : : move ( m1 ) , a2 ) ; <nl> + EXPECT_EQ ( m1 . get_allocator ( ) , m2 . get_allocator ( ) ) ; <nl> EXPECT_EQ ( m2 . data ( ) , d ) ; <nl> + EXPECT_EQ ( m2 . at ( 42 ) , 42 ) ; <nl> } <nl> } <nl> <nl> TEST ( SortedVectorTypes , TestPmrMoveConstructDifferentAlloc ) { <nl> auto d = s1 . data ( ) ; <nl> <nl> pmr : : sorted_vector_set < int > s2 ( std : : move ( s1 ) , a2 ) ; <nl> + EXPECT_NE ( s1 . get_allocator ( ) , s2 . get_allocator ( ) ) ; <nl> EXPECT_NE ( s2 . data ( ) , d ) ; <nl> + EXPECT_EQ ( s2 . count ( 42 ) , 1 ) ; <nl> } <nl> <nl> { <nl> TEST ( SortedVectorTypes , TestPmrMoveConstructDifferentAlloc ) { <nl> auto d = m1 . data ( ) ; <nl> <nl> pmr : : sorted_vector_map < int , int > m2 ( std : : move ( m1 ) , a2 ) ; <nl> + EXPECT_NE ( m1 . get_allocator ( ) , m2 . get_allocator ( ) ) ; <nl> EXPECT_NE ( m2 . data ( ) , d ) ; <nl> + EXPECT_EQ ( m2 . at ( 42 ) , 42 ) ; <nl> } <nl> } <nl> <nl>
bugfix sorted_vector_types allocator - extended c ' ctor
facebook/folly
c27460f2a6ff98ff89177afcfa048d8121fb5369
2019-09-11T14:18:25Z
mmm a / src / mongo / db / repl / rs_rollback . cpp <nl> ppp b / src / mongo / db / repl / rs_rollback . cpp <nl> namespace { <nl> <nl> / / Add the doc to our rollback file <nl> BSONObj obj ; <nl> - bool found = Helpers : : findOne ( txn , ctx . db ( ) - > getCollection ( doc . ns ) , pattern , obj , false ) ; <nl> - if ( found ) { <nl> - removeSaver - > goingToDelete ( obj ) ; <nl> - } <nl> - else { <nl> - error ( ) < < " rollback cannot find object : " < < pattern <nl> - < < " in namespace " < < doc . ns ; <nl> + Collection * collection = ctx . db ( ) - > getCollection ( doc . ns ) ; <nl> + <nl> + / / Do not log an error when undoing an insert on a no longer existent collection . <nl> + / / It is likely that the collection was dropped as part of rolling back a <nl> + / / createCollection command and regardless , the document no longer exists . <nl> + if ( collection ) { <nl> + bool found = Helpers : : findOne ( txn , collection , pattern , obj , false ) ; <nl> + if ( found ) { <nl> + removeSaver - > goingToDelete ( obj ) ; <nl> + } <nl> + else { <nl> + error ( ) < < " rollback cannot find object : " < < pattern <nl> + < < " in namespace " < < doc . ns ; <nl> + } <nl> } <nl> <nl> if ( it - > second . isEmpty ( ) ) { <nl> namespace { <nl> / / TODO 1 . 6 : can ' t delete from a capped collection . need to handle that here . <nl> deletes + + ; <nl> <nl> - Collection * collection = ctx . db ( ) - > getCollection ( doc . ns ) ; <nl> if ( collection ) { <nl> if ( collection - > isCapped ( ) ) { <nl> / / can ' t delete from a capped collection - so we truncate instead . if <nl>
SERVER - 18211 do not log a message when rolling back an insert for a dropped collection
mongodb/mongo
91a530bf170231a0f3024e130e1c798a544f5375
2015-04-29T09:42:07Z
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> include ( cmake / OpenCVModule . cmake ) <nl> # Detect endianness of build platform <nl> # mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> <nl> - if ( CMAKE_SYSTEM_NAME STREQUAL iOS ) <nl> + if ( IOS ) <nl> # test_big_endian needs try_compile , which doesn ' t work for iOS <nl> # http : / / public . kitware . com / Bug / view . php ? id = 12288 <nl> set ( WORDS_BIGENDIAN 0 ) <nl>
Merge pull request from ruslo : unify . ios
opencv/opencv
3109c770131acc00bc5062475e73cd5b4743519a
2015-05-15T12:32:05Z
mmm a / src / common / CMakeLists . txt <nl> ppp b / src / common / CMakeLists . txt <nl> if ( $ ENV { CI } ) <nl> string ( SUBSTRING $ { WORD } 1 - 1 REMAINDER ) <nl> string ( TOUPPER $ { FIRST_LETTER } FIRST_LETTER ) <nl> # this leaves a trailing space on the last word , but we actually want that <nl> - # because of how its styled in the title bar . <nl> + # because of how it ' s styled in the title bar . <nl> set ( REPO_NAME " $ { REPO_NAME } $ { FIRST_LETTER } $ { REMAINDER } " ) <nl> endforeach ( ) <nl> endif ( ) <nl>
Merge pull request from akkatracker / patch - 1
yuzu-emu/yuzu
ee024eb0a2836fb94cf3c70621ab1e0d091cd5d3
2018-01-21T18:06:37Z
mmm a / tensorflow / contrib / learn / BUILD <nl> ppp b / tensorflow / contrib / learn / BUILD <nl> py_test ( <nl> ] , <nl> ) <nl> <nl> + py_test ( <nl> + name = " metric_spec_test " , <nl> + size = " small " , <nl> + srcs = [ " python / learn / metric_spec_test . py " ] , <nl> + srcs_version = " PY2AND3 " , <nl> + deps = [ <nl> + " : learn " , <nl> + " / / tensorflow : tensorflow_py " , <nl> + " / / tensorflow / python : framework_test_lib " , <nl> + ] , <nl> + ) <nl> + <nl> py_test ( <nl> name = " experiment_test " , <nl> size = " small " , <nl> mmm a / tensorflow / contrib / learn / python / learn / metric_spec_test . py <nl> ppp b / tensorflow / contrib / learn / python / learn / metric_spec_test . py <nl> def test_fail_no_prediction ( self ) : <nl> predictions = { " pred1 " : " pred1_tensor " , " pred2 " : " pred2_tensor " } <nl> <nl> self . assertRaisesRegexp ( ValueError , <nl> - " MetricSpec without specified prediction requires " <nl> - " predictions tensor or single element dict , got " , <nl> + " MetricSpec without specified prediction_key " <nl> + " requires predictions tensor or single element " <nl> + " dict , got " , <nl> MetricSpec ( metric_fn = test_metric , <nl> label_key = " label1 " , <nl> weight_key = " feature2 " ) . create_metric_ops , <nl> def test_fail_no_label ( self ) : <nl> predictions = { " pred1 " : " pred1_tensor " , " pred2 " : " pred2_tensor " } <nl> <nl> self . assertRaisesRegexp ( ValueError , <nl> - " MetricSpec without specified label requires " <nl> + " MetricSpec without specified label_key requires " <nl> " labels tensor or single element dict , got " , <nl> MetricSpec ( metric_fn = test_metric , <nl> prediction_key = " pred1 " , <nl> def test_fail_single_prediction ( self ) : <nl> predictions = " pred1_tensor " <nl> <nl> self . assertRaisesRegexp ( ValueError , <nl> - " MetricSpec with specified prediction requires " <nl> + " MetricSpec with prediction_key specified requires " <nl> " predictions dict , got " , <nl> MetricSpec ( metric_fn = test_metric , <nl> prediction_key = " pred1 " , <nl> def test_fail_single_label ( self ) : <nl> predictions = { " pred1 " : " pred1_tensor " , " pred2 " : " pred2_tensor " } <nl> <nl> self . assertRaisesRegexp ( ValueError , <nl> - " MetricSpec with specified label requires " <nl> + " MetricSpec with label_key specified requires " <nl> " labels dict , got " , <nl> MetricSpec ( metric_fn = test_metric , <nl> prediction_key = " pred1 " , <nl>
Fix metric_spec_test .
tensorflow/tensorflow
f366a3bcfd23d943615b17fd7103ddfa8e72c585
2016-09-02T19:48:57Z
mmm a / tensorflow / python / training / sync_replicas_optimizer . py <nl> ppp b / tensorflow / python / training / sync_replicas_optimizer . py <nl> def get_init_tokens_op ( self , num_tokens = - 1 ) : <nl> if num_tokens > 0 : <nl> with ops . device ( self . _global_step . device ) , ops . name_scope ( " " ) : <nl> tokens = array_ops . fill ( [ num_tokens ] , <nl> - self . _global_step . ref ( ) ) <nl> + self . _global_step . _ref ( ) ) # pylint : disable = protected - access <nl> init_tokens = self . _sync_token_queue . enqueue_many ( ( tokens , ) ) <nl> else : <nl> init_tokens = control_flow_ops . no_op ( name = " no_init_tokens " ) <nl>
Another missed _ref in sync_replicas_optimizer .
tensorflow/tensorflow
4dcd9c50c7ba359e3d31a7d0242f7b89387fc2aa
2016-11-17T20:45:03Z
mmm a / src / json . hpp <nl> ppp b / src / json . hpp <nl> class basic_json <nl> return false ; <nl> } <nl> <nl> - / * ! <nl> - @ brief comparison : equal <nl> - <nl> - The functions compares the given JSON value against a null pointer . As the <nl> - null pointer can be used to initialize a JSON value to null , a comparison <nl> - of JSON value @ a v with a null pointer should be equivalent to call <nl> - ` v . is_null ( ) ` . <nl> - <nl> - @ param [ in ] v JSON value to consider <nl> - @ return whether @ a v is null <nl> - <nl> - @ complexity Constant . <nl> - <nl> - @ liveexample { The example compares several JSON types to the null pointer . <nl> - , operator__equal__nullptr_t } <nl> - <nl> - @ since version 1 . 0 . 0 <nl> + / * ! @ brief comparison : equal <nl> + @ copydoc operator = = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator = = ( const_reference v , std : : nullptr_t ) noexcept <nl> - { <nl> - return v . is_null ( ) ; <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator = = ( const_reference lhs , const ScalarType rhs ) noexcept { <nl> + return ( lhs = = basic_json ( rhs ) ) ; <nl> } <nl> <nl> / * ! <nl> @ brief comparison : equal <nl> - @ copydoc operator = = ( const_reference , std : : nullptr_t ) <nl> + @ copydoc operator = = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator = = ( std : : nullptr_t , const_reference v ) noexcept <nl> - { <nl> - return v . is_null ( ) ; <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator = = ( const ScalarType lhs , const_reference rhs ) noexcept { <nl> + return ( basic_json ( lhs ) = = rhs ) ; <nl> } <nl> <nl> / * ! <nl> class basic_json <nl> <nl> / * ! <nl> @ brief comparison : not equal <nl> - <nl> - The functions compares the given JSON value against a null pointer . As the <nl> - null pointer can be used to initialize a JSON value to null , a comparison <nl> - of JSON value @ a v with a null pointer should be equivalent to call <nl> - ` not v . is_null ( ) ` . <nl> - <nl> - @ param [ in ] v JSON value to consider <nl> - @ return whether @ a v is not null <nl> - <nl> - @ complexity Constant . <nl> - <nl> - @ liveexample { The example compares several JSON types to the null pointer . <nl> - , operator__notequal__nullptr_t } <nl> - <nl> - @ since version 1 . 0 . 0 <nl> + @ copydoc operator ! = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator ! = ( const_reference v , std : : nullptr_t ) noexcept <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator ! = ( const_reference lhs , const ScalarType rhs ) noexcept <nl> { <nl> - return not v . is_null ( ) ; <nl> + return ( lhs ! = basic_json ( rhs ) ) ; <nl> } <nl> <nl> / * ! <nl> @ brief comparison : not equal <nl> - @ copydoc operator ! = ( const_reference , std : : nullptr_t ) <nl> + @ copydoc operator ! = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator ! = ( std : : nullptr_t , const_reference v ) noexcept <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator ! = ( const ScalarType lhs , const_reference rhs ) noexcept <nl> { <nl> - return not v . is_null ( ) ; <nl> + return ( basic_json ( lhs ) ! = rhs ) ; <nl> } <nl> <nl> / * ! <nl> class basic_json <nl> m_start = m_cursor ; <nl> assert ( m_start ! = nullptr ) ; <nl> <nl> - <nl> - { <nl> - lexer_char_t yych ; <nl> - unsigned int yyaccept = 0 ; <nl> - static const unsigned char yybm [ ] = <nl> - { <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 32 , 32 , 0 , 0 , 32 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 160 , 128 , 0 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 192 , 192 , 192 , 192 , 192 , 192 , 192 , 192 , <nl> - 192 , 192 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 0 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> - } ; <nl> - if ( ( m_limit - m_cursor ) < 5 ) <nl> - { <nl> - fill_line_buffer ( 5 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yybm [ 0 + yych ] & 32 ) <nl> - { <nl> - goto basic_json_parser_6 ; <nl> - } <nl> - if ( yych < = ' [ ' ) <nl> - { <nl> - if ( yych < = ' - ' ) <nl> - { <nl> - if ( yych < = ' " ' ) <nl> - { <nl> - if ( yych < = 0x00 ) <nl> - { <nl> - goto basic_json_parser_2 ; <nl> - } <nl> - if ( yych < = ' ! ' ) <nl> - { <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - goto basic_json_parser_9 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' + ' ) <nl> - { <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - if ( yych < = ' , ' ) <nl> - { <nl> - goto basic_json_parser_10 ; <nl> - } <nl> - goto basic_json_parser_12 ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - if ( yych < = ' 0 ' ) <nl> - { <nl> - goto basic_json_parser_13 ; <nl> - } <nl> - goto basic_json_parser_15 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' : ' ) <nl> - { <nl> - goto basic_json_parser_17 ; <nl> - } <nl> - if ( yych < = ' Z ' ) <nl> - { <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - goto basic_json_parser_19 ; <nl> - } <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' n ' ) <nl> - { <nl> - if ( yych < = ' e ' ) <nl> - { <nl> - if ( yych = = ' ] ' ) <nl> - { <nl> - goto basic_json_parser_21 ; <nl> - } <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_23 ; <nl> - } <nl> - if ( yych < = ' m ' ) <nl> - { <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - goto basic_json_parser_24 ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' z ' ) <nl> - { <nl> - if ( yych = = ' t ' ) <nl> - { <nl> - goto basic_json_parser_25 ; <nl> - } <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' { ' ) <nl> - { <nl> - goto basic_json_parser_26 ; <nl> - } <nl> - if ( yych = = ' } ' ) <nl> - { <nl> - goto basic_json_parser_28 ; <nl> - } <nl> - goto basic_json_parser_4 ; <nl> - } <nl> - } <nl> - } <nl> + <nl> + { <nl> + lexer_char_t yych ; <nl> + unsigned int yyaccept = 0 ; <nl> + static const unsigned char yybm [ ] = { <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 32 , 32 , 0 , 0 , 32 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 160 , 128 , 0 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 192 , 192 , 192 , 192 , 192 , 192 , 192 , 192 , <nl> + 192 , 192 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 0 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 128 , 128 , 128 , 128 , 128 , 128 , 128 , 128 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , <nl> + } ; <nl> + if ( ( m_limit - m_cursor ) < 5 ) fill_line_buffer ( 5 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yybm [ 0 + yych ] & 32 ) { <nl> + goto basic_json_parser_6 ; <nl> + } <nl> + if ( yych < = ' [ ' ) { <nl> + if ( yych < = ' - ' ) { <nl> + if ( yych < = ' " ' ) { <nl> + if ( yych < = 0x00 ) goto basic_json_parser_2 ; <nl> + if ( yych < = ' ! ' ) goto basic_json_parser_4 ; <nl> + goto basic_json_parser_9 ; <nl> + } else { <nl> + if ( yych < = ' + ' ) goto basic_json_parser_4 ; <nl> + if ( yych < = ' , ' ) goto basic_json_parser_10 ; <nl> + goto basic_json_parser_12 ; <nl> + } <nl> + } else { <nl> + if ( yych < = ' 9 ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_4 ; <nl> + if ( yych < = ' 0 ' ) goto basic_json_parser_13 ; <nl> + goto basic_json_parser_15 ; <nl> + } else { <nl> + if ( yych < = ' : ' ) goto basic_json_parser_17 ; <nl> + if ( yych < = ' Z ' ) goto basic_json_parser_4 ; <nl> + goto basic_json_parser_19 ; <nl> + } <nl> + } <nl> + } else { <nl> + if ( yych < = ' n ' ) { <nl> + if ( yych < = ' e ' ) { <nl> + if ( yych = = ' ] ' ) goto basic_json_parser_21 ; <nl> + goto basic_json_parser_4 ; <nl> + } else { <nl> + if ( yych < = ' f ' ) goto basic_json_parser_23 ; <nl> + if ( yych < = ' m ' ) goto basic_json_parser_4 ; <nl> + goto basic_json_parser_24 ; <nl> + } <nl> + } else { <nl> + if ( yych < = ' z ' ) { <nl> + if ( yych = = ' t ' ) goto basic_json_parser_25 ; <nl> + goto basic_json_parser_4 ; <nl> + } else { <nl> + if ( yych < = ' { ' ) goto basic_json_parser_26 ; <nl> + if ( yych = = ' } ' ) goto basic_json_parser_28 ; <nl> + goto basic_json_parser_4 ; <nl> + } <nl> + } <nl> + } <nl> basic_json_parser_2 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : end_of_input ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : end_of_input ; break ; } <nl> basic_json_parser_4 : <nl> - + + m_cursor ; <nl> + + + m_cursor ; <nl> basic_json_parser_5 : <nl> - { <nl> - last_token_type = token_type : : parse_error ; <nl> - break ; <nl> - } <nl> + { last_token_type = token_type : : parse_error ; break ; } <nl> basic_json_parser_6 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yybm [ 0 + yych ] & 32 ) <nl> - { <nl> - goto basic_json_parser_6 ; <nl> - } <nl> - { <nl> - continue ; <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yybm [ 0 + yych ] & 32 ) { <nl> + goto basic_json_parser_6 ; <nl> + } <nl> + { continue ; } <nl> basic_json_parser_9 : <nl> - yyaccept = 0 ; <nl> - yych = * ( m_marker = + + m_cursor ) ; <nl> - if ( yych < = 0x1F ) <nl> - { <nl> - goto basic_json_parser_5 ; <nl> - } <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_31 ; <nl> - } <nl> - if ( yych < = 0xC1 ) <nl> - { <nl> - goto basic_json_parser_5 ; <nl> - } <nl> - if ( yych < = 0xF4 ) <nl> - { <nl> - goto basic_json_parser_31 ; <nl> - } <nl> - goto basic_json_parser_5 ; <nl> + yyaccept = 0 ; <nl> + yych = * ( m_marker = + + m_cursor ) ; <nl> + if ( yych < = 0x1F ) goto basic_json_parser_5 ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_31 ; <nl> + if ( yych < = 0xC1 ) goto basic_json_parser_5 ; <nl> + if ( yych < = 0xF4 ) goto basic_json_parser_31 ; <nl> + goto basic_json_parser_5 ; <nl> basic_json_parser_10 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : value_separator ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : value_separator ; break ; } <nl> basic_json_parser_12 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_5 ; <nl> - } <nl> - if ( yych < = ' 0 ' ) <nl> - { <nl> - goto basic_json_parser_13 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_15 ; <nl> - } <nl> - goto basic_json_parser_5 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych < = ' / ' ) goto basic_json_parser_5 ; <nl> + if ( yych < = ' 0 ' ) goto basic_json_parser_13 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_15 ; <nl> + goto basic_json_parser_5 ; <nl> basic_json_parser_13 : <nl> - yyaccept = 1 ; <nl> - yych = * ( m_marker = + + m_cursor ) ; <nl> - if ( yych < = ' D ' ) <nl> - { <nl> - if ( yych = = ' . ' ) <nl> - { <nl> - goto basic_json_parser_43 ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' E ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - if ( yych = = ' e ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - } <nl> + yyaccept = 1 ; <nl> + yych = * ( m_marker = + + m_cursor ) ; <nl> + if ( yych < = ' D ' ) { <nl> + if ( yych = = ' . ' ) goto basic_json_parser_43 ; <nl> + } else { <nl> + if ( yych < = ' E ' ) goto basic_json_parser_44 ; <nl> + if ( yych = = ' e ' ) goto basic_json_parser_44 ; <nl> + } <nl> basic_json_parser_14 : <nl> - { <nl> - last_token_type = token_type : : value_number ; <nl> - break ; <nl> - } <nl> + { last_token_type = token_type : : value_number ; break ; } <nl> basic_json_parser_15 : <nl> - yyaccept = 1 ; <nl> - m_marker = + + m_cursor ; <nl> - if ( ( m_limit - m_cursor ) < 3 ) <nl> - { <nl> - fill_line_buffer ( 3 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yybm [ 0 + yych ] & 64 ) <nl> - { <nl> - goto basic_json_parser_15 ; <nl> - } <nl> - if ( yych < = ' D ' ) <nl> - { <nl> - if ( yych = = ' . ' ) <nl> - { <nl> - goto basic_json_parser_43 ; <nl> - } <nl> - goto basic_json_parser_14 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' E ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - if ( yych = = ' e ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - goto basic_json_parser_14 ; <nl> - } <nl> + yyaccept = 1 ; <nl> + m_marker = + + m_cursor ; <nl> + if ( ( m_limit - m_cursor ) < 3 ) fill_line_buffer ( 3 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yybm [ 0 + yych ] & 64 ) { <nl> + goto basic_json_parser_15 ; <nl> + } <nl> + if ( yych < = ' D ' ) { <nl> + if ( yych = = ' . ' ) goto basic_json_parser_43 ; <nl> + goto basic_json_parser_14 ; <nl> + } else { <nl> + if ( yych < = ' E ' ) goto basic_json_parser_44 ; <nl> + if ( yych = = ' e ' ) goto basic_json_parser_44 ; <nl> + goto basic_json_parser_14 ; <nl> + } <nl> basic_json_parser_17 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : name_separator ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : name_separator ; break ; } <nl> basic_json_parser_19 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : begin_array ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : begin_array ; break ; } <nl> basic_json_parser_21 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : end_array ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : end_array ; break ; } <nl> basic_json_parser_23 : <nl> - yyaccept = 0 ; <nl> - yych = * ( m_marker = + + m_cursor ) ; <nl> - if ( yych = = ' a ' ) <nl> - { <nl> - goto basic_json_parser_45 ; <nl> - } <nl> - goto basic_json_parser_5 ; <nl> + yyaccept = 0 ; <nl> + yych = * ( m_marker = + + m_cursor ) ; <nl> + if ( yych = = ' a ' ) goto basic_json_parser_45 ; <nl> + goto basic_json_parser_5 ; <nl> basic_json_parser_24 : <nl> - yyaccept = 0 ; <nl> - yych = * ( m_marker = + + m_cursor ) ; <nl> - if ( yych = = ' u ' ) <nl> - { <nl> - goto basic_json_parser_46 ; <nl> - } <nl> - goto basic_json_parser_5 ; <nl> + yyaccept = 0 ; <nl> + yych = * ( m_marker = + + m_cursor ) ; <nl> + if ( yych = = ' u ' ) goto basic_json_parser_46 ; <nl> + goto basic_json_parser_5 ; <nl> basic_json_parser_25 : <nl> - yyaccept = 0 ; <nl> - yych = * ( m_marker = + + m_cursor ) ; <nl> - if ( yych = = ' r ' ) <nl> - { <nl> - goto basic_json_parser_47 ; <nl> - } <nl> - goto basic_json_parser_5 ; <nl> + yyaccept = 0 ; <nl> + yych = * ( m_marker = + + m_cursor ) ; <nl> + if ( yych = = ' r ' ) goto basic_json_parser_47 ; <nl> + goto basic_json_parser_5 ; <nl> basic_json_parser_26 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : begin_object ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : begin_object ; break ; } <nl> basic_json_parser_28 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : end_object ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : end_object ; break ; } <nl> basic_json_parser_30 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> basic_json_parser_31 : <nl> - if ( yybm [ 0 + yych ] & 128 ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - if ( yych < = 0xE0 ) <nl> - { <nl> - if ( yych < = ' \ \ ' ) <nl> - { <nl> - if ( yych < = 0x1F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' " ' ) <nl> - { <nl> - goto basic_json_parser_33 ; <nl> - } <nl> - goto basic_json_parser_35 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = 0xC1 ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xDF ) <nl> - { <nl> - goto basic_json_parser_36 ; <nl> - } <nl> - goto basic_json_parser_37 ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = 0xEF ) <nl> - { <nl> - if ( yych = = 0xED ) <nl> - { <nl> - goto basic_json_parser_39 ; <nl> - } <nl> - goto basic_json_parser_38 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = 0xF0 ) <nl> - { <nl> - goto basic_json_parser_40 ; <nl> - } <nl> - if ( yych < = 0xF3 ) <nl> - { <nl> - goto basic_json_parser_41 ; <nl> - } <nl> - if ( yych < = 0xF4 ) <nl> - { <nl> - goto basic_json_parser_42 ; <nl> - } <nl> - } <nl> - } <nl> + if ( yybm [ 0 + yych ] & 128 ) { <nl> + goto basic_json_parser_30 ; <nl> + } <nl> + if ( yych < = 0xE0 ) { <nl> + if ( yych < = ' \ \ ' ) { <nl> + if ( yych < = 0x1F ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' " ' ) goto basic_json_parser_33 ; <nl> + goto basic_json_parser_35 ; <nl> + } else { <nl> + if ( yych < = 0xC1 ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xDF ) goto basic_json_parser_36 ; <nl> + goto basic_json_parser_37 ; <nl> + } <nl> + } else { <nl> + if ( yych < = 0xEF ) { <nl> + if ( yych = = 0xED ) goto basic_json_parser_39 ; <nl> + goto basic_json_parser_38 ; <nl> + } else { <nl> + if ( yych < = 0xF0 ) goto basic_json_parser_40 ; <nl> + if ( yych < = 0xF3 ) goto basic_json_parser_41 ; <nl> + if ( yych < = 0xF4 ) goto basic_json_parser_42 ; <nl> + } <nl> + } <nl> basic_json_parser_32 : <nl> - m_cursor = m_marker ; <nl> - if ( yyaccept = = 0 ) <nl> - { <nl> - goto basic_json_parser_5 ; <nl> - } <nl> - else <nl> - { <nl> - goto basic_json_parser_14 ; <nl> - } <nl> + m_cursor = m_marker ; <nl> + if ( yyaccept = = 0 ) { <nl> + goto basic_json_parser_5 ; <nl> + } else { <nl> + goto basic_json_parser_14 ; <nl> + } <nl> basic_json_parser_33 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : value_string ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : value_string ; break ; } <nl> basic_json_parser_35 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' e ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - if ( yych = = ' " ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - if ( yych < = ' . ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' \ \ ' ) <nl> - { <nl> - if ( yych < = ' [ ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych = = ' b ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - } <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' q ' ) <nl> - { <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - if ( yych = = ' n ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' s ' ) <nl> - { <nl> - if ( yych < = ' r ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' t ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - if ( yych < = ' u ' ) <nl> - { <nl> - goto basic_json_parser_48 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - } <nl> - } <nl> - basic_json_parser_36 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xBF ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' e ' ) { <nl> + if ( yych < = ' / ' ) { <nl> + if ( yych = = ' " ' ) goto basic_json_parser_30 ; <nl> + if ( yych < = ' . ' ) goto basic_json_parser_32 ; <nl> + goto basic_json_parser_30 ; <nl> + } else { <nl> + if ( yych < = ' \ \ ' ) { <nl> + if ( yych < = ' [ ' ) goto basic_json_parser_32 ; <nl> + goto basic_json_parser_30 ; <nl> + } else { <nl> + if ( yych = = ' b ' ) goto basic_json_parser_30 ; <nl> goto basic_json_parser_32 ; <nl> - basic_json_parser_37 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x9F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xBF ) <nl> - { <nl> - goto basic_json_parser_36 ; <nl> - } <nl> + } <nl> + } <nl> + } else { <nl> + if ( yych < = ' q ' ) { <nl> + if ( yych < = ' f ' ) goto basic_json_parser_30 ; <nl> + if ( yych = = ' n ' ) goto basic_json_parser_30 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' s ' ) { <nl> + if ( yych < = ' r ' ) goto basic_json_parser_30 ; <nl> goto basic_json_parser_32 ; <nl> - basic_json_parser_38 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xBF ) <nl> - { <nl> - goto basic_json_parser_36 ; <nl> - } <nl> + } else { <nl> + if ( yych < = ' t ' ) goto basic_json_parser_30 ; <nl> + if ( yych < = ' u ' ) goto basic_json_parser_48 ; <nl> goto basic_json_parser_32 ; <nl> + } <nl> + } <nl> + } <nl> + basic_json_parser_36 : <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xBF ) goto basic_json_parser_30 ; <nl> + goto basic_json_parser_32 ; <nl> + basic_json_parser_37 : <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x9F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xBF ) goto basic_json_parser_36 ; <nl> + goto basic_json_parser_32 ; <nl> + basic_json_parser_38 : <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xBF ) goto basic_json_parser_36 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_39 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0x9F ) <nl> - { <nl> - goto basic_json_parser_36 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0x9F ) goto basic_json_parser_36 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_40 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x8F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xBF ) <nl> - { <nl> - goto basic_json_parser_38 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x8F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xBF ) goto basic_json_parser_38 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_41 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0xBF ) <nl> - { <nl> - goto basic_json_parser_38 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0xBF ) goto basic_json_parser_38 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_42 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = 0x7F ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = 0x8F ) <nl> - { <nl> - goto basic_json_parser_38 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = 0x7F ) goto basic_json_parser_32 ; <nl> + if ( yych < = 0x8F ) goto basic_json_parser_38 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_43 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_49 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_49 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_44 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych < = ' , ' ) <nl> - { <nl> - if ( yych = = ' + ' ) <nl> - { <nl> - goto basic_json_parser_51 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' - ' ) <nl> - { <nl> - goto basic_json_parser_51 ; <nl> - } <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_52 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> + yych = * + + m_cursor ; <nl> + if ( yych < = ' , ' ) { <nl> + if ( yych = = ' + ' ) goto basic_json_parser_51 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' - ' ) goto basic_json_parser_51 ; <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_52 ; <nl> + goto basic_json_parser_32 ; <nl> + } <nl> basic_json_parser_45 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' l ' ) <nl> - { <nl> - goto basic_json_parser_54 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' l ' ) goto basic_json_parser_54 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_46 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' l ' ) <nl> - { <nl> - goto basic_json_parser_55 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' l ' ) goto basic_json_parser_55 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_47 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' u ' ) <nl> - { <nl> - goto basic_json_parser_56 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' u ' ) goto basic_json_parser_56 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_48 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' @ ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_57 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' F ' ) <nl> - { <nl> - goto basic_json_parser_57 ; <nl> - } <nl> - if ( yych < = ' ` ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_57 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' @ ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_57 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' F ' ) goto basic_json_parser_57 ; <nl> + if ( yych < = ' ` ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' f ' ) goto basic_json_parser_57 ; <nl> + goto basic_json_parser_32 ; <nl> + } <nl> basic_json_parser_49 : <nl> - yyaccept = 1 ; <nl> - m_marker = + + m_cursor ; <nl> - if ( ( m_limit - m_cursor ) < 3 ) <nl> - { <nl> - fill_line_buffer ( 3 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' D ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_14 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_49 ; <nl> - } <nl> - goto basic_json_parser_14 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' E ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - if ( yych = = ' e ' ) <nl> - { <nl> - goto basic_json_parser_44 ; <nl> - } <nl> - goto basic_json_parser_14 ; <nl> - } <nl> + yyaccept = 1 ; <nl> + m_marker = + + m_cursor ; <nl> + if ( ( m_limit - m_cursor ) < 3 ) fill_line_buffer ( 3 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' D ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_14 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_49 ; <nl> + goto basic_json_parser_14 ; <nl> + } else { <nl> + if ( yych < = ' E ' ) goto basic_json_parser_44 ; <nl> + if ( yych = = ' e ' ) goto basic_json_parser_44 ; <nl> + goto basic_json_parser_14 ; <nl> + } <nl> basic_json_parser_51 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych > = ' : ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> + yych = * + + m_cursor ; <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych > = ' : ' ) goto basic_json_parser_32 ; <nl> basic_json_parser_52 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_14 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_52 ; <nl> - } <nl> - goto basic_json_parser_14 ; <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' / ' ) goto basic_json_parser_14 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_52 ; <nl> + goto basic_json_parser_14 ; <nl> basic_json_parser_54 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' s ' ) <nl> - { <nl> - goto basic_json_parser_58 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' s ' ) goto basic_json_parser_58 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_55 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' l ' ) <nl> - { <nl> - goto basic_json_parser_59 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' l ' ) goto basic_json_parser_59 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_56 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' e ' ) <nl> - { <nl> - goto basic_json_parser_61 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' e ' ) goto basic_json_parser_61 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_57 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' @ ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_63 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' F ' ) <nl> - { <nl> - goto basic_json_parser_63 ; <nl> - } <nl> - if ( yych < = ' ` ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_63 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' @ ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_63 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' F ' ) goto basic_json_parser_63 ; <nl> + if ( yych < = ' ` ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' f ' ) goto basic_json_parser_63 ; <nl> + goto basic_json_parser_32 ; <nl> + } <nl> basic_json_parser_58 : <nl> - yych = * + + m_cursor ; <nl> - if ( yych = = ' e ' ) <nl> - { <nl> - goto basic_json_parser_64 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> + yych = * + + m_cursor ; <nl> + if ( yych = = ' e ' ) goto basic_json_parser_64 ; <nl> + goto basic_json_parser_32 ; <nl> basic_json_parser_59 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : literal_null ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : literal_null ; break ; } <nl> basic_json_parser_61 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : literal_true ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : literal_true ; break ; } <nl> basic_json_parser_63 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' @ ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_66 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' F ' ) <nl> - { <nl> - goto basic_json_parser_66 ; <nl> - } <nl> - if ( yych < = ' ` ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_66 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' @ ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_66 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' F ' ) goto basic_json_parser_66 ; <nl> + if ( yych < = ' ` ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' f ' ) goto basic_json_parser_66 ; <nl> + goto basic_json_parser_32 ; <nl> + } <nl> basic_json_parser_64 : <nl> - + + m_cursor ; <nl> - { <nl> - last_token_type = token_type : : literal_false ; <nl> - break ; <nl> - } <nl> + + + m_cursor ; <nl> + { last_token_type = token_type : : literal_false ; break ; } <nl> basic_json_parser_66 : <nl> - + + m_cursor ; <nl> - if ( m_limit < = m_cursor ) <nl> - { <nl> - fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> - } <nl> - yych = * m_cursor ; <nl> - if ( yych < = ' @ ' ) <nl> - { <nl> - if ( yych < = ' / ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' 9 ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - else <nl> - { <nl> - if ( yych < = ' F ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - if ( yych < = ' ` ' ) <nl> - { <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - if ( yych < = ' f ' ) <nl> - { <nl> - goto basic_json_parser_30 ; <nl> - } <nl> - goto basic_json_parser_32 ; <nl> - } <nl> - } <nl> + + + m_cursor ; <nl> + if ( m_limit < = m_cursor ) fill_line_buffer ( 1 ) ; / / LCOV_EXCL_LINE <nl> + yych = * m_cursor ; <nl> + if ( yych < = ' @ ' ) { <nl> + if ( yych < = ' / ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' 9 ' ) goto basic_json_parser_30 ; <nl> + goto basic_json_parser_32 ; <nl> + } else { <nl> + if ( yych < = ' F ' ) goto basic_json_parser_30 ; <nl> + if ( yych < = ' ` ' ) goto basic_json_parser_32 ; <nl> + if ( yych < = ' f ' ) goto basic_json_parser_30 ; <nl> + goto basic_json_parser_32 ; <nl> + } <nl> + } <nl> <nl> } <nl> <nl> mmm a / src / json . hpp . re2c <nl> ppp b / src / json . hpp . re2c <nl> class basic_json <nl> return false ; <nl> } <nl> <nl> - / * ! <nl> - @ brief comparison : equal <nl> - <nl> - The functions compares the given JSON value against a null pointer . As the <nl> - null pointer can be used to initialize a JSON value to null , a comparison <nl> - of JSON value @ a v with a null pointer should be equivalent to call <nl> - ` v . is_null ( ) ` . <nl> - <nl> - @ param [ in ] v JSON value to consider <nl> - @ return whether @ a v is null <nl> - <nl> - @ complexity Constant . <nl> - <nl> - @ liveexample { The example compares several JSON types to the null pointer . <nl> - , operator__equal__nullptr_t } <nl> - <nl> - @ since version 1 . 0 . 0 <nl> + / * ! @ brief comparison : equal <nl> + @ copydoc operator = = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator = = ( const_reference v , std : : nullptr_t ) noexcept <nl> - { <nl> - return v . is_null ( ) ; <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator = = ( const_reference lhs , const ScalarType rhs ) noexcept { <nl> + return ( lhs = = basic_json ( rhs ) ) ; <nl> } <nl> <nl> / * ! <nl> @ brief comparison : equal <nl> - @ copydoc operator = = ( const_reference , std : : nullptr_t ) <nl> + @ copydoc operator = = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator = = ( std : : nullptr_t , const_reference v ) noexcept <nl> - { <nl> - return v . is_null ( ) ; <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator = = ( const ScalarType lhs , const_reference rhs ) noexcept { <nl> + return ( basic_json ( lhs ) = = rhs ) ; <nl> } <nl> <nl> / * ! <nl> class basic_json <nl> <nl> / * ! <nl> @ brief comparison : not equal <nl> - <nl> - The functions compares the given JSON value against a null pointer . As the <nl> - null pointer can be used to initialize a JSON value to null , a comparison <nl> - of JSON value @ a v with a null pointer should be equivalent to call <nl> - ` not v . is_null ( ) ` . <nl> - <nl> - @ param [ in ] v JSON value to consider <nl> - @ return whether @ a v is not null <nl> - <nl> - @ complexity Constant . <nl> - <nl> - @ liveexample { The example compares several JSON types to the null pointer . <nl> - , operator__notequal__nullptr_t } <nl> - <nl> - @ since version 1 . 0 . 0 <nl> + @ copydoc operator ! = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator ! = ( const_reference v , std : : nullptr_t ) noexcept <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator ! = ( const_reference lhs , const ScalarType rhs ) noexcept <nl> { <nl> - return not v . is_null ( ) ; <nl> + return ( lhs ! = basic_json ( rhs ) ) ; <nl> } <nl> <nl> / * ! <nl> @ brief comparison : not equal <nl> - @ copydoc operator ! = ( const_reference , std : : nullptr_t ) <nl> + @ copydoc operator ! = ( const_reference , const_reference ) <nl> * / <nl> - friend bool operator ! = ( std : : nullptr_t , const_reference v ) noexcept <nl> + template < typename ScalarType , typename std : : enable_if < <nl> + std : : is_scalar < ScalarType > : : value , int > : : type = 0 > <nl> + friend bool operator ! = ( const ScalarType lhs , const_reference rhs ) noexcept <nl> { <nl> - return not v . is_null ( ) ; <nl> + return ( basic_json ( lhs ) ! = rhs ) ; <nl> } <nl> <nl> / * ! <nl> mmm a / test / src / unit - regression . cpp <nl> ppp b / test / src / unit - regression . cpp <nl> TEST_CASE ( " regression tests " ) <nl> std : : vector < uint8_t > vec3 { 0xbf , 0x61 , 0x61 , 0x01 } ; <nl> CHECK_THROWS_AS ( json : : from_cbor ( vec3 ) , std : : out_of_range ) ; <nl> } <nl> + <nl> + SECTION ( " issue # 414 - compare with literal 0 ) " ) <nl> + { <nl> + # define CHECK_TYPE ( v ) \ <nl> + CHECK ( ( json ( v ) = = v ) ) ; \ <nl> + CHECK ( ( v = = json ( v ) ) ) ; \ <nl> + CHECK_FALSE ( ( json ( v ) ! = v ) ) ; \ <nl> + CHECK_FALSE ( ( v ! = json ( v ) ) ) ; <nl> + <nl> + CHECK_TYPE ( nullptr ) ; <nl> + CHECK_TYPE ( 0 ) ; <nl> + CHECK_TYPE ( 0u ) ; <nl> + CHECK_TYPE ( 0L ) ; <nl> + CHECK_TYPE ( 0 . 0 ) ; <nl> + CHECK_TYPE ( " " ) ; <nl> + <nl> + # undef CHECK_TYPE <nl> + } <nl> } <nl>
fix - comparing to 0 literal
nlohmann/json
6198439f59be82dd82e102a0c07bfe1c5bb48f5d
2017-01-24T20:33:37Z
mmm a / lib / Sema / CSApply . cpp <nl> ppp b / lib / Sema / CSApply . cpp <nl> namespace { <nl> / / We also need to handle the implicitly unwrap of the result <nl> / / of the called function if that ' s the type checking solution <nl> / / we ended up with . <nl> - return forceUnwrapIfExpected ( ref , member , memberLocator ) ; <nl> + return forceUnwrapIfExpected ( ref , member , memberLocator , <nl> + member - > getAttrs ( ) . hasAttribute < OptionalAttr > ( ) ) ; <nl> } <nl> <nl> / / For types and properties , build member references . <nl> namespace { <nl> return expr ; <nl> } <nl> <nl> - Expr * forceUnwrapResult ( Expr * expr ) { <nl> + / / Add a forced unwrap of an expression which either has type Optional < T > <nl> + / / or is a function that returns an Optional < T > . The latter turns into a <nl> + / / conversion expression that we will hoist above the ApplyExpr <nl> + / / that needs to be forced during the process of rewriting the expression . <nl> + / / <nl> + / / forForcedOptional is used to indicate that we will further need <nl> + / / to hoist this result above an explicit force of an optional that is <nl> + / / in place for something like an @ optional protocol member from <nl> + / / Objective C that we might otherwise mistake for the thing we mean to <nl> + / / force here . <nl> + Expr * forceUnwrapResult ( Expr * expr , bool forForcedOptional = false ) { <nl> auto ty = simplifyType ( cs . getType ( expr ) ) ; <nl> <nl> + if ( forForcedOptional ) <nl> + ty = ty - > getOptionalObjectType ( ) ; <nl> + <nl> if ( auto * fnTy = ty - > getAs < AnyFunctionType > ( ) ) { <nl> auto underlyingType = cs . replaceFinalResultTypeWithUnderlying ( fnTy ) ; <nl> <nl> namespace { <nl> } <nl> <nl> Expr * forceUnwrapIfExpected ( Expr * expr , Decl * decl , <nl> - ConstraintLocatorBuilder locator ) { <nl> + ConstraintLocatorBuilder locator , <nl> + bool forForcedOptional = false ) { <nl> if ( ! shouldForceUnwrapResult ( decl , locator ) ) <nl> return expr ; <nl> <nl> / / Force the expression if required for the solution . <nl> - return forceUnwrapResult ( expr ) ; <nl> + return forceUnwrapResult ( expr , forForcedOptional ) ; <nl> } <nl> <nl> Expr * visitDeclRefExpr ( DeclRefExpr * expr ) { <nl> namespace { <nl> } <nl> <nl> Expr * visitForceValueExpr ( ForceValueExpr * expr ) { <nl> + / / Check to see if we are forcing an <nl> + / / ImplicitlyUnwrappedFunctionConversionExpr . This can happen <nl> + / / in cases where we had a ForceValueExpr of an optional for a <nl> + / / declaration for a function whose result type we need to <nl> + / / implicitly force after applying . We need to hoist the function <nl> + / / conversion above the ForceValueExpr , so that we may ultimately <nl> + / / hoist it above the ApplyExpr where we will eventually rewrite the <nl> + / / function conversion into a force of the result . <nl> + Expr * replacement = expr ; <nl> + if ( auto fnConv = <nl> + dyn_cast < ImplicitlyUnwrappedFunctionConversionExpr > ( expr - > getSubExpr ( ) ) ) { <nl> + auto fnConvSubExpr = fnConv - > getSubExpr ( ) ; <nl> + auto fnConvSubObjTy = <nl> + cs . getType ( fnConvSubExpr ) - > getOptionalObjectType ( ) ; <nl> + cs . setType ( expr , fnConvSubObjTy ) ; <nl> + expr - > setSubExpr ( fnConvSubExpr ) ; <nl> + fnConv - > setSubExpr ( expr ) ; <nl> + replacement = fnConv ; <nl> + } <nl> + <nl> Type valueType = simplifyType ( cs . getType ( expr ) ) ; <nl> cs . setType ( expr , valueType ) ; <nl> - <nl> + <nl> / / Coerce the object type , if necessary . <nl> auto subExpr = expr - > getSubExpr ( ) ; <nl> if ( auto objectTy = cs . getType ( subExpr ) - > getOptionalObjectType ( ) ) { <nl> namespace { <nl> } <nl> } <nl> <nl> - return expr ; <nl> + return replacement ; <nl> } <nl> <nl> Expr * visitOpenExistentialExpr ( OpenExistentialExpr * expr ) { <nl> mmm a / lib / Sema / ConstraintSystem . cpp <nl> ppp b / lib / Sema / ConstraintSystem . cpp <nl> void ConstraintSystem : : resolveOverload ( ConstraintLocator * locator , <nl> Type openedFullType ; <nl> <nl> bool isDynamicResult = choice . getKind ( ) = = OverloadChoiceKind : : DeclViaDynamic ; <nl> - bool createdDynamicResultDisjunction = false ; <nl> + bool bindConstraintCreated = false ; <nl> <nl> switch ( auto kind = choice . getKind ( ) ) { <nl> case OverloadChoiceKind : : Decl : <nl> void ConstraintSystem : : resolveOverload ( ConstraintLocator * locator , <nl> / / <nl> / / Subscript declarations are handled within <nl> / / getTypeOfMemberReference ( ) ; their result types are optional . <nl> + <nl> + / / Deal with values declared as implicitly unwrapped , or <nl> + / / functions with return types that are implicitly unwrapped . <nl> + if ( choice . isImplicitlyUnwrappedValueOrReturnValue ( ) ) { <nl> + / / Build the disjunction to attempt binding both T ? and T ( or <nl> + / / function returning T ? and function returning T ) . <nl> + Type ty = createTypeVariable ( locator , TVO_CanBindToInOut ) ; <nl> + buildDisjunctionForImplicitlyUnwrappedOptional ( ty , refType , <nl> + locator ) ; <nl> + addConstraint ( ConstraintKind : : Bind , boundType , <nl> + OptionalType : : get ( ty - > getRValueType ( ) ) , locator ) ; <nl> + bindConstraintCreated = true ; <nl> + } <nl> refType = OptionalType : : get ( refType - > getRValueType ( ) ) ; <nl> } <nl> / / For a non - subscript declaration found via dynamic lookup , strip <nl> void ConstraintSystem : : resolveOverload ( ConstraintLocator * locator , <nl> refType = OptionalType : : get ( refType - > getRValueType ( ) ) ; <nl> } <nl> <nl> - createdDynamicResultDisjunction = true ; <nl> + bindConstraintCreated = true ; <nl> } <nl> <nl> / / If the declaration is unavailable , note that in the score . <nl> void ConstraintSystem : : resolveOverload ( ConstraintLocator * locator , <nl> openedFullType , <nl> refType } ; <nl> <nl> - / / We created appropriate disjunctions for dynamic result above . <nl> - if ( ! createdDynamicResultDisjunction ) { <nl> + / / In some cases we already created the appropriate bind constraints . <nl> + if ( ! bindConstraintCreated ) { <nl> if ( choice . isImplicitlyUnwrappedValueOrReturnValue ( ) ) { <nl> / / Build the disjunction to attempt binding both T ? and T ( or <nl> / / function returning T ? and function returning T ) . <nl> new file mode 100644 <nl> index 000000000000 . . f7241a39ca1b <nl> mmm / dev / null <nl> ppp b / test / Constraints / iuo_objc . swift <nl> <nl> + / / RUN : % target - swift - frontend ( mock - sdk : % clang - importer - sdk ) - typecheck - verify % s <nl> + / / REQUIRES : objc_interop <nl> + <nl> + import Foundation <nl> + <nl> + func iuo_error ( prop : IUOProperty ) { <nl> + let _ : Coat ? = prop . iuo . optional ( ) <nl> + / / expected - error @ - 1 { { value of optional type ' ( ( ) - > Coat ? ) ? ' not unwrapped ; did you mean to use ' ! ' or ' ? ' ? } } <nl> + let _ : Coat ? = prop . iuo . optional ( ) ! <nl> + / / expected - error @ - 1 { { cannot invoke ' optional ' with no arguments } } <nl> + let _ : Coat ? = prop . iuo . optional ! ( ) <nl> + let _ : Coat ? = prop . iuo . optional ! ( ) ! <nl> + let _ : Coat ? = prop . iuo ! . optional ( ) <nl> + / / expected - error @ - 1 { { value of optional type ' ( ( ) - > Coat ? ) ? ' not unwrapped ; did you mean to use ' ! ' or ' ? ' ? } } <nl> + let _ : Coat ? = prop . iuo ! . optional ( ) ! <nl> + / / expected - error @ - 1 { { cannot invoke ' optional ' with no arguments } } <nl> + let _ : Coat ? = prop . iuo ! . optional ! ( ) <nl> + let _ : Coat ? = prop . iuo ! . optional ! ( ) ! <nl> + let _ : Coat = prop . iuo . optional ( ) <nl> + / / expected - error @ - 1 { { value of optional type ' ( ( ) - > Coat ) ? ' not unwrapped ; did you mean to use ' ! ' or ' ? ' ? } } <nl> + let _ : Coat = prop . iuo . optional ( ) ! <nl> + / / expected - error @ - 1 { { cannot invoke ' optional ' with no arguments } } <nl> + let _ : Coat = prop . iuo . optional ! ( ) <nl> + let _ : Coat = prop . iuo . optional ! ( ) ! <nl> + let _ : Coat = prop . iuo ! . optional ( ) <nl> + / / expected - error @ - 1 { { value of optional type ' ( ( ) - > Coat ) ? ' not unwrapped ; did you mean to use ' ! ' or ' ? ' ? } } <nl> + let _ : Coat = prop . iuo ! . optional ( ) ! <nl> + / / expected - error @ - 1 { { cannot invoke ' optional ' with no arguments } } <nl> + let _ : Coat = prop . iuo ! . optional ! ( ) <nl> + let _ : Coat = prop . iuo ! . optional ! ( ) ! <nl> + } <nl> mmm a / test / Inputs / clang - importer - sdk / usr / include / Foundation . h <nl> ppp b / test / Inputs / clang - importer - sdk / usr / include / Foundation . h <nl> typedef struct NonNilableReferences { <nl> @ protocol NSProtocolWithOptionalRequirement <nl> @ optional <nl> - ( void ) optionalRequirement ; <nl> + - ( DummyClass * ) optionalRequirementMethodWithIUOResult ; <nl> @ end <nl> <nl> @ interface NSClassWithMethodFromNSProtocolWithOptionalRequirement <nl> void install_global_event_handler ( _Nullable event_handler handler ) ; <nl> <nl> __nullable id returnNullableId ( void ) ; <nl> void takeNullableId ( __nullable id ) ; <nl> + <nl> + @ interface I <nl> + @ end <nl> + <nl> + @ protocol OptionalMethods <nl> + @ optional <nl> + - ( Coat * ) optional ; <nl> + @ end <nl> + <nl> + @ interface IUOProperty <nl> + @ property ( readonly ) id < OptionalMethods > iuo ; <nl> + @ end <nl> mmm a / utils / gyb_syntax_support / DeclNodes . py <nl> ppp b / utils / gyb_syntax_support / DeclNodes . py <nl> <nl> # typealias - name generic - parameter - clause ? <nl> # type - assignment <nl> # typealias - name - > identifier <nl> - Node ( ' TypealiasDecl ' , kind = ' Decl ' , <nl> + Node ( ' TypealiasDecl ' , kind = ' Decl ' , traits = [ ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> <nl> # inheritance - clause ? type - assignment ? <nl> # generic - where - clause ? <nl> # associatedtype - name - > identifier <nl> - Node ( ' AssociatedtypeDecl ' , kind = ' Decl ' , <nl> + Node ( ' AssociatedtypeDecl ' , kind = ' Decl ' , traits = [ ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> <nl> # generic - where - clause ? <nl> # ' { ' class - members ' } ' <nl> # class - name - > identifier <nl> - Node ( ' ClassDecl ' , kind = ' Decl ' , traits = [ ' DeclGroupSyntax ' ] , <nl> + Node ( ' ClassDecl ' , kind = ' Decl ' , <nl> + traits = [ ' DeclGroupSyntax ' , ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> <nl> # generic - where - clause ? <nl> # ' { ' struct - members ' } ' <nl> # struct - name - > identifier <nl> - Node ( ' StructDecl ' , kind = ' Decl ' , traits = [ ' DeclGroupSyntax ' ] , <nl> + Node ( ' StructDecl ' , kind = ' Decl ' , <nl> + traits = [ ' DeclGroupSyntax ' , ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> <nl> Child ( ' Members ' , kind = ' MemberDeclBlock ' ) , <nl> ] ) , <nl> <nl> - Node ( ' ProtocolDecl ' , kind = ' Decl ' , traits = [ ' DeclGroupSyntax ' ] , <nl> + Node ( ' ProtocolDecl ' , kind = ' Decl ' , <nl> + traits = [ ' DeclGroupSyntax ' , ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> <nl> element = ' Syntax ' , <nl> element_name = ' Modifier ' ) , <nl> <nl> - Node ( ' FunctionDecl ' , kind = ' Decl ' , <nl> + Node ( ' FunctionDecl ' , kind = ' Decl ' , traits = [ ' IdentifiedDeclSyntax ' ] , <nl> children = [ <nl> Child ( ' Attributes ' , kind = ' AttributeList ' , <nl> is_optional = True ) , <nl> mmm a / utils / gyb_syntax_support / Traits . py <nl> ppp b / utils / gyb_syntax_support / Traits . py <nl> def __init__ ( self , trait_name , children ) : <nl> Child ( ' LeftBrace ' , kind = ' LeftBraceToken ' ) , <nl> Child ( ' RightBrace ' , kind = ' RightBraceToken ' ) , <nl> ] ) , <nl> + <nl> + Trait ( ' IdentifiedDeclSyntax ' , <nl> + children = [ <nl> + Child ( ' Identifier ' , kind = ' IdentifierToken ' ) , <nl> + ] ) , <nl> ] <nl>
Merge remote - tracking branch ' origin / master ' into master - next
apple/swift
58e64e84012312ba325ecdaf655c55e2b0db0430
2018-02-17T02:49:52Z
mmm a / addons / skin . confluence / 720p / Home . xml <nl> ppp b / addons / skin . confluence / 720p / Home . xml <nl> <nl> < onclick > RunAddon ( $ INFO [ Skin . String ( HomeVideosButton1 ) ] ) < / onclick > <nl> < icon > $ INFO [ system . addonicon ( Skin . String ( HomeVideosButton1 ) ) ] < / icon > <nl> < thumb > - < / thumb > <nl> - < visible > Container ( 9000 ) . HasFocus ( 2 ) + ! IsEmpty ( Skin . String ( HomeVideosButton1 ) ) < / visible > <nl> + < visible > [ Container ( 9000 ) . HasFocus ( 2 ) | Container ( 9000 ) . HasFocus ( 10 ) | Container ( 9000 ) . HasFocus ( 11 ) ] + ! IsEmpty ( Skin . String ( HomeVideosButton1 ) ) < / visible > <nl> < / item > <nl> < item > <nl> < label > $ INFO [ system . addontitle ( Skin . String ( HomeVideosButton2 ) ) ] < / label > <nl> < onclick > RunAddon ( $ INFO [ Skin . String ( HomeVideosButton2 ) ] ) < / onclick > <nl> < icon > $ INFO [ system . addonicon ( Skin . String ( HomeVideosButton2 ) ) ] < / icon > <nl> < thumb > - < / thumb > <nl> - < visible > Container ( 9000 ) . HasFocus ( 2 ) + ! IsEmpty ( Skin . String ( HomeVideosButton2 ) ) < / visible > <nl> + < visible > [ Container ( 9000 ) . HasFocus ( 2 ) | Container ( 9000 ) . HasFocus ( 10 ) | Container ( 9000 ) . HasFocus ( 11 ) ] + ! IsEmpty ( Skin . String ( HomeVideosButton2 ) ) < / visible > <nl> < / item > <nl> < item > <nl> < label > $ INFO [ system . addontitle ( Skin . String ( HomeVideosButton3 ) ) ] < / label > <nl> < onclick > RunAddon ( $ INFO [ Skin . String ( HomeVideosButton3 ) ] ) < / onclick > <nl> < icon > $ INFO [ system . addonicon ( Skin . String ( HomeVideosButton3 ) ) ] < / icon > <nl> < thumb > - < / thumb > <nl> - < visible > Container ( 9000 ) . HasFocus ( 2 ) + ! IsEmpty ( Skin . String ( HomeVideosButton3 ) ) < / visible > <nl> + < visible > [ Container ( 9000 ) . HasFocus ( 2 ) | Container ( 9000 ) . HasFocus ( 10 ) | Container ( 9000 ) . HasFocus ( 11 ) ] + ! IsEmpty ( Skin . String ( HomeVideosButton3 ) ) < / visible > <nl> < / item > <nl> < item > <nl> < label > $ INFO [ system . addontitle ( Skin . String ( HomeVideosButton4 ) ) ] < / label > <nl> < onclick > RunAddon ( $ INFO [ Skin . String ( HomeVideosButton4 ) ] ) < / onclick > <nl> < icon > $ INFO [ system . addonicon ( Skin . String ( HomeVideosButton4 ) ) ] < / icon > <nl> < thumb > - < / thumb > <nl> - < visible > Container ( 9000 ) . HasFocus ( 2 ) + ! IsEmpty ( Skin . String ( HomeVideosButton4 ) ) < / visible > <nl> + < visible > [ Container ( 9000 ) . HasFocus ( 2 ) | Container ( 9000 ) . HasFocus ( 10 ) | Container ( 9000 ) . HasFocus ( 11 ) ] + ! IsEmpty ( Skin . String ( HomeVideosButton4 ) ) < / visible > <nl> < / item > <nl> < item > <nl> < label > $ INFO [ system . addontitle ( Skin . String ( HomeVideosButton5 ) ) ] < / label > <nl> < onclick > RunAddon ( $ INFO [ Skin . String ( HomeVideosButton5 ) ] ) < / onclick > <nl> < icon > $ INFO [ system . addonicon ( Skin . String ( HomeVideosButton5 ) ) ] < / icon > <nl> < thumb > - < / thumb > <nl> - < visible > Container ( 9000 ) . HasFocus ( 2 ) + ! IsEmpty ( Skin . String ( HomeVideosButton5 ) ) < / visible > <nl> + < visible > [ Container ( 9000 ) . HasFocus ( 2 ) | Container ( 9000 ) . HasFocus ( 10 ) | Container ( 9000 ) . HasFocus ( 11 ) ] + ! IsEmpty ( Skin . String ( HomeVideosButton5 ) ) < / visible > <nl> < / item > <nl> <nl> < item > <nl>
Changed : [ Confluence ] Make sure the Video Add - on short cuts on home are also visible with the Main menu " TV Shows " and " Movies " buttons
xbmc/xbmc
34f799e369ce32ec906ec4a5916b3325b826a17e
2011-10-10T06:46:03Z
mmm a / tensorflow / contrib / android / jni / tensorflow_inference_jni . cc <nl> ppp b / tensorflow / contrib / android / jni / tensorflow_inference_jni . cc <nl> JNIEXPORT jint JNICALL TENSORFLOW_METHOD ( runInference ) ( <nl> } <nl> <nl> JNIEXPORT jint JNICALL TENSORFLOW_METHOD ( close ) ( JNIEnv * env , jobject thiz ) { <nl> - mutex_lock l ( mutex_ ) ; <nl> SessionVariables * vars = GetSessionVars ( env , thiz ) ; <nl> <nl> tensorflow : : Status s = vars - > session - > Close ( ) ; <nl> JNIEXPORT jint JNICALL TENSORFLOW_METHOD ( close ) ( JNIEnv * env , jobject thiz ) { <nl> LOG ( ERROR ) < < " Error closing session : " < < s ; <nl> } <nl> <nl> + mutex_lock l ( mutex_ ) ; <nl> std : : map < int64 , SessionVariables * > & sessions = * GetSessionsSingleton ( ) ; <nl> sessions . erase ( vars - > id ) ; <nl> delete vars ; <nl>
Move mutex when closing Android TF session to prevent deadlock .
tensorflow/tensorflow
b3eb232e533c77ce537eab29e7f7732f1139ce9d
2016-09-28T20:47:47Z
mmm a / MachineLearning / cn / ComputationNetwork . h <nl> ppp b / MachineLearning / cn / ComputationNetwork . h <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> { <nl> for ( ComputationNodePtr node : FinalCriterionNodes ( ) ) <nl> { <nl> - PrintComputationTree ( node , false ) ; <nl> if ( ! allowFragment ) FormRecurentLoops ( node ) ; <nl> + PrintComputationTree ( node , false ) ; <nl> size_t actualMBSize = this - > GetActualMBSize ( ) ; <nl> this - > SetActualMiniBatchSize ( actualMBSize ) ; <nl> ValidateNetwork ( node ) ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> / / now output nodes <nl> if ( OutputNodes ( ) . size ( ) > 0 ) <nl> { <nl> - for ( ComputationNodePtr node : OutputNodes ( ) ) <nl> - ValidateNetwork ( node ) ; <nl> + for ( ComputationNodePtr node : OutputNodes ( ) ) <nl> + { <nl> + if ( ! allowFragment ) FormRecurentLoops ( node ) ; <nl> + ValidateNetwork ( node ) ; <nl> + } <nl> } <nl> else if ( ! allowFragment ) <nl> { <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> / / now evaluation nodes <nl> if ( EvaluationNodes ( ) . size ( ) > 0 ) <nl> { <nl> - for ( ComputationNodePtr node : EvaluationNodes ( ) ) <nl> - ValidateNetwork ( node ) ; <nl> + for ( ComputationNodePtr node : EvaluationNodes ( ) ) <nl> + { <nl> + if ( ! allowFragment ) FormRecurentLoops ( node ) ; <nl> + ValidateNetwork ( node ) ; <nl> + } <nl> } <nl> } <nl> <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> std : : vector < ComputationNodePtr > sourceLoopNodes ; <nl> getStrongSCC ( rootNode ) ; <nl> std : : list < ComputationNodePtr > & nodes = GetEvalOrder ( rootNode , sourceLoopNodes ) ; <nl> + std : : list < ComputationNodePtr > nodesForGrad ; <nl> <nl> / / / debug purpose <nl> for ( auto iter = m_recurrentInfo . begin ( ) ; iter ! = m_recurrentInfo . end ( ) ; iter + + ) <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> for ( auto iter = m_recurrentInfo . begin ( ) ; iter ! = m_recurrentInfo . end ( ) ; iter + + ) <nl> { <nl> / / sort the recurrent nodes in their ascending name , which is the same as visiting nodes in G ^ R <nl> - if ( ( * iter ) . m_recurrentNodes . size ( ) > 1 & & ( * iter ) . m_recurrentNodesForForward . size ( ) = = 0 ) <nl> + ( * iter ) . m_recurrentNodesForForward . clear ( ) ; <nl> + if ( ( * iter ) . m_recurrentNodes . size ( ) > 1 ) <nl> { <nl> std : : list < ComputationNodePtr > result ; <nl> std : : unordered_set < ComputationNodePtr > visited ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> result . pop_front ( ) ; <nl> } <nl> <nl> - <nl> + ( * iter ) . m_recurrentNodes = ( * iter ) . m_recurrentNodesForForward ; <nl> } <nl> } <nl> <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> std : : list < ComputationNodePtr > noRecurrentNodes ; <nl> <nl> noRecurrentNodes = rootNode - > ReshuffleNodes ( recurrentNodes ) ; <nl> - <nl> - ReorderLoops ( nodes , recurrentNodes , noRecurrentNodes ) ; <nl> <nl> nodes . sort ( IsSmaller ) ; <nl> <nl> + ReorderLoops ( nodes , recurrentNodes , noRecurrentNodes ) ; <nl> + <nl> m_cacheEvalOrders [ rootNode ] = nodes ; <nl> + nodesForGrad = nodes ; <nl> + nodesForGrad . reverse ( ) ; <nl> + m_cacheGradientCalcOrders [ rootNode ] = nodesForGrad ; <nl> <nl> # ifdef DISPLAY_DEBUG <nl> fprintf ( stderr , " Reordered nodes \ n " ) ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> <nl> std : : list < ComputationNodePtr > vTmp ; <nl> std : : list < ComputationNodePtr > vRecurrentTmp ; <nl> - int prevId = - 1 ; <nl> + / / int prevId = - 1 ; <nl> + vector < bool > accessed ; <nl> + accessed . assign ( m_recurrentInfo . size ( ) , false ) ; <nl> for ( auto nodeIter = nodes . begin ( ) ; nodeIter ! = nodes . end ( ) ; nodeIter + + ) <nl> { <nl> int iId = FindInRecurrentLoop ( * nodeIter ) ; <nl> if ( iId > = 0 ) <nl> { <nl> - if ( prevId ! = iId & & vRecurrentTmp . size ( ) > 0 ) <nl> + <nl> + if ( ! accessed [ iId ] ) <nl> + { <nl> + newList . insert ( newList . end ( ) , m_recurrentInfo [ iId ] . m_recurrentNodes . begin ( ) , m_recurrentInfo [ iId ] . m_recurrentNodes . end ( ) ) ; <nl> + accessed [ iId ] = true ; <nl> + } <nl> + <nl> + / * if ( prevId ! = iId & & vRecurrentTmp . size ( ) > 0 ) <nl> { <nl> newList . insert ( newList . end ( ) , vRecurrentTmp . begin ( ) , vRecurrentTmp . end ( ) ) ; <nl> vRecurrentTmp . clear ( ) ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> <nl> vRecurrentTmp . push_back ( * nodeIter ) ; <nl> <nl> - prevId = iId ; <nl> + prevId = iId ; * / <nl> } <nl> else <nl> { <nl> - vTmp . push_back ( * nodeIter ) ; <nl> + / / vTmp . push_back ( * nodeIter ) ; <nl> + newList . push_back ( * nodeIter ) ; <nl> } <nl> } <nl> <nl>
Fix the error during validation stage . Bug : when the anchor node is not the root in a strong component connection , the post visited order may initialize the forward computation incorrect .
microsoft/CNTK
e773dc62644d58fad5cdbe85f415e5c65d14a056
2015-01-03T06:55:27Z
mmm a / tensorflow / core / common_runtime / simple_graph_execution_state . cc <nl> ppp b / tensorflow / core / common_runtime / simple_graph_execution_state . cc <nl> void SimpleGraphExecutionState : : MergeCostsFromGlobal ( CostModel * costs ) { <nl> Status SimpleGraphExecutionState : : BuildGraph ( <nl> const BuildGraphOptions & options , std : : unique_ptr < SimpleClientGraph > * out ) { <nl> VLOG ( 1 ) < < " BuildGraph " ; <nl> + if ( ! graph_ ) { <nl> + / / It is only valid to call this method directly when the original graph <nl> + / / was created with the option ` place_pruned_graph = = false ` . <nl> + return errors : : Internal ( <nl> + " Attempted to prune a graph that has not been fully initialized . " ) ; <nl> + } <nl> std : : unique_ptr < Graph > ng ( new Graph ( flib_def_ . get ( ) ) ) ; <nl> CopyGraph ( * graph_ , ng . get ( ) ) ; <nl> <nl> mmm a / tensorflow / core / distributed_runtime / master_session . cc <nl> ppp b / tensorflow / core / distributed_runtime / master_session . cc <nl> Status MasterSession : : Create ( GraphDef * graph_def ) { <nl> / / TODO ( b / 29900832 ) : Fix this or remove the option . <nl> LOG ( WARNING ) < < " Distributed session does not support the " <nl> " place_pruned_graph option . " ; <nl> + session_opts_ . config . mutable_graph_options ( ) - > set_place_pruned_graph ( false ) ; <nl> } <nl> <nl> SimpleGraphExecutionStateOptions options ; <nl> mmm a / tensorflow / python / training / server_lib_test . py <nl> ppp b / tensorflow / python / training / server_lib_test . py <nl> def blocking_dequeue ( ) : <nl> sess . close ( ) <nl> blocking_thread . join ( ) <nl> <nl> + def testInteractiveSession ( self ) : <nl> + server = tf . train . Server . create_local_server ( ) <nl> + # Session creation will warn ( in C + + ) that the place_pruned_graph option <nl> + # is not supported , but it should successfully ignore it . <nl> + sess = tf . InteractiveSession ( server . target ) <nl> + c = tf . constant ( 42 . 0 ) <nl> + self . assertEqual ( 42 . 0 , c . eval ( ) ) <nl> + sess . close ( ) <nl> + <nl> def testSetConfiguration ( self ) : <nl> config = tf . ConfigProto ( <nl> gpu_options = tf . GPUOptions ( per_process_gpu_memory_fraction = 0 . 1 ) ) <nl>
Fix MasterSession so that it properly ignores the place_pruned_graph option .
tensorflow/tensorflow
f11da014806f3c2c4429e23e88812d824cb592f6
2016-10-11T16:34:41Z
mmm a / README . md <nl> ppp b / README . md <nl> npm install electron - prebuilt - - save - dev <nl> <nl> # # # Mirrors <nl> <nl> - - [ China ] ( https : / / npm . taobao . org / mirrors / atom - shell ) <nl> + - [ China ] ( https : / / npm . taobao . org / mirrors / electron ) <nl> <nl> # # Documentation <nl> <nl> mmm a / atom . gyp <nl> ppp b / atom . gyp <nl> <nl> ' product_name % ' : ' Electron ' , <nl> ' company_name % ' : ' GitHub , Inc ' , <nl> ' company_abbr % ' : ' github ' , <nl> - ' version % ' : ' 0 . 25 . 2 ' , <nl> + ' version % ' : ' 0 . 26 . 0 ' , <nl> <nl> ' atom_source_root ' : ' < ! ( [ " python " , " tools / atom_source_root . py " ] ) ' , <nl> } , <nl> <nl> ' < ( libchromiumcontent_dir ) / snapshot_blob . bin ' , <nl> ' external_binaries / d3dcompiler_47 . dll ' , <nl> ' external_binaries / xinput1_3 . dll ' , <nl> + ' external_binaries / msvcp120 . dll ' , <nl> + ' external_binaries / msvcr120 . dll ' , <nl> + ' external_binaries / vccorlib120 . dll ' , <nl> ] , <nl> } , <nl> { <nl> mmm a / atom / app / atom_content_client . cc <nl> ppp b / atom / app / atom_content_client . cc <nl> <nl> # include < vector > <nl> <nl> # include " atom / common / chrome_version . h " <nl> + # include " atom / common / options_switches . h " <nl> + # include " base / command_line . h " <nl> + # include " content / public / common / content_constants . h " <nl> + # include " content / public / common / pepper_plugin_info . h " <nl> + # include " ppapi / shared_impl / ppapi_permissions . h " <nl> <nl> namespace atom { <nl> <nl> + namespace { <nl> + <nl> + content : : PepperPluginInfo CreatePepperFlashInfo ( const base : : FilePath & path , <nl> + const std : : string & version ) { <nl> + content : : PepperPluginInfo plugin ; <nl> + <nl> + plugin . is_out_of_process = true ; <nl> + plugin . name = content : : kFlashPluginName ; <nl> + plugin . path = path ; <nl> + plugin . permissions = ppapi : : PERMISSION_ALL_BITS ; <nl> + plugin . version = version ; <nl> + <nl> + content : : WebPluginMimeType swf_mime_type ( <nl> + content : : kFlashPluginSwfMimeType , <nl> + content : : kFlashPluginSwfExtension , <nl> + content : : kFlashPluginSwfDescription ) ; <nl> + plugin . mime_types . push_back ( swf_mime_type ) ; <nl> + content : : WebPluginMimeType spl_mime_type ( <nl> + content : : kFlashPluginSplMimeType , <nl> + content : : kFlashPluginSplExtension , <nl> + content : : kFlashPluginSplDescription ) ; <nl> + plugin . mime_types . push_back ( spl_mime_type ) ; <nl> + <nl> + return plugin ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> AtomContentClient : : AtomContentClient ( ) { <nl> } <nl> <nl> void AtomContentClient : : AddAdditionalSchemes ( <nl> standard_schemes - > push_back ( " chrome - extension " ) ; <nl> } <nl> <nl> + void AtomContentClient : : AddPepperPlugins ( <nl> + std : : vector < content : : PepperPluginInfo > * plugins ) { <nl> + auto command_line = base : : CommandLine : : ForCurrentProcess ( ) ; <nl> + auto flash_path = command_line - > GetSwitchValueNative ( <nl> + switches : : kPpapiFlashPath ) ; <nl> + if ( flash_path . empty ( ) ) <nl> + return ; <nl> + <nl> + auto flash_version = command_line - > GetSwitchValueASCII ( <nl> + switches : : kPpapiFlashVersion ) ; <nl> + <nl> + plugins - > push_back ( <nl> + CreatePepperFlashInfo ( base : : FilePath ( flash_path ) , flash_version ) ) ; <nl> + } <nl> + <nl> } / / namespace atom <nl> mmm a / atom / app / atom_content_client . h <nl> ppp b / atom / app / atom_content_client . h <nl> class AtomContentClient : public brightray : : ContentClient { <nl> void AddAdditionalSchemes ( <nl> std : : vector < std : : string > * standard_schemes , <nl> std : : vector < std : : string > * savable_schemes ) override ; <nl> + void AddPepperPlugins ( <nl> + std : : vector < content : : PepperPluginInfo > * plugins ) override ; <nl> <nl> private : <nl> DISALLOW_COPY_AND_ASSIGN ( AtomContentClient ) ; <nl> mmm a / atom / app / atom_main_delegate . cc <nl> ppp b / atom / app / atom_main_delegate . cc <nl> <nl> # include " atom / browser / atom_browser_client . h " <nl> # include " atom / common / google_api_key . h " <nl> # include " atom / renderer / atom_renderer_client . h " <nl> + # include " atom / utility / atom_content_utility_client . h " <nl> # include " base / command_line . h " <nl> # include " base / debug / stack_trace . h " <nl> # include " base / environment . h " <nl> content : : ContentRendererClient * <nl> return renderer_client_ . get ( ) ; <nl> } <nl> <nl> + content : : ContentUtilityClient * AtomMainDelegate : : CreateContentUtilityClient ( ) { <nl> + utility_client_ . reset ( new AtomContentUtilityClient ) ; <nl> + return utility_client_ . get ( ) ; <nl> + } <nl> + <nl> scoped_ptr < brightray : : ContentClient > AtomMainDelegate : : CreateContentClient ( ) { <nl> return scoped_ptr < brightray : : ContentClient > ( new AtomContentClient ) . Pass ( ) ; <nl> } <nl> mmm a / atom / app / atom_main_delegate . h <nl> ppp b / atom / app / atom_main_delegate . h <nl> class AtomMainDelegate : public brightray : : MainDelegate { <nl> void PreSandboxStartup ( ) override ; <nl> content : : ContentBrowserClient * CreateContentBrowserClient ( ) override ; <nl> content : : ContentRendererClient * CreateContentRendererClient ( ) override ; <nl> + content : : ContentUtilityClient * CreateContentUtilityClient ( ) override ; <nl> <nl> / / brightray : : MainDelegate : <nl> scoped_ptr < brightray : : ContentClient > CreateContentClient ( ) override ; <nl> class AtomMainDelegate : public brightray : : MainDelegate { <nl> brightray : : ContentClient content_client_ ; <nl> scoped_ptr < content : : ContentBrowserClient > browser_client_ ; <nl> scoped_ptr < content : : ContentRendererClient > renderer_client_ ; <nl> + scoped_ptr < content : : ContentUtilityClient > utility_client_ ; <nl> <nl> DISALLOW_COPY_AND_ASSIGN ( AtomMainDelegate ) ; <nl> } ; <nl> mmm a / atom / browser / api / atom_api_protocol . cc <nl> ppp b / atom / browser / api / atom_api_protocol . cc <nl> class CustomProtocolRequestJob : public AdapterRequestJob { <nl> base : : Bind ( & AdapterRequestJob : : CreateFileJobAndStart , <nl> GetWeakPtr ( ) , path ) ) ; <nl> return ; <nl> + } else if ( name = = " RequestErrorJob " ) { <nl> + / / Default value net : : ERR_NOT_IMPLEMENTED <nl> + int error = - 11 ; <nl> + dict . Get ( " error " , & error ) ; <nl> + <nl> + BrowserThread : : PostTask ( BrowserThread : : IO , FROM_HERE , <nl> + base : : Bind ( & AdapterRequestJob : : CreateErrorJobAndStart , <nl> + GetWeakPtr ( ) , error ) ) ; <nl> + return ; <nl> } <nl> } <nl> <nl> mmm a / atom / browser / api / atom_api_web_contents . cc <nl> ppp b / atom / browser / api / atom_api_web_contents . cc <nl> <nl> <nl> # include < set > <nl> <nl> + # include " atom / browser / atom_browser_client . h " <nl> # include " atom / browser / atom_browser_context . h " <nl> # include " atom / browser / atom_javascript_dialog_manager . h " <nl> # include " atom / browser / native_window . h " <nl> void WebContents : : WebContentsDestroyed ( ) { <nl> } <nl> <nl> void WebContents : : NavigationEntryCommitted ( <nl> - const content : : LoadCommittedDetails & load_details ) { <nl> - Emit ( " navigation - entry - commited " , load_details . entry - > GetURL ( ) ) ; <nl> + const content : : LoadCommittedDetails & details ) { <nl> + Emit ( " navigation - entry - commited " , details . entry - > GetURL ( ) , <nl> + details . is_in_page , details . did_replace_entry ) ; <nl> } <nl> <nl> void WebContents : : DidAttach ( int guest_proxy_routing_id ) { <nl> base : : string16 WebContents : : GetTitle ( ) const { <nl> return web_contents ( ) - > GetTitle ( ) ; <nl> } <nl> <nl> - gfx : : Image WebContents : : GetFavicon ( ) const { <nl> - auto entry = web_contents ( ) - > GetController ( ) . GetLastCommittedEntry ( ) ; <nl> - if ( ! entry ) <nl> - return gfx : : Image ( ) ; <nl> - return entry - > GetFavicon ( ) . image ; <nl> - } <nl> - <nl> bool WebContents : : IsLoading ( ) const { <nl> return web_contents ( ) - > IsLoading ( ) ; <nl> } <nl> void WebContents : : ReloadIgnoringCache ( ) { <nl> web_contents ( ) - > GetController ( ) . ReloadIgnoringCache ( false ) ; <nl> } <nl> <nl> + void WebContents : : GoBack ( ) { <nl> + atom : : AtomBrowserClient : : SuppressRendererProcessRestartForOnce ( ) ; <nl> + web_contents ( ) - > GetController ( ) . GoBack ( ) ; <nl> + } <nl> + <nl> + void WebContents : : GoForward ( ) { <nl> + atom : : AtomBrowserClient : : SuppressRendererProcessRestartForOnce ( ) ; <nl> + web_contents ( ) - > GetController ( ) . GoForward ( ) ; <nl> + } <nl> + <nl> + void WebContents : : GoToOffset ( int offset ) { <nl> + atom : : AtomBrowserClient : : SuppressRendererProcessRestartForOnce ( ) ; <nl> + web_contents ( ) - > GetController ( ) . GoToOffset ( offset ) ; <nl> + } <nl> + <nl> int WebContents : : GetRoutingID ( ) const { <nl> return web_contents ( ) - > GetRoutingID ( ) ; <nl> } <nl> mate : : ObjectTemplateBuilder WebContents : : GetObjectTemplateBuilder ( <nl> . SetMethod ( " isAlive " , & WebContents : : IsAlive ) <nl> . SetMethod ( " _loadUrl " , & WebContents : : LoadURL ) <nl> . SetMethod ( " getTitle " , & WebContents : : GetTitle ) <nl> - . SetMethod ( " getFavicon " , & WebContents : : GetFavicon ) <nl> . SetMethod ( " isLoading " , & WebContents : : IsLoading ) <nl> . SetMethod ( " isWaitingForResponse " , & WebContents : : IsWaitingForResponse ) <nl> . SetMethod ( " _stop " , & WebContents : : Stop ) <nl> . SetMethod ( " _reloadIgnoringCache " , & WebContents : : ReloadIgnoringCache ) <nl> + . SetMethod ( " _goBack " , & WebContents : : GoBack ) <nl> + . SetMethod ( " _goForward " , & WebContents : : GoForward ) <nl> + . SetMethod ( " _goToOffset " , & WebContents : : GoToOffset ) <nl> . SetMethod ( " getRoutingId " , & WebContents : : GetRoutingID ) <nl> . SetMethod ( " getProcessId " , & WebContents : : GetProcessID ) <nl> . SetMethod ( " isCrashed " , & WebContents : : IsCrashed ) <nl> mmm a / atom / browser / api / atom_api_web_contents . h <nl> ppp b / atom / browser / api / atom_api_web_contents . h <nl> class WebContents : public mate : : EventEmitter , <nl> bool IsAlive ( ) const ; <nl> void LoadURL ( const GURL & url , const mate : : Dictionary & options ) ; <nl> base : : string16 GetTitle ( ) const ; <nl> - gfx : : Image GetFavicon ( ) const ; <nl> bool IsLoading ( ) const ; <nl> bool IsWaitingForResponse ( ) const ; <nl> void Stop ( ) ; <nl> void ReloadIgnoringCache ( ) ; <nl> + void GoBack ( ) ; <nl> + void GoForward ( ) ; <nl> + void GoToOffset ( int offset ) ; <nl> int GetRoutingID ( ) const ; <nl> int GetProcessID ( ) const ; <nl> bool IsCrashed ( ) const ; <nl> mmm a / atom / browser / api / lib / navigation - controller . coffee <nl> ppp b / atom / browser / api / lib / navigation - controller . coffee <nl> <nl> + ipc = require ' ipc ' <nl> + <nl> + # The history operation in renderer is redirected to browser . <nl> + ipc . on ' ATOM_SHELL_NAVIGATION_CONTROLLER ' , ( event , method , args . . . ) - > <nl> + event . sender [ method ] args . . . <nl> + <nl> # JavaScript implementation of Chromium ' s NavigationController . <nl> # Instead of relying on Chromium for history control , we compeletely do history <nl> # control on user land , and only rely on WebContents . loadUrl for navigation . <nl> class NavigationController <nl> @ history = [ ] <nl> @ currentIndex = - 1 <nl> @ pendingIndex = - 1 <nl> + @ inPageIndex = - 1 <nl> <nl> - @ webContents . on ' navigation - entry - commited ' , ( event , url ) = > <nl> - if @ pendingIndex is - 1 # Normal navigation . <nl> - @ history = @ history . slice 0 , @ currentIndex + 1 # Clear history . <nl> - if @ history [ @ currentIndex ] isnt url <nl> - @ currentIndex + + <nl> - @ history . push url <nl> - else # Go to index . <nl> + @ webContents . on ' navigation - entry - commited ' , ( event , url , inPage , replaceEntry ) = > <nl> + if @ inPageIndex > - 1 and not inPage <nl> + # Navigated to a new page , clear in - page mark . <nl> + @ inPageIndex = - 1 <nl> + else if @ inPageIndex is - 1 and inPage <nl> + # Started in - page navigations . <nl> + @ inPageIndex = @ currentIndex <nl> + <nl> + if @ pendingIndex > = 0 # Go to index . <nl> @ currentIndex = @ pendingIndex <nl> @ pendingIndex = - 1 <nl> @ history [ @ currentIndex ] = url <nl> + else if replaceEntry # Non - user initialized navigation . <nl> + @ history [ @ currentIndex ] = url <nl> + else # Normal navigation . <nl> + @ history = @ history . slice 0 , @ currentIndex + 1 # Clear history . <nl> + currentEntry = @ history [ @ currentIndex ] <nl> + if currentEntry ? . url isnt url <nl> + @ currentIndex + + <nl> + @ history . push url <nl> <nl> loadUrl : ( url , options = { } ) - > <nl> @ pendingIndex = - 1 <nl> class NavigationController <nl> goBack : - > <nl> return unless @ canGoBack ( ) <nl> @ pendingIndex = @ getActiveIndex ( ) - 1 <nl> - @ webContents . _loadUrl @ history [ @ pendingIndex ] , { } <nl> + if @ inPageIndex > - 1 and @ pendingIndex > = @ inPageIndex <nl> + @ webContents . _goBack ( ) <nl> + else <nl> + @ webContents . _loadUrl @ history [ @ pendingIndex ] , { } <nl> <nl> goForward : - > <nl> return unless @ canGoForward ( ) <nl> @ pendingIndex = @ getActiveIndex ( ) + 1 <nl> - @ webContents . _loadUrl @ history [ @ pendingIndex ] , { } <nl> + if @ inPageIndex > - 1 and @ pendingIndex > = @ inPageIndex <nl> + @ webContents . _goForward ( ) <nl> + else <nl> + @ webContents . _loadUrl @ history [ @ pendingIndex ] , { } <nl> <nl> goToIndex : ( index ) - > <nl> return unless @ canGoToIndex index <nl> @ pendingIndex = index <nl> - @ webContents . _loadUrl @ history [ @ pendingIndex ] , { } <nl> + @ webContents . _loadUrl @ history [ @ pendingIndex ] . url , { } <nl> <nl> goToOffset : ( offset ) - > <nl> return unless @ canGoToOffset offset <nl> - @ goToIndex @ currentIndex + offset <nl> + pendingIndex = @ currentIndex + offset <nl> + if @ inPageIndex > - 1 and pendingIndex > = @ inPageIndex <nl> + @ pendingIndex = pendingIndex <nl> + @ webContents . _goToOffset offset <nl> + else <nl> + @ goToIndex pendingIndex <nl> <nl> getActiveIndex : - > <nl> if @ pendingIndex is - 1 then @ currentIndex else @ pendingIndex <nl> mmm a / atom / browser / api / lib / protocol . coffee <nl> ppp b / atom / browser / api / lib / protocol . coffee <nl> protocol . RequestFileJob = <nl> class RequestFileJob <nl> constructor : ( @ path ) - > <nl> <nl> + protocol . RequestErrorJob = <nl> + class RequestErrorJob <nl> + constructor : ( @ error ) - > <nl> + <nl> module . exports = protocol <nl> mmm a / atom / browser / api / lib / web - contents . coffee <nl> ppp b / atom / browser / api / lib / web - contents . coffee <nl> module . exports . wrap = ( webContents ) - > <nl> <nl> # The navigation controller . <nl> controller = new NavigationController ( webContents ) <nl> - webContents . controller = controller <nl> for name , method of NavigationController . prototype when method instanceof Function <nl> do ( name , method ) - > <nl> webContents [ name ] = - > method . apply controller , arguments <nl> mmm a / atom / browser / atom_browser_client . cc <nl> ppp b / atom / browser / atom_browser_client . cc <nl> <nl> # include " base / command_line . h " <nl> # include " base / strings / string_number_conversions . h " <nl> # include " chrome / browser / printing / printing_message_filter . h " <nl> + # include " chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . h " <nl> # include " chrome / browser / speech / tts_message_filter . h " <nl> + # include " content / public / browser / browser_ppapi_host . h " <nl> # include " content / public / browser / render_process_host . h " <nl> # include " content / public / browser / render_view_host . h " <nl> # include " content / public / browser / resource_dispatcher_host . h " <nl> # include " content / public / browser / site_instance . h " <nl> # include " content / public / browser / web_contents . h " <nl> # include " content / public / common / web_preferences . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> # include " ui / base / l10n / l10n_util . h " <nl> <nl> namespace atom { <nl> <nl> namespace { <nl> <nl> + / / Next navigation should not restart renderer process . <nl> + bool g_suppress_renderer_process_restart = false ; <nl> + <nl> struct FindByProcessId { <nl> explicit FindByProcessId ( int child_process_id ) <nl> : child_process_id_ ( child_process_id ) { <nl> struct FindByProcessId { <nl> <nl> } / / namespace <nl> <nl> + / / static <nl> + void AtomBrowserClient : : SuppressRendererProcessRestartForOnce ( ) { <nl> + g_suppress_renderer_process_restart = true ; <nl> + } <nl> + <nl> AtomBrowserClient : : AtomBrowserClient ( ) <nl> : dying_render_process_ ( nullptr ) { <nl> } <nl> void AtomBrowserClient : : OverrideSiteInstanceForNavigation ( <nl> content : : SiteInstance * current_instance , <nl> const GURL & url , <nl> content : : SiteInstance * * new_instance ) { <nl> + if ( g_suppress_renderer_process_restart ) { <nl> + g_suppress_renderer_process_restart = false ; <nl> + return ; <nl> + } <nl> + <nl> if ( current_instance - > HasProcess ( ) ) <nl> dying_render_process_ = current_instance - > GetProcess ( ) ; <nl> <nl> void AtomBrowserClient : : AppendExtraCommandLineSwitches ( <nl> dying_render_process_ = nullptr ; <nl> } <nl> <nl> + void AtomBrowserClient : : DidCreatePpapiPlugin ( <nl> + content : : BrowserPpapiHost * browser_host ) { <nl> + auto command_line = base : : CommandLine : : ForCurrentProcess ( ) ; <nl> + if ( command_line - > HasSwitch ( switches : : kEnablePlugins ) ) <nl> + browser_host - > GetPpapiHost ( ) - > AddHostFactoryFilter ( <nl> + scoped_ptr < ppapi : : host : : HostFactory > ( <nl> + new chrome : : ChromeBrowserPepperHostFactory ( browser_host ) ) ) ; <nl> + } <nl> + <nl> brightray : : BrowserMainParts * AtomBrowserClient : : OverrideCreateBrowserMainParts ( <nl> const content : : MainFunctionParams & ) { <nl> v8 : : V8 : : Initialize ( ) ; / / Init V8 before creating main parts . <nl> mmm a / atom / browser / atom_browser_client . h <nl> ppp b / atom / browser / atom_browser_client . h <nl> class AtomBrowserClient : public brightray : : BrowserClient { <nl> AtomBrowserClient ( ) ; <nl> virtual ~ AtomBrowserClient ( ) ; <nl> <nl> + / / Don ' t force renderer process to restart for once . <nl> + static void SuppressRendererProcessRestartForOnce ( ) ; <nl> + <nl> protected : <nl> / / content : : ContentBrowserClient : <nl> void RenderProcessWillLaunch ( content : : RenderProcessHost * host ) override ; <nl> class AtomBrowserClient : public brightray : : BrowserClient { <nl> content : : SiteInstance * * new_instance ) ; <nl> void AppendExtraCommandLineSwitches ( base : : CommandLine * command_line , <nl> int child_process_id ) override ; <nl> + void DidCreatePpapiPlugin ( content : : BrowserPpapiHost * browser_host ) override ; <nl> <nl> private : <nl> brightray : : BrowserMainParts * OverrideCreateBrowserMainParts ( <nl> mmm a / atom / browser / lib / rpc - server . coffee <nl> ppp b / atom / browser / lib / rpc - server . coffee <nl> ipc . on ' ATOM_BROWSER_CURRENT_WINDOW ' , ( event , guestInstanceId ) - > <nl> catch e <nl> event . returnValue = errorToMeta e <nl> <nl> + ipc . on ' ATOM_BROWSER_CURRENT_WEB_CONTENTS ' , ( event ) - > <nl> + event . returnValue = valueToMeta event . sender , event . sender <nl> + <nl> ipc . on ' ATOM_BROWSER_CONSTRUCTOR ' , ( event , id , args ) - > <nl> try <nl> args = unwrapArgs event . sender , args <nl> mmm a / atom / browser / native_window_mac . mm <nl> ppp b / atom / browser / native_window_mac . mm <nl> - ( void ) drawRect : ( NSRect ) dirtyRect { <nl> options . Get ( switches : : kWidth , & width ) ; <nl> options . Get ( switches : : kHeight , & height ) ; <nl> <nl> - NSRect main_screen_rect = [ [ NSScreen mainScreen ] frame ] ; <nl> + NSRect main_screen_rect = [ [ [ NSScreen screens ] objectAtIndex : 0 ] frame ] ; <nl> NSRect cocoa_bounds = NSMakeRect ( <nl> round ( ( NSWidth ( main_screen_rect ) - width ) / 2 ) , <nl> round ( ( NSHeight ( main_screen_rect ) - height ) / 2 ) , <nl> width , <nl> height ) ; <nl> <nl> + bool useStandardWindow = true ; <nl> + options . Get ( switches : : kStandardWindow , & useStandardWindow ) ; <nl> + <nl> + NSUInteger styleMask = NSTitledWindowMask | NSClosableWindowMask | <nl> + NSMiniaturizableWindowMask | NSResizableWindowMask ; <nl> + if ( ! useStandardWindow ) { <nl> + styleMask | = NSTexturedBackgroundWindowMask ; <nl> + } <nl> + <nl> window_ . reset ( [ [ AtomNSWindow alloc ] <nl> initWithContentRect : cocoa_bounds <nl> - styleMask : NSTitledWindowMask | NSClosableWindowMask | <nl> - NSMiniaturizableWindowMask | NSResizableWindowMask | <nl> - NSTexturedBackgroundWindowMask <nl> + styleMask : styleMask <nl> backing : NSBackingStoreBuffered <nl> defer : YES ] ) ; <nl> [ window_ setShell : this ] ; <nl> - ( void ) drawRect : ( NSRect ) dirtyRect { <nl> bounds . width ( ) , <nl> bounds . height ( ) ) ; <nl> / / Flip coordinates based on the primary screen . <nl> - NSScreen * screen = [ NSScreen mainScreen ] ; <nl> + NSScreen * screen = [ [ NSScreen screens ] objectAtIndex : 0 ] ; <nl> cocoa_bounds . origin . y = <nl> NSHeight ( [ screen frame ] ) - bounds . height ( ) - bounds . y ( ) ; <nl> <nl> - ( void ) drawRect : ( NSRect ) dirtyRect { <nl> gfx : : Rect NativeWindowMac : : GetBounds ( ) { <nl> NSRect frame = [ window_ frame ] ; <nl> gfx : : Rect bounds ( frame . origin . x , 0 , NSWidth ( frame ) , NSHeight ( frame ) ) ; <nl> - NSScreen * screen = [ NSScreen mainScreen ] ; <nl> + NSScreen * screen = [ [ NSScreen screens ] objectAtIndex : 0 ] ; <nl> bounds . set_y ( NSHeight ( [ screen frame ] ) - NSMaxY ( frame ) ) ; <nl> return bounds ; <nl> } <nl> mmm a / atom / browser / net / adapter_request_job . cc <nl> ppp b / atom / browser / net / adapter_request_job . cc <nl> <nl> # include " atom / browser / net / adapter_request_job . h " <nl> <nl> # include " base / threading / sequenced_worker_pool . h " <nl> + # include " atom / browser / net / url_request_buffer_job . h " <nl> # include " atom / browser / net / url_request_string_job . h " <nl> # include " atom / browser / net / asar / url_request_asar_job . h " <nl> # include " atom / common / asar / asar_util . h " <nl> - # include " atom / browser / net / url_request_buffer_job . h " <nl> # include " content / public / browser / browser_thread . h " <nl> # include " net / base / net_errors . h " <nl> # include " net / url_request / url_request_error_job . h " <nl> mmm a / atom / browser / resources / mac / Info . plist <nl> ppp b / atom / browser / resources / mac / Info . plist <nl> <nl> < key > CFBundleIconFile < / key > <nl> < string > atom . icns < / string > <nl> < key > CFBundleVersion < / key > <nl> - < string > 0 . 25 . 2 < / string > <nl> + < string > 0 . 26 . 0 < / string > <nl> < key > LSMinimumSystemVersion < / key > <nl> < string > 10 . 8 . 0 < / string > <nl> < key > NSMainNibFile < / key > <nl> mmm a / atom / browser / resources / win / atom . rc <nl> ppp b / atom / browser / resources / win / atom . rc <nl> END <nl> / / <nl> <nl> VS_VERSION_INFO VERSIONINFO <nl> - FILEVERSION 0 , 25 , 2 , 0 <nl> - PRODUCTVERSION 0 , 25 , 2 , 0 <nl> + FILEVERSION 0 , 26 , 0 , 0 <nl> + PRODUCTVERSION 0 , 26 , 0 , 0 <nl> FILEFLAGSMASK 0x3fL <nl> # ifdef _DEBUG <nl> FILEFLAGS 0x1L <nl> BEGIN <nl> BEGIN <nl> VALUE " CompanyName " , " GitHub , Inc . " <nl> VALUE " FileDescription " , " Electron " <nl> - VALUE " FileVersion " , " 0 . 25 . 2 " <nl> + VALUE " FileVersion " , " 0 . 26 . 0 " <nl> VALUE " InternalName " , " electron . exe " <nl> VALUE " LegalCopyright " , " Copyright ( C ) 2015 GitHub , Inc . All rights reserved . " <nl> VALUE " OriginalFilename " , " electron . exe " <nl> VALUE " ProductName " , " Electron " <nl> - VALUE " ProductVersion " , " 0 . 25 . 2 " <nl> + VALUE " ProductVersion " , " 0 . 26 . 0 " <nl> VALUE " SquirrelAwareVersion " , " 1 " <nl> END <nl> END <nl> mmm a / atom / browser / ui / accelerator_util . cc <nl> ppp b / atom / browser / ui / accelerator_util . cc <nl> bool StringToAccelerator ( const std : : string & description , <nl> modifiers | = ui : : EF_SHIFT_DOWN ; <nl> } else if ( tokens [ i ] = = " ctrl " | | tokens [ i ] = = " control " ) { <nl> modifiers | = ui : : EF_CONTROL_DOWN ; <nl> + } else if ( tokens [ i ] = = " super " ) { <nl> + modifiers | = ui : : EF_COMMAND_DOWN ; <nl> + # if defined ( OS_MACOSX ) <nl> } else if ( tokens [ i ] = = " cmd " | | tokens [ i ] = = " command " ) { <nl> modifiers | = ui : : EF_COMMAND_DOWN ; <nl> + # endif <nl> } else if ( tokens [ i ] = = " commandorcontrol " | | tokens [ i ] = = " cmdorctrl " ) { <nl> # if defined ( OS_MACOSX ) <nl> modifiers | = ui : : EF_COMMAND_DOWN ; <nl> bool StringToAccelerator ( const std : : string & description , <nl> } else if ( tokens [ i ] . size ( ) > 1 & & tokens [ i ] [ 0 ] = = ' f ' ) { <nl> / / F1 - F24 . <nl> int n ; <nl> - if ( base : : StringToInt ( tokens [ i ] . c_str ( ) + 1 , & n ) ) { <nl> + if ( base : : StringToInt ( tokens [ i ] . c_str ( ) + 1 , & n ) & & n > 0 & & n < 25 ) { <nl> key = static_cast < ui : : KeyboardCode > ( ui : : VKEY_F1 + n - 1 ) ; <nl> } else { <nl> LOG ( WARNING ) < < tokens [ i ] < < " is not available on keyboard " ; <nl> mmm a / atom / browser / ui / tray_icon_cocoa . mm <nl> ppp b / atom / browser / ui / tray_icon_cocoa . mm <nl> - ( void ) handleClick : ( id ) sender { <nl> NSRect frame = [ NSApp currentEvent ] . window . frame ; <nl> gfx : : Rect bounds ( frame . origin . x , 0 , NSWidth ( frame ) , NSHeight ( frame ) ) ; <nl> / / Flip coordinates to gfx ( 0 , 0 in top - left corner ) using current screen . <nl> - NSScreen * screen = [ NSScreen mainScreen ] ; <nl> + NSScreen * screen = [ [ NSScreen screens ] objectAtIndex : 0 ] ; <nl> bounds . set_y ( NSHeight ( [ screen frame ] ) - NSMaxY ( frame ) ) ; <nl> <nl> trayIcon_ - > NotifyClicked ( bounds ) ; <nl> mmm a / atom / common / api / atom_api_asar . cc <nl> ppp b / atom / common / api / atom_api_asar . cc <nl> class Archive : public mate : : Wrappable { <nl> return mate : : ConvertToV8 ( isolate , new_path ) ; <nl> } <nl> <nl> + / / Return the file descriptor . <nl> + int GetFD ( ) const { <nl> + if ( ! archive_ ) <nl> + return - 1 ; <nl> + return archive_ - > GetFD ( ) ; <nl> + } <nl> + <nl> / / Free the resources used by archive . <nl> void Destroy ( ) { <nl> archive_ . reset ( ) ; <nl> class Archive : public mate : : Wrappable { <nl> . SetMethod ( " readdir " , & Archive : : Readdir ) <nl> . SetMethod ( " realpath " , & Archive : : Realpath ) <nl> . SetMethod ( " copyFileOut " , & Archive : : CopyFileOut ) <nl> + . SetMethod ( " getFd " , & Archive : : GetFD ) <nl> . SetMethod ( " destroy " , & Archive : : Destroy ) ; <nl> } <nl> <nl> mmm a / atom / common / asar / archive . cc <nl> ppp b / atom / common / asar / archive . cc <nl> <nl> <nl> # include " atom / common / asar / archive . h " <nl> <nl> + # if defined ( OS_WIN ) <nl> + # include < io . h > <nl> + # endif <nl> + <nl> # include < string > <nl> # include < vector > <nl> <nl> bool FillFileInfoWithNode ( Archive : : FileInfo * info , <nl> <nl> Archive : : Archive ( const base : : FilePath & path ) <nl> : path_ ( path ) , <nl> + file_ ( path_ , base : : File : : FLAG_OPEN | base : : File : : FLAG_READ ) , <nl> header_size_ ( 0 ) { <nl> } <nl> <nl> Archive : : ~ Archive ( ) { <nl> } <nl> <nl> bool Archive : : Init ( ) { <nl> - base : : File file ( path_ , base : : File : : FLAG_OPEN | base : : File : : FLAG_READ ) ; <nl> - if ( ! file . IsValid ( ) ) <nl> + if ( ! file_ . IsValid ( ) ) <nl> return false ; <nl> <nl> std : : vector < char > buf ; <nl> int len ; <nl> <nl> buf . resize ( 8 ) ; <nl> - len = file . ReadAtCurrentPos ( buf . data ( ) , buf . size ( ) ) ; <nl> + len = file_ . ReadAtCurrentPos ( buf . data ( ) , buf . size ( ) ) ; <nl> if ( len ! = static_cast < int > ( buf . size ( ) ) ) { <nl> PLOG ( ERROR ) < < " Failed to read header size from " < < path_ . value ( ) ; <nl> return false ; <nl> bool Archive : : Init ( ) { <nl> } <nl> <nl> buf . resize ( size ) ; <nl> - len = file . ReadAtCurrentPos ( buf . data ( ) , buf . size ( ) ) ; <nl> + len = file_ . ReadAtCurrentPos ( buf . data ( ) , buf . size ( ) ) ; <nl> if ( len ! = static_cast < int > ( buf . size ( ) ) ) { <nl> PLOG ( ERROR ) < < " Failed to read header from " < < path_ . value ( ) ; <nl> return false ; <nl> bool Archive : : CopyFileOut ( const base : : FilePath & path , base : : FilePath * out ) { <nl> } <nl> <nl> scoped_ptr < ScopedTemporaryFile > temp_file ( new ScopedTemporaryFile ) ; <nl> - if ( ! temp_file - > InitFromFile ( path_ , info . offset , info . size ) ) <nl> + if ( ! temp_file - > InitFromFile ( & file_ , info . offset , info . size ) ) <nl> return false ; <nl> <nl> * out = temp_file - > path ( ) ; <nl> bool Archive : : CopyFileOut ( const base : : FilePath & path , base : : FilePath * out ) { <nl> return true ; <nl> } <nl> <nl> + int Archive : : GetFD ( ) const { <nl> + if ( ! file_ . IsValid ( ) ) <nl> + return - 1 ; <nl> + <nl> + # if defined ( OS_WIN ) <nl> + return <nl> + _open_osfhandle ( reinterpret_cast < intptr_t > ( file_ . GetPlatformFile ( ) ) , 0 ) ; <nl> + # elif defined ( OS_POSIX ) <nl> + return file_ . GetPlatformFile ( ) ; <nl> + # else <nl> + return - 1 ; <nl> + # endif <nl> + } <nl> + <nl> } / / namespace asar <nl> mmm a / atom / common / asar / archive . h <nl> ppp b / atom / common / asar / archive . h <nl> <nl> # include < vector > <nl> <nl> # include " base / containers / scoped_ptr_hash_map . h " <nl> + # include " base / files / file . h " <nl> # include " base / files / file_path . h " <nl> # include " base / memory / scoped_ptr . h " <nl> <nl> class Archive { <nl> / / For unpacked file , this method will return its real path . <nl> bool CopyFileOut ( const base : : FilePath & path , base : : FilePath * out ) ; <nl> <nl> + / / Returns the file ' s fd . <nl> + int GetFD ( ) const ; <nl> + <nl> base : : FilePath path ( ) const { return path_ ; } <nl> base : : DictionaryValue * header ( ) const { return header_ . get ( ) ; } <nl> <nl> private : <nl> base : : FilePath path_ ; <nl> + base : : File file_ ; <nl> uint32 header_size_ ; <nl> scoped_ptr < base : : DictionaryValue > header_ ; <nl> <nl> mmm a / atom / common / asar / scoped_temporary_file . cc <nl> ppp b / atom / common / asar / scoped_temporary_file . cc <nl> bool ScopedTemporaryFile : : Init ( ) { <nl> return base : : CreateTemporaryFile ( & path_ ) ; <nl> } <nl> <nl> - bool ScopedTemporaryFile : : InitFromFile ( const base : : FilePath & path , <nl> + bool ScopedTemporaryFile : : InitFromFile ( base : : File * src , <nl> uint64 offset , uint64 size ) { <nl> - if ( ! Init ( ) ) <nl> + if ( ! src - > IsValid ( ) ) <nl> return false ; <nl> <nl> - base : : File src ( path , base : : File : : FLAG_OPEN | base : : File : : FLAG_READ ) ; <nl> - if ( ! src . IsValid ( ) ) <nl> + if ( ! Init ( ) ) <nl> return false ; <nl> <nl> std : : vector < char > buf ( size ) ; <nl> - int len = src . Read ( offset , buf . data ( ) , buf . size ( ) ) ; <nl> + int len = src - > Read ( offset , buf . data ( ) , buf . size ( ) ) ; <nl> if ( len ! = static_cast < int > ( size ) ) <nl> return false ; <nl> <nl> mmm a / atom / common / asar / scoped_temporary_file . h <nl> ppp b / atom / common / asar / scoped_temporary_file . h <nl> <nl> <nl> # include " base / files / file_path . h " <nl> <nl> + namespace base { <nl> + class File ; <nl> + } <nl> + <nl> namespace asar { <nl> <nl> / / An object representing a temporary file that should be cleaned up when this <nl> class ScopedTemporaryFile { <nl> bool Init ( ) ; <nl> <nl> / / Init an temporary file and fill it with content of | path | . <nl> - bool InitFromFile ( const base : : FilePath & path , uint64 offset , uint64 size ) ; <nl> + bool InitFromFile ( base : : File * src , uint64 offset , uint64 size ) ; <nl> <nl> base : : FilePath path ( ) const { return path_ ; } <nl> <nl> mmm a / atom / common / atom_version . h <nl> ppp b / atom / common / atom_version . h <nl> <nl> # define ATOM_VERSION_H <nl> <nl> # define ATOM_MAJOR_VERSION 0 <nl> - # define ATOM_MINOR_VERSION 25 <nl> - # define ATOM_PATCH_VERSION 2 <nl> + # define ATOM_MINOR_VERSION 26 <nl> + # define ATOM_PATCH_VERSION 0 <nl> <nl> # define ATOM_VERSION_IS_RELEASE 1 <nl> <nl> mmm a / atom / common / lib / asar . coffee <nl> ppp b / atom / common / lib / asar . coffee <nl> exports . wrapFsWithAsar = ( fs ) - > <nl> return fs . readFile realPath , options , callback <nl> <nl> if not options <nl> - options = encoding : null , flag : ' r ' <nl> + options = encoding : null <nl> else if util . isString options <nl> - options = encoding : options , flag : ' r ' <nl> + options = encoding : options <nl> else if not util . isObject options <nl> throw new TypeError ( ' Bad arguments ' ) <nl> <nl> - flag = options . flag | | ' r ' <nl> encoding = options . encoding <nl> <nl> buffer = new Buffer ( info . size ) <nl> - open archive . path , flag , ( error , fd ) - > <nl> - return callback error if error <nl> - fs . read fd , buffer , 0 , info . size , info . offset , ( error ) - > <nl> - fs . close fd , - > <nl> - callback error , if encoding then buffer . toString encoding else buffer <nl> + fd = archive . getFd ( ) <nl> + return notFoundError asarPath , filePath , callback unless fd > = 0 <nl> + <nl> + fs . read fd , buffer , 0 , info . size , info . offset , ( error ) - > <nl> + callback error , if encoding then buffer . toString encoding else buffer <nl> <nl> openSync = fs . openSync <nl> readFileSync = fs . readFileSync <nl> exports . wrapFsWithAsar = ( fs ) - > <nl> return fs . readFileSync realPath , options <nl> <nl> if not options <nl> - options = encoding : null , flag : ' r ' <nl> + options = encoding : null <nl> else if util . isString options <nl> - options = encoding : options , flag : ' r ' <nl> + options = encoding : options <nl> else if not util . isObject options <nl> throw new TypeError ( ' Bad arguments ' ) <nl> <nl> - flag = options . flag | | ' r ' <nl> encoding = options . encoding <nl> <nl> buffer = new Buffer ( info . size ) <nl> - fd = openSync archive . path , flag <nl> - try <nl> - fs . readSync fd , buffer , 0 , info . size , info . offset <nl> - catch e <nl> - throw e <nl> - finally <nl> - fs . closeSync fd <nl> + fd = archive . getFd ( ) <nl> + notFoundError asarPath , filePath unless fd > = 0 <nl> + <nl> + fs . readSync fd , buffer , 0 , info . size , info . offset <nl> if encoding then buffer . toString encoding else buffer <nl> <nl> readdir = fs . readdir <nl> mmm a / atom / common / options_switches . cc <nl> ppp b / atom / common / options_switches . cc <nl> const char kDirectWrite [ ] = " direct - write " ; <nl> / / Enable plugins . <nl> const char kEnablePlugins [ ] = " enable - plugins " ; <nl> <nl> + / / Ppapi Flash path . <nl> + const char kPpapiFlashPath [ ] = " ppapi - flash - path " ; <nl> + <nl> + / / Ppapi Flash version . <nl> + const char kPpapiFlashVersion [ ] = " ppapi - flash - version " ; <nl> + <nl> / / Instancd ID of guest WebContents . <nl> const char kGuestInstanceID [ ] = " guest - instance - id " ; <nl> <nl> const char kType [ ] = " type " ; <nl> / / Disable auto - hiding cursor . <nl> const char kDisableAutoHideCursor [ ] = " disable - auto - hide - cursor " ; <nl> <nl> + / / Use the OS X ' s standard window instead of the textured window . <nl> + const char kStandardWindow [ ] = " standard - window " ; <nl> + <nl> / / Web runtime features . <nl> const char kExperimentalFeatures [ ] = " experimental - features " ; <nl> const char kExperimentalCanvasFeatures [ ] = " experimental - canvas - features " ; <nl> mmm a / atom / common / options_switches . h <nl> ppp b / atom / common / options_switches . h <nl> extern const char kEnableLargerThanScreen [ ] ; <nl> extern const char kDarkTheme [ ] ; <nl> extern const char kDirectWrite [ ] ; <nl> extern const char kEnablePlugins [ ] ; <nl> + extern const char kPpapiFlashPath [ ] ; <nl> + extern const char kPpapiFlashVersion [ ] ; <nl> extern const char kGuestInstanceID [ ] ; <nl> extern const char kPreloadScript [ ] ; <nl> extern const char kTransparent [ ] ; <nl> extern const char kType [ ] ; <nl> extern const char kDisableAutoHideCursor [ ] ; <nl> + extern const char kStandardWindow [ ] ; <nl> <nl> extern const char kExperimentalFeatures [ ] ; <nl> extern const char kExperimentalCanvasFeatures [ ] ; <nl> mmm a / atom / renderer / api / lib / remote . coffee <nl> ppp b / atom / renderer / api / lib / remote . coffee <nl> exports . require = ( module ) - > <nl> meta = ipc . sendSync ' ATOM_BROWSER_REQUIRE ' , module <nl> moduleCache [ module ] = metaToValue meta <nl> <nl> - # Get current window object . <nl> + # Get current BrowserWindow object . <nl> windowCache = null <nl> exports . getCurrentWindow = - > <nl> return windowCache if windowCache ? <nl> meta = ipc . sendSync ' ATOM_BROWSER_CURRENT_WINDOW ' , process . guestInstanceId <nl> windowCache = metaToValue meta <nl> <nl> + # Get current WebContents object . <nl> + webContentsCache = null <nl> + exports . getCurrentWebContents = - > <nl> + return webContentsCache if webContentsCache ? <nl> + meta = ipc . sendSync ' ATOM_BROWSER_CURRENT_WEB_CONTENTS ' <nl> + webContentsCache = metaToValue meta <nl> + <nl> # Get a global object in browser . <nl> exports . getGlobal = ( name ) - > <nl> meta = ipc . sendSync ' ATOM_BROWSER_GLOBAL ' , name <nl> mmm a / atom / renderer / atom_renderer_client . cc <nl> ppp b / atom / renderer / atom_renderer_client . cc <nl> <nl> # include " atom / common / options_switches . h " <nl> # include " atom / renderer / atom_render_view_observer . h " <nl> # include " atom / renderer / guest_view_container . h " <nl> + # include " chrome / renderer / pepper / pepper_helper . h " <nl> # include " chrome / renderer / printing / print_web_view_helper . h " <nl> # include " chrome / renderer / tts_dispatcher . h " <nl> # include " content / public / common / content_constants . h " <nl> void AtomRendererClient : : RenderThreadStarted ( ) { <nl> content : : RenderThread : : Get ( ) - > AddObserver ( this ) ; <nl> } <nl> <nl> + void AtomRendererClient : : RenderFrameCreated ( <nl> + content : : RenderFrame * render_frame ) { <nl> + new PepperHelper ( render_frame ) ; <nl> + } <nl> + <nl> void AtomRendererClient : : RenderViewCreated ( content : : RenderView * render_view ) { <nl> new printing : : PrintWebViewHelper ( render_view ) ; <nl> new AtomRenderViewObserver ( render_view , this ) ; <nl> mmm a / atom / renderer / atom_renderer_client . h <nl> ppp b / atom / renderer / atom_renderer_client . h <nl> class AtomRendererClient : public content : : ContentRendererClient , <nl> <nl> / / content : : ContentRendererClient : <nl> void RenderThreadStarted ( ) override ; <nl> + void RenderFrameCreated ( content : : RenderFrame * ) override ; <nl> void RenderViewCreated ( content : : RenderView * ) override ; <nl> blink : : WebSpeechSynthesizer * OverrideSpeechSynthesizer ( <nl> blink : : WebSpeechSynthesizerClient * client ) override ; <nl> mmm a / atom / renderer / lib / override . coffee <nl> ppp b / atom / renderer / lib / override . coffee <nl> window . confirm = ( message , title = ' ' ) - > <nl> window . prompt = - > <nl> throw new Error ( ' prompt ( ) is and will not be supported . ' ) <nl> <nl> + # Simple implementation of postMessage . <nl> window . opener = <nl> postMessage : ( message , targetOrigin = ' * ' ) - > <nl> ipc . send ' ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE ' , message , targetOrigin <nl> <nl> ipc . on ' ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE ' , ( message , targetOrigin ) - > <nl> window . postMessage message , targetOrigin <nl> + <nl> + # Forward history operations to browser . <nl> + sendHistoryOperation = ( args . . . ) - > <nl> + ipc . send ' ATOM_SHELL_NAVIGATION_CONTROLLER ' , args . . . <nl> + window . history . back = - > sendHistoryOperation ' goBack ' <nl> + window . history . forward = - > sendHistoryOperation ' goForward ' <nl> + window . history . go = ( offset ) - > sendHistoryOperation ' goToOffset ' , offset <nl> mmm a / atom / renderer / lib / web - view / web - view . coffee <nl> ppp b / atom / renderer / lib / web - view / web - view . coffee <nl> registerWebViewElement = - > <nl> remote . getGuestWebContents ( internal . guestInstanceId ) [ m ] args . . . <nl> proto [ m ] = createHandler m for m in methods <nl> <nl> - # Return dataUrl instead of nativeImage . <nl> - proto . getFavicon = ( args . . . ) - > <nl> - internal = v8Util . getHiddenValue this , ' internal ' <nl> - return unless internal <nl> - favicon = remote . getGuestWebContents ( internal . guestInstanceId ) [ ' getFavicon ' ] args . . . <nl> - favicon . toDataUrl ( ) <nl> - <nl> window . WebView = webFrame . registerEmbedderCustomElement ' webview ' , <nl> prototype : proto <nl> <nl> new file mode 100644 <nl> index 000000000000 . . cc739227aad8 <nl> mmm / dev / null <nl> ppp b / atom / utility / atom_content_utility_client . cc <nl> <nl> + / / Copyright ( c ) 2015 GitHub , Inc . <nl> + / / Use of this source code is governed by the MIT license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " atom / utility / atom_content_utility_client . h " <nl> + <nl> + # include " base / command_line . h " <nl> + # include " base / files / file_path . h " <nl> + # include " base / memory / ref_counted . h " <nl> + # include " base / time / time . h " <nl> + # include " chrome / common / chrome_utility_messages . h " <nl> + # include " chrome / utility / utility_message_handler . h " <nl> + # include " content / public / common / content_switches . h " <nl> + # include " content / public / utility / utility_thread . h " <nl> + # include " ipc / ipc_channel . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + <nl> + <nl> + # if defined ( OS_WIN ) <nl> + # include " chrome / utility / printing_handler . h " <nl> + # endif <nl> + <nl> + <nl> + namespace { <nl> + <nl> + bool Send ( IPC : : Message * message ) { <nl> + return content : : UtilityThread : : Get ( ) - > Send ( message ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + namespace atom { <nl> + <nl> + int64_t AtomContentUtilityClient : : max_ipc_message_size_ = <nl> + IPC : : Channel : : kMaximumMessageSize ; <nl> + <nl> + AtomContentUtilityClient : : AtomContentUtilityClient ( ) <nl> + : filter_messages_ ( false ) { <nl> + # if defined ( OS_WIN ) <nl> + handlers_ . push_back ( new PrintingHandler ( ) ) ; <nl> + # endif <nl> + } <nl> + <nl> + AtomContentUtilityClient : : ~ AtomContentUtilityClient ( ) { <nl> + } <nl> + <nl> + void AtomContentUtilityClient : : UtilityThreadStarted ( ) { <nl> + } <nl> + <nl> + bool AtomContentUtilityClient : : OnMessageReceived ( <nl> + const IPC : : Message & message ) { <nl> + if ( filter_messages_ & & ! ContainsKey ( message_id_whitelist_ , message . type ( ) ) ) <nl> + return false ; <nl> + <nl> + bool handled = true ; <nl> + IPC_BEGIN_MESSAGE_MAP ( AtomContentUtilityClient , message ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityMsg_StartupPing , OnStartupPing ) <nl> + IPC_MESSAGE_UNHANDLED ( handled = false ) <nl> + IPC_END_MESSAGE_MAP ( ) <nl> + <nl> + for ( Handlers : : iterator it = handlers_ . begin ( ) ; <nl> + ! handled & & it ! = handlers_ . end ( ) ; + + it ) { <nl> + handled = ( * it ) - > OnMessageReceived ( message ) ; <nl> + } <nl> + <nl> + return handled ; <nl> + } <nl> + <nl> + void AtomContentUtilityClient : : OnStartupPing ( ) { <nl> + Send ( new ChromeUtilityHostMsg_ProcessStarted ) ; <nl> + / / Don ' t release the process , we assume further messages are on the way . <nl> + } <nl> + <nl> + } / / namespace atom <nl> new file mode 100644 <nl> index 000000000000 . . 2c245b62f61e <nl> mmm / dev / null <nl> ppp b / atom / utility / atom_content_utility_client . h <nl> <nl> + / / Copyright ( c ) 2015 GitHub , Inc . <nl> + / / Use of this source code is governed by the MIT license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef ATOM_UTILITY_ATOM_CONTENT_UTILITY_CLIENT_H_ <nl> + # define ATOM_UTILITY_ATOM_CONTENT_UTILITY_CLIENT_H_ <nl> + <nl> + # include < set > <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " base / memory / scoped_vector . h " <nl> + # include " content / public / utility / content_utility_client . h " <nl> + # include " ipc / ipc_platform_file . h " <nl> + <nl> + namespace base { <nl> + class FilePath ; <nl> + struct FileDescriptor ; <nl> + } <nl> + <nl> + class UtilityMessageHandler ; <nl> + <nl> + namespace atom { <nl> + <nl> + class AtomContentUtilityClient : public content : : ContentUtilityClient { <nl> + public : <nl> + AtomContentUtilityClient ( ) ; <nl> + ~ AtomContentUtilityClient ( ) override ; <nl> + <nl> + void UtilityThreadStarted ( ) override ; <nl> + bool OnMessageReceived ( const IPC : : Message & message ) override ; <nl> + <nl> + <nl> + static void set_max_ipc_message_size_for_test ( int64_t max_message_size ) { <nl> + max_ipc_message_size_ = max_message_size ; <nl> + } <nl> + <nl> + private : <nl> + void OnStartupPing ( ) ; <nl> + <nl> + typedef ScopedVector < UtilityMessageHandler > Handlers ; <nl> + Handlers handlers_ ; <nl> + <nl> + / / Flag to enable whitelisting . <nl> + bool filter_messages_ ; <nl> + / / A list of message_ids to filter . <nl> + std : : set < int > message_id_whitelist_ ; <nl> + / / Maximum IPC msg size ( default to kMaximumMessageSize ; override for testing ) <nl> + static int64_t max_ipc_message_size_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( AtomContentUtilityClient ) ; <nl> + } ; <nl> + <nl> + } / / namespace atom <nl> + <nl> + # endif / / ATOM_UTILITY_ATOM_CONTENT_UTILITY_CLIENT_H_ <nl> mmm a / chromium_src / chrome / browser / extensions / global_shortcut_listener_win . cc <nl> ppp b / chromium_src / chrome / browser / extensions / global_shortcut_listener_win . cc <nl> void GlobalShortcutListenerWin : : OnWndProc ( HWND hwnd , <nl> modifiers | = ( LOWORD ( lparam ) & MOD_SHIFT ) ? ui : : EF_SHIFT_DOWN : 0 ; <nl> modifiers | = ( LOWORD ( lparam ) & MOD_ALT ) ? ui : : EF_ALT_DOWN : 0 ; <nl> modifiers | = ( LOWORD ( lparam ) & MOD_CONTROL ) ? ui : : EF_CONTROL_DOWN : 0 ; <nl> + modifiers | = ( LOWORD ( lparam ) & MOD_WIN ) ? ui : : EF_COMMAND_DOWN : 0 ; <nl> + <nl> ui : : Accelerator accelerator ( <nl> ui : : KeyboardCodeForWindowsKeyCode ( key_code ) , modifiers ) ; <nl> <nl> bool GlobalShortcutListenerWin : : RegisterAcceleratorImpl ( <nl> modifiers | = accelerator . IsShiftDown ( ) ? MOD_SHIFT : 0 ; <nl> modifiers | = accelerator . IsCtrlDown ( ) ? MOD_CONTROL : 0 ; <nl> modifiers | = accelerator . IsAltDown ( ) ? MOD_ALT : 0 ; <nl> + modifiers | = accelerator . IsCmdDown ( ) ? MOD_WIN : 0 ; <nl> + <nl> static int hotkey_id = 0 ; <nl> bool success = ! ! RegisterHotKey ( <nl> gfx : : SingletonHwnd : : GetInstance ( ) - > hwnd ( ) , <nl> mmm a / chromium_src / chrome / browser / extensions / global_shortcut_listener_x11 . cc <nl> ppp b / chromium_src / chrome / browser / extensions / global_shortcut_listener_x11 . cc <nl> int GetNativeModifiers ( const ui : : Accelerator & accelerator ) { <nl> modifiers | = accelerator . IsShiftDown ( ) ? ShiftMask : 0 ; <nl> modifiers | = accelerator . IsCtrlDown ( ) ? ControlMask : 0 ; <nl> modifiers | = accelerator . IsAltDown ( ) ? Mod1Mask : 0 ; <nl> + modifiers | = accelerator . IsCmdDown ( ) ? Mod4Mask : 0 ; <nl> <nl> return modifiers ; <nl> } <nl> void GlobalShortcutListenerX11 : : OnXKeyPressEvent ( : : XEvent * x_event ) { <nl> modifiers | = ( x_event - > xkey . state & ShiftMask ) ? ui : : EF_SHIFT_DOWN : 0 ; <nl> modifiers | = ( x_event - > xkey . state & ControlMask ) ? ui : : EF_CONTROL_DOWN : 0 ; <nl> modifiers | = ( x_event - > xkey . state & Mod1Mask ) ? ui : : EF_ALT_DOWN : 0 ; <nl> + / / For Windows key <nl> + modifiers | = ( x_event - > xkey . state & Mod4Mask ) ? ui : : EF_COMMAND_DOWN : 0 ; <nl> <nl> ui : : Accelerator accelerator ( <nl> ui : : KeyboardCodeFromXKeyEvent ( x_event ) , modifiers ) ; <nl> new file mode 100644 <nl> index 000000000000 . . 89bac3b68dca <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / printing / pdf_to_emf_converter . cc <nl> <nl> + / / Copyright 2014 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / printing / pdf_to_emf_converter . h " <nl> + <nl> + # include < queue > <nl> + <nl> + # include " base / files / file . h " <nl> + # include " base / files / file_util . h " <nl> + # include " base / files / scoped_temp_dir . h " <nl> + # include " base / logging . h " <nl> + # include " chrome / common / chrome_utility_messages . h " <nl> + # include " chrome / common / print_messages . h " <nl> + # include " content / public / browser / browser_thread . h " <nl> + # include " content / public / browser / child_process_data . h " <nl> + # include " content / public / browser / utility_process_host . h " <nl> + # include " content / public / browser / utility_process_host_client . h " <nl> + # include " printing / emf_win . h " <nl> + # include " printing / pdf_render_settings . h " <nl> + <nl> + namespace printing { <nl> + <nl> + namespace { <nl> + <nl> + using content : : BrowserThread ; <nl> + <nl> + class PdfToEmfConverterImpl ; <nl> + <nl> + / / Allows to delete temporary directory after all temporary files created inside <nl> + / / are closed . Windows cannot delete directory with opened files . Directory is <nl> + / / used to store PDF and metafiles . PDF should be gone by the time utility <nl> + / / process exits . Metafiles should be gone when all LazyEmf destroyed . <nl> + class RefCountedTempDir <nl> + : public base : : RefCountedThreadSafe < RefCountedTempDir , <nl> + BrowserThread : : DeleteOnFileThread > { <nl> + public : <nl> + RefCountedTempDir ( ) { ignore_result ( temp_dir_ . CreateUniqueTempDir ( ) ) ; } <nl> + bool IsValid ( ) const { return temp_dir_ . IsValid ( ) ; } <nl> + const base : : FilePath & GetPath ( ) const { return temp_dir_ . path ( ) ; } <nl> + <nl> + private : <nl> + friend struct BrowserThread : : DeleteOnThread < BrowserThread : : FILE > ; <nl> + friend class base : : DeleteHelper < RefCountedTempDir > ; <nl> + ~ RefCountedTempDir ( ) { } <nl> + <nl> + base : : ScopedTempDir temp_dir_ ; <nl> + DISALLOW_COPY_AND_ASSIGN ( RefCountedTempDir ) ; <nl> + } ; <nl> + <nl> + typedef scoped_ptr < base : : File , BrowserThread : : DeleteOnFileThread > <nl> + ScopedTempFile ; <nl> + <nl> + / / Wrapper for Emf to keep only file handle in memory , and load actual data only <nl> + / / on playback . Emf : : InitFromFile ( ) can play metafile directly from disk , but it <nl> + / / can ' t open file handles . We need file handles to reliably delete temporary <nl> + / / files , and to efficiently interact with utility process . <nl> + class LazyEmf : public MetafilePlayer { <nl> + public : <nl> + LazyEmf ( const scoped_refptr < RefCountedTempDir > & temp_dir , ScopedTempFile file ) <nl> + : temp_dir_ ( temp_dir ) , file_ ( file . Pass ( ) ) { } <nl> + virtual ~ LazyEmf ( ) { Close ( ) ; } <nl> + <nl> + virtual bool SafePlayback ( HDC hdc ) const override ; <nl> + virtual bool SaveTo ( base : : File * file ) const override ; <nl> + <nl> + private : <nl> + void Close ( ) const ; <nl> + bool LoadEmf ( Emf * emf ) const ; <nl> + <nl> + mutable scoped_refptr < RefCountedTempDir > temp_dir_ ; <nl> + mutable ScopedTempFile file_ ; / / Mutable because of consts in base class . <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( LazyEmf ) ; <nl> + } ; <nl> + <nl> + / / Converts PDF into EMF . <nl> + / / Class uses 3 threads : UI , IO and FILE . <nl> + / / Internal workflow is following : <nl> + / / 1 . Create instance on the UI thread . ( files_ , settings_ , ) <nl> + / / 2 . Create pdf file on the FILE thread . <nl> + / / 3 . Start utility process and start conversion on the IO thread . <nl> + / / 4 . Utility process returns page count . <nl> + / / 5 . For each page : <nl> + / / 1 . Clients requests page with file handle to a temp file . <nl> + / / 2 . Utility converts the page , save it to the file and reply . <nl> + / / <nl> + / / All these steps work sequentially , so no data should be accessed <nl> + / / simultaneously by several threads . <nl> + class PdfToEmfUtilityProcessHostClient <nl> + : public content : : UtilityProcessHostClient { <nl> + public : <nl> + PdfToEmfUtilityProcessHostClient ( <nl> + base : : WeakPtr < PdfToEmfConverterImpl > converter , <nl> + const PdfRenderSettings & settings ) ; <nl> + <nl> + void Start ( const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfToEmfConverter : : StartCallback & start_callback ) ; <nl> + <nl> + void GetPage ( int page_number , <nl> + const PdfToEmfConverter : : GetPageCallback & get_page_callback ) ; <nl> + <nl> + void Stop ( ) ; <nl> + <nl> + / / UtilityProcessHostClient implementation . <nl> + virtual void OnProcessCrashed ( int exit_code ) override ; <nl> + virtual void OnProcessLaunchFailed ( ) override ; <nl> + virtual bool OnMessageReceived ( const IPC : : Message & message ) override ; <nl> + <nl> + private : <nl> + class GetPageCallbackData { <nl> + MOVE_ONLY_TYPE_FOR_CPP_03 ( GetPageCallbackData , RValue ) ; <nl> + <nl> + public : <nl> + GetPageCallbackData ( int page_number , <nl> + PdfToEmfConverter : : GetPageCallback callback ) <nl> + : page_number_ ( page_number ) , callback_ ( callback ) { } <nl> + <nl> + / / Move constructor for STL . <nl> + GetPageCallbackData ( RValue other ) { this - > operator = ( other ) ; } <nl> + <nl> + / / Move assignment for STL . <nl> + GetPageCallbackData & operator = ( RValue rhs ) { <nl> + page_number_ = rhs . object - > page_number_ ; <nl> + callback_ = rhs . object - > callback_ ; <nl> + emf_ = rhs . object - > emf_ . Pass ( ) ; <nl> + return * this ; <nl> + } <nl> + <nl> + int page_number ( ) const { return page_number_ ; } <nl> + const PdfToEmfConverter : : GetPageCallback & callback ( ) const { <nl> + return callback_ ; <nl> + } <nl> + ScopedTempFile emf ( ) { return emf_ . Pass ( ) ; } <nl> + void set_emf ( ScopedTempFile emf ) { emf_ = emf . Pass ( ) ; } <nl> + <nl> + private : <nl> + int page_number_ ; <nl> + PdfToEmfConverter : : GetPageCallback callback_ ; <nl> + ScopedTempFile emf_ ; <nl> + } ; <nl> + <nl> + virtual ~ PdfToEmfUtilityProcessHostClient ( ) ; <nl> + <nl> + bool Send ( IPC : : Message * msg ) ; <nl> + <nl> + / / Message handlers . <nl> + void OnProcessStarted ( ) ; <nl> + void OnPageCount ( int page_count ) ; <nl> + void OnPageDone ( bool success , float scale_factor ) ; <nl> + <nl> + void OnFailed ( ) ; <nl> + void OnTempPdfReady ( ScopedTempFile pdf ) ; <nl> + void OnTempEmfReady ( GetPageCallbackData * callback_data , ScopedTempFile emf ) ; <nl> + <nl> + scoped_refptr < RefCountedTempDir > temp_dir_ ; <nl> + <nl> + / / Used to suppress callbacks after PdfToEmfConverterImpl is deleted . <nl> + base : : WeakPtr < PdfToEmfConverterImpl > converter_ ; <nl> + PdfRenderSettings settings_ ; <nl> + scoped_refptr < base : : RefCountedMemory > data_ ; <nl> + <nl> + / / Document loaded callback . <nl> + PdfToEmfConverter : : StartCallback start_callback_ ; <nl> + <nl> + / / Process host for IPC . <nl> + base : : WeakPtr < content : : UtilityProcessHost > utility_process_host_ ; <nl> + <nl> + / / Queue of callbacks for GetPage ( ) requests . Utility process should reply <nl> + / / with PageDone in the same order as requests were received . <nl> + / / Use containers that keeps element pointers valid after push ( ) and pop ( ) . <nl> + typedef std : : queue < GetPageCallbackData > GetPageCallbacks ; <nl> + GetPageCallbacks get_page_callbacks_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PdfToEmfUtilityProcessHostClient ) ; <nl> + } ; <nl> + <nl> + class PdfToEmfConverterImpl : public PdfToEmfConverter { <nl> + public : <nl> + PdfToEmfConverterImpl ( ) ; <nl> + <nl> + virtual ~ PdfToEmfConverterImpl ( ) ; <nl> + <nl> + virtual void Start ( const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfRenderSettings & conversion_settings , <nl> + const StartCallback & start_callback ) override ; <nl> + <nl> + virtual void GetPage ( int page_number , <nl> + const GetPageCallback & get_page_callback ) override ; <nl> + <nl> + / / Helps to cancel callbacks if this object is destroyed . <nl> + void RunCallback ( const base : : Closure & callback ) ; <nl> + <nl> + private : <nl> + scoped_refptr < PdfToEmfUtilityProcessHostClient > utility_client_ ; <nl> + base : : WeakPtrFactory < PdfToEmfConverterImpl > weak_ptr_factory_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PdfToEmfConverterImpl ) ; <nl> + } ; <nl> + <nl> + ScopedTempFile CreateTempFile ( scoped_refptr < RefCountedTempDir > * temp_dir ) { <nl> + if ( ! temp_dir - > get ( ) ) <nl> + * temp_dir = new RefCountedTempDir ( ) ; <nl> + ScopedTempFile file ; <nl> + if ( ! ( * temp_dir ) - > IsValid ( ) ) <nl> + return file . Pass ( ) ; <nl> + base : : FilePath path ; <nl> + if ( ! base : : CreateTemporaryFileInDir ( ( * temp_dir ) - > GetPath ( ) , & path ) ) <nl> + return file . Pass ( ) ; <nl> + file . reset ( new base : : File ( path , <nl> + base : : File : : FLAG_CREATE_ALWAYS | <nl> + base : : File : : FLAG_WRITE | <nl> + base : : File : : FLAG_READ | <nl> + base : : File : : FLAG_DELETE_ON_CLOSE | <nl> + base : : File : : FLAG_TEMPORARY ) ) ; <nl> + if ( ! file - > IsValid ( ) ) <nl> + file . reset ( ) ; <nl> + return file . Pass ( ) ; <nl> + } <nl> + <nl> + ScopedTempFile CreateTempPdfFile ( <nl> + const scoped_refptr < base : : RefCountedMemory > & data , <nl> + scoped_refptr < RefCountedTempDir > * temp_dir ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : FILE ) ; <nl> + <nl> + ScopedTempFile pdf_file = CreateTempFile ( temp_dir ) ; <nl> + if ( ! pdf_file | | <nl> + static_cast < int > ( data - > size ( ) ) ! = <nl> + pdf_file - > WriteAtCurrentPos ( data - > front_as < char > ( ) , data - > size ( ) ) ) { <nl> + pdf_file . reset ( ) ; <nl> + } <nl> + pdf_file - > Seek ( base : : File : : FROM_BEGIN , 0 ) ; <nl> + return pdf_file . Pass ( ) ; <nl> + } <nl> + <nl> + bool LazyEmf : : SafePlayback ( HDC hdc ) const { <nl> + Emf emf ; <nl> + bool result = LoadEmf ( & emf ) & & emf . SafePlayback ( hdc ) ; <nl> + / / TODO ( vitalybuka ) : Fix destruction of metafiles . For some reasons <nl> + / / instances of Emf are not deleted . crbug . com / 411683 <nl> + / / It ' s known that the Emf going to be played just once to a printer . So just <nl> + / / release file here . <nl> + Close ( ) ; <nl> + return result ; <nl> + } <nl> + <nl> + bool LazyEmf : : SaveTo ( base : : File * file ) const { <nl> + Emf emf ; <nl> + return LoadEmf ( & emf ) & & emf . SaveTo ( file ) ; <nl> + } <nl> + <nl> + void LazyEmf : : Close ( ) const { <nl> + file_ . reset ( ) ; <nl> + temp_dir_ = NULL ; <nl> + } <nl> + <nl> + bool LazyEmf : : LoadEmf ( Emf * emf ) const { <nl> + file_ - > Seek ( base : : File : : FROM_BEGIN , 0 ) ; <nl> + int64 size = file_ - > GetLength ( ) ; <nl> + if ( size < = 0 ) <nl> + return false ; <nl> + std : : vector < char > data ( size ) ; <nl> + if ( file_ - > ReadAtCurrentPos ( data . data ( ) , data . size ( ) ) ! = size ) <nl> + return false ; <nl> + return emf - > InitFromData ( data . data ( ) , data . size ( ) ) ; <nl> + } <nl> + <nl> + PdfToEmfUtilityProcessHostClient : : PdfToEmfUtilityProcessHostClient ( <nl> + base : : WeakPtr < PdfToEmfConverterImpl > converter , <nl> + const PdfRenderSettings & settings ) <nl> + : converter_ ( converter ) , settings_ ( settings ) { <nl> + } <nl> + <nl> + PdfToEmfUtilityProcessHostClient : : ~ PdfToEmfUtilityProcessHostClient ( ) { <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : Start ( <nl> + const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfToEmfConverter : : StartCallback & start_callback ) { <nl> + if ( ! BrowserThread : : CurrentlyOn ( BrowserThread : : IO ) ) { <nl> + BrowserThread : : PostTask ( BrowserThread : : IO , <nl> + FROM_HERE , <nl> + base : : Bind ( & PdfToEmfUtilityProcessHostClient : : Start , <nl> + this , <nl> + data , <nl> + start_callback ) ) ; <nl> + return ; <nl> + } <nl> + data_ = data ; <nl> + <nl> + / / Store callback before any OnFailed ( ) call to make it called on failure . <nl> + start_callback_ = start_callback ; <nl> + <nl> + / / NOTE : This process _must_ be sandboxed , otherwise the pdf dll will load <nl> + / / gdiplus . dll , change how rendering happens , and not be able to correctly <nl> + / / generate when sent to a metafile DC . <nl> + utility_process_host_ = <nl> + content : : UtilityProcessHost : : Create ( <nl> + this , base : : MessageLoop : : current ( ) - > message_loop_proxy ( ) ) <nl> + - > AsWeakPtr ( ) ; <nl> + if ( ! utility_process_host_ ) <nl> + return OnFailed ( ) ; <nl> + / / Should reply with OnProcessStarted ( ) . <nl> + Send ( new ChromeUtilityMsg_StartupPing ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnProcessStarted ( ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( ! utility_process_host_ ) <nl> + return OnFailed ( ) ; <nl> + <nl> + scoped_refptr < base : : RefCountedMemory > data = data_ ; <nl> + data_ = NULL ; <nl> + BrowserThread : : PostTaskAndReplyWithResult ( <nl> + BrowserThread : : FILE , <nl> + FROM_HERE , <nl> + base : : Bind ( & CreateTempPdfFile , data , & temp_dir_ ) , <nl> + base : : Bind ( & PdfToEmfUtilityProcessHostClient : : OnTempPdfReady , this ) ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnTempPdfReady ( ScopedTempFile pdf ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( ! utility_process_host_ ) <nl> + return OnFailed ( ) ; <nl> + base : : ProcessHandle process = utility_process_host_ - > GetData ( ) . handle ; <nl> + / / Should reply with OnPageCount ( ) . <nl> + Send ( new ChromeUtilityMsg_RenderPDFPagesToMetafiles ( <nl> + IPC : : GetFileHandleForProcess ( pdf - > GetPlatformFile ( ) , process , false ) , <nl> + settings_ ) ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnPageCount ( int page_count ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( start_callback_ . is_null ( ) ) <nl> + return OnFailed ( ) ; <nl> + BrowserThread : : PostTask ( BrowserThread : : UI , <nl> + FROM_HERE , <nl> + base : : Bind ( & PdfToEmfConverterImpl : : RunCallback , <nl> + converter_ , <nl> + base : : Bind ( start_callback_ , page_count ) ) ) ; <nl> + start_callback_ . Reset ( ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : GetPage ( <nl> + int page_number , <nl> + const PdfToEmfConverter : : GetPageCallback & get_page_callback ) { <nl> + if ( ! BrowserThread : : CurrentlyOn ( BrowserThread : : IO ) ) { <nl> + BrowserThread : : PostTask ( <nl> + BrowserThread : : IO , <nl> + FROM_HERE , <nl> + base : : Bind ( & PdfToEmfUtilityProcessHostClient : : GetPage , <nl> + this , <nl> + page_number , <nl> + get_page_callback ) ) ; <nl> + return ; <nl> + } <nl> + <nl> + / / Store callback before any OnFailed ( ) call to make it called on failure . <nl> + get_page_callbacks_ . push ( GetPageCallbackData ( page_number , get_page_callback ) ) ; <nl> + <nl> + if ( ! utility_process_host_ ) <nl> + return OnFailed ( ) ; <nl> + <nl> + BrowserThread : : PostTaskAndReplyWithResult ( <nl> + BrowserThread : : FILE , <nl> + FROM_HERE , <nl> + base : : Bind ( & CreateTempFile , & temp_dir_ ) , <nl> + base : : Bind ( & PdfToEmfUtilityProcessHostClient : : OnTempEmfReady , <nl> + this , <nl> + & get_page_callbacks_ . back ( ) ) ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnTempEmfReady ( <nl> + GetPageCallbackData * callback_data , <nl> + ScopedTempFile emf ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( ! utility_process_host_ ) <nl> + return OnFailed ( ) ; <nl> + base : : ProcessHandle process = utility_process_host_ - > GetData ( ) . handle ; <nl> + IPC : : PlatformFileForTransit transit = <nl> + IPC : : GetFileHandleForProcess ( emf - > GetPlatformFile ( ) , process , false ) ; <nl> + callback_data - > set_emf ( emf . Pass ( ) ) ; <nl> + / / Should reply with OnPageDone ( ) . <nl> + Send ( new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage ( <nl> + callback_data - > page_number ( ) , transit ) ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnPageDone ( bool success , <nl> + float scale_factor ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( get_page_callbacks_ . empty ( ) ) <nl> + return OnFailed ( ) ; <nl> + scoped_ptr < MetafilePlayer > emf ; <nl> + GetPageCallbackData & data = get_page_callbacks_ . front ( ) ; <nl> + if ( success ) <nl> + emf . reset ( new LazyEmf ( temp_dir_ , data . emf ( ) . Pass ( ) ) ) ; <nl> + BrowserThread : : PostTask ( BrowserThread : : UI , <nl> + FROM_HERE , <nl> + base : : Bind ( & PdfToEmfConverterImpl : : RunCallback , <nl> + converter_ , <nl> + base : : Bind ( data . callback ( ) , <nl> + data . page_number ( ) , <nl> + scale_factor , <nl> + base : : Passed ( & emf ) ) ) ) ; <nl> + get_page_callbacks_ . pop ( ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : Stop ( ) { <nl> + if ( ! BrowserThread : : CurrentlyOn ( BrowserThread : : IO ) ) { <nl> + BrowserThread : : PostTask ( <nl> + BrowserThread : : IO , <nl> + FROM_HERE , <nl> + base : : Bind ( & PdfToEmfUtilityProcessHostClient : : Stop , this ) ) ; <nl> + return ; <nl> + } <nl> + Send ( new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop ( ) ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnProcessCrashed ( int exit_code ) { <nl> + OnFailed ( ) ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnProcessLaunchFailed ( ) { <nl> + OnFailed ( ) ; <nl> + } <nl> + <nl> + bool PdfToEmfUtilityProcessHostClient : : OnMessageReceived ( <nl> + const IPC : : Message & message ) { <nl> + bool handled = true ; <nl> + IPC_BEGIN_MESSAGE_MAP ( PdfToEmfUtilityProcessHostClient , message ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityHostMsg_ProcessStarted , OnProcessStarted ) <nl> + IPC_MESSAGE_HANDLER ( <nl> + ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount , OnPageCount ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone , <nl> + OnPageDone ) <nl> + IPC_MESSAGE_UNHANDLED ( handled = false ) <nl> + IPC_END_MESSAGE_MAP ( ) <nl> + return handled ; <nl> + } <nl> + <nl> + bool PdfToEmfUtilityProcessHostClient : : Send ( IPC : : Message * msg ) { <nl> + if ( utility_process_host_ ) <nl> + return utility_process_host_ - > Send ( msg ) ; <nl> + delete msg ; <nl> + return false ; <nl> + } <nl> + <nl> + void PdfToEmfUtilityProcessHostClient : : OnFailed ( ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : IO ) ; <nl> + if ( ! start_callback_ . is_null ( ) ) <nl> + OnPageCount ( 0 ) ; <nl> + while ( ! get_page_callbacks_ . empty ( ) ) <nl> + OnPageDone ( false , 0 . 0f ) ; <nl> + utility_process_host_ . reset ( ) ; <nl> + } <nl> + <nl> + PdfToEmfConverterImpl : : PdfToEmfConverterImpl ( ) : weak_ptr_factory_ ( this ) { <nl> + } <nl> + <nl> + PdfToEmfConverterImpl : : ~ PdfToEmfConverterImpl ( ) { <nl> + if ( utility_client_ . get ( ) ) <nl> + utility_client_ - > Stop ( ) ; <nl> + } <nl> + <nl> + void PdfToEmfConverterImpl : : Start ( <nl> + const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfRenderSettings & conversion_settings , <nl> + const StartCallback & start_callback ) { <nl> + DCHECK ( ! utility_client_ . get ( ) ) ; <nl> + utility_client_ = new PdfToEmfUtilityProcessHostClient ( <nl> + weak_ptr_factory_ . GetWeakPtr ( ) , conversion_settings ) ; <nl> + utility_client_ - > Start ( data , start_callback ) ; <nl> + } <nl> + <nl> + void PdfToEmfConverterImpl : : GetPage ( int page_number , <nl> + const GetPageCallback & get_page_callback ) { <nl> + utility_client_ - > GetPage ( page_number , get_page_callback ) ; <nl> + } <nl> + <nl> + void PdfToEmfConverterImpl : : RunCallback ( const base : : Closure & callback ) { <nl> + DCHECK_CURRENTLY_ON ( BrowserThread : : UI ) ; <nl> + callback . Run ( ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + PdfToEmfConverter : : ~ PdfToEmfConverter ( ) { <nl> + } <nl> + <nl> + / / static <nl> + scoped_ptr < PdfToEmfConverter > PdfToEmfConverter : : CreateDefault ( ) { <nl> + return scoped_ptr < PdfToEmfConverter > ( new PdfToEmfConverterImpl ( ) ) ; <nl> + } <nl> + <nl> + } / / namespace printing <nl> new file mode 100644 <nl> index 000000000000 . . 60fdbc4b7e4e <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / printing / pdf_to_emf_converter . h <nl> <nl> + / / Copyright 2014 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_ <nl> + # define CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_ <nl> + <nl> + # include " base / callback . h " <nl> + # include " base / memory / ref_counted_memory . h " <nl> + # include " base / memory / scoped_ptr . h " <nl> + <nl> + namespace base { <nl> + class FilePath ; <nl> + } <nl> + <nl> + namespace printing { <nl> + <nl> + class MetafilePlayer ; <nl> + class PdfRenderSettings ; <nl> + <nl> + class PdfToEmfConverter { <nl> + public : <nl> + typedef base : : Callback < void ( int page_count ) > StartCallback ; <nl> + typedef base : : Callback < void ( int page_number , <nl> + float scale_factor , <nl> + scoped_ptr < MetafilePlayer > emf ) > GetPageCallback ; <nl> + <nl> + virtual ~ PdfToEmfConverter ( ) ; <nl> + <nl> + static scoped_ptr < PdfToEmfConverter > CreateDefault ( ) ; <nl> + <nl> + / / Starts conversion of PDF provided as | data | . Calls | start_callback | <nl> + / / with positive | page_count | . | page_count | is 0 if initialization failed . <nl> + virtual void Start ( const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfRenderSettings & conversion_settings , <nl> + const StartCallback & start_callback ) = 0 ; <nl> + <nl> + / / Requests conversion of the page . | page_number | is 0 - base page number in <nl> + / / PDF provided in Start ( ) call . <nl> + / / Calls | get_page_callback | after conversion . | emf | of callback in not NULL <nl> + / / if conversion succeeded . <nl> + virtual void GetPage ( int page_number , <nl> + const GetPageCallback & get_page_callback ) = 0 ; <nl> + } ; <nl> + <nl> + } / / namespace printing <nl> + <nl> + # endif / / CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_ <nl> mmm a / chromium_src / chrome / browser / printing / print_job . cc <nl> ppp b / chromium_src / chrome / browser / printing / print_job . cc <nl> <nl> # include " printing / printed_document . h " <nl> # include " printing / printed_page . h " <nl> <nl> + # if defined ( OS_WIN ) <nl> + # include " chrome / browser / printing / pdf_to_emf_converter . h " <nl> + # include " printing / pdf_render_settings . h " <nl> + # endif <nl> + <nl> + <nl> using base : : TimeDelta ; <nl> <nl> namespace { <nl> void PrintJob : : OnNotifyPrintJobEvent ( const JobEventDetails & event_details ) { <nl> } <nl> } <nl> <nl> + # if defined ( OS_WIN ) <nl> + <nl> + class PrintJob : : PdfToEmfState { <nl> + public : <nl> + PdfToEmfState ( const gfx : : Size & page_size , const gfx : : Rect & content_area ) <nl> + : page_count_ ( 0 ) , <nl> + current_page_ ( 0 ) , <nl> + pages_in_progress_ ( 0 ) , <nl> + page_size_ ( page_size ) , <nl> + content_area_ ( content_area ) , <nl> + converter_ ( PdfToEmfConverter : : CreateDefault ( ) ) { } <nl> + <nl> + void Start ( const scoped_refptr < base : : RefCountedMemory > & data , <nl> + const PdfRenderSettings & conversion_settings , <nl> + const PdfToEmfConverter : : StartCallback & start_callback ) { <nl> + converter_ - > Start ( data , conversion_settings , start_callback ) ; <nl> + } <nl> + <nl> + void GetMorePages ( <nl> + const PdfToEmfConverter : : GetPageCallback & get_page_callback ) { <nl> + const int kMaxNumberOfTempFilesPerDocument = 3 ; <nl> + while ( pages_in_progress_ < kMaxNumberOfTempFilesPerDocument & & <nl> + current_page_ < page_count_ ) { <nl> + + + pages_in_progress_ ; <nl> + converter_ - > GetPage ( current_page_ + + , get_page_callback ) ; <nl> + } <nl> + } <nl> + <nl> + void OnPageProcessed ( <nl> + const PdfToEmfConverter : : GetPageCallback & get_page_callback ) { <nl> + - - pages_in_progress_ ; <nl> + GetMorePages ( get_page_callback ) ; <nl> + / / Release converter if we don ' t need this any more . <nl> + if ( ! pages_in_progress_ & & current_page_ > = page_count_ ) <nl> + converter_ . reset ( ) ; <nl> + } <nl> + <nl> + void set_page_count ( int page_count ) { page_count_ = page_count ; } <nl> + gfx : : Size page_size ( ) const { return page_size_ ; } <nl> + gfx : : Rect content_area ( ) const { return content_area_ ; } <nl> + <nl> + private : <nl> + int page_count_ ; <nl> + int current_page_ ; <nl> + int pages_in_progress_ ; <nl> + gfx : : Size page_size_ ; <nl> + gfx : : Rect content_area_ ; <nl> + scoped_ptr < PdfToEmfConverter > converter_ ; <nl> + } ; <nl> + <nl> + void PrintJob : : StartPdfToEmfConversion ( <nl> + const scoped_refptr < base : : RefCountedMemory > & bytes , <nl> + const gfx : : Size & page_size , <nl> + const gfx : : Rect & content_area ) { <nl> + DCHECK ( ! ptd_to_emf_state_ . get ( ) ) ; <nl> + ptd_to_emf_state_ . reset ( new PdfToEmfState ( page_size , content_area ) ) ; <nl> + const int kPrinterDpi = settings ( ) . dpi ( ) ; <nl> + ptd_to_emf_state_ - > Start ( <nl> + bytes , <nl> + printing : : PdfRenderSettings ( content_area , kPrinterDpi , true ) , <nl> + base : : Bind ( & PrintJob : : OnPdfToEmfStarted , this ) ) ; <nl> + } <nl> + <nl> + void PrintJob : : OnPdfToEmfStarted ( int page_count ) { <nl> + if ( page_count < = 0 ) { <nl> + ptd_to_emf_state_ . reset ( ) ; <nl> + Cancel ( ) ; <nl> + return ; <nl> + } <nl> + ptd_to_emf_state_ - > set_page_count ( page_count ) ; <nl> + ptd_to_emf_state_ - > GetMorePages ( <nl> + base : : Bind ( & PrintJob : : OnPdfToEmfPageConverted , this ) ) ; <nl> + } <nl> + <nl> + void PrintJob : : OnPdfToEmfPageConverted ( int page_number , <nl> + float scale_factor , <nl> + scoped_ptr < MetafilePlayer > emf ) { <nl> + DCHECK ( ptd_to_emf_state_ ) ; <nl> + if ( ! document_ . get ( ) | | ! emf ) { <nl> + ptd_to_emf_state_ . reset ( ) ; <nl> + Cancel ( ) ; <nl> + return ; <nl> + } <nl> + <nl> + / / Update the rendered document . It will send notifications to the listener . <nl> + document_ - > SetPage ( page_number , <nl> + emf . Pass ( ) , <nl> + scale_factor , <nl> + ptd_to_emf_state_ - > page_size ( ) , <nl> + ptd_to_emf_state_ - > content_area ( ) ) ; <nl> + <nl> + ptd_to_emf_state_ - > GetMorePages ( <nl> + base : : Bind ( & PrintJob : : OnPdfToEmfPageConverted , this ) ) ; <nl> + } <nl> + <nl> + # endif / / OS_WIN <nl> + <nl> void PrintJob : : OnDocumentDone ( ) { <nl> / / Be sure to live long enough . The instance could be destroyed by the <nl> / / JOB_DONE broadcast . <nl> mmm a / chromium_src / chrome / browser / printing / print_job . h <nl> ppp b / chromium_src / chrome / browser / printing / print_job . h <nl> class PrintJob : public PrintJobWorkerOwner , <nl> / / Access the current printed document . Warning : may be NULL . <nl> PrintedDocument * document ( ) const ; <nl> <nl> + # if defined ( OS_WIN ) <nl> + void StartPdfToEmfConversion ( <nl> + const scoped_refptr < base : : RefCountedMemory > & bytes , <nl> + const gfx : : Size & page_size , <nl> + const gfx : : Rect & content_area ) ; <nl> + <nl> + void OnPdfToEmfStarted ( int page_count ) ; <nl> + void OnPdfToEmfPageConverted ( int page_number , <nl> + float scale_factor , <nl> + scoped_ptr < MetafilePlayer > emf ) ; <nl> + <nl> + # endif / / OS_WIN <nl> + <nl> protected : <nl> virtual ~ PrintJob ( ) ; <nl> <nl> class PrintJob : public PrintJobWorkerOwner , <nl> / / the notified calls Cancel ( ) again . <nl> bool is_canceling_ ; <nl> <nl> + # if defined ( OS_WIN ) <nl> + class PdfToEmfState ; <nl> + scoped_ptr < PdfToEmfState > ptd_to_emf_state_ ; <nl> + # endif / / OS_WIN <nl> + <nl> / / Used at shutdown so that we can quit a nested message loop . <nl> base : : WeakPtrFactory < PrintJob > quit_factory_ ; <nl> <nl> mmm a / chromium_src / chrome / browser / printing / print_view_manager_base . cc <nl> ppp b / chromium_src / chrome / browser / printing / print_view_manager_base . cc <nl> void PrintViewManagerBase : : OnDidPrintPage ( <nl> params . data_size ) ; <nl> <nl> document - > DebugDumpData ( bytes . get ( ) , FILE_PATH_LITERAL ( " . pdf " ) ) ; <nl> + print_job_ - > StartPdfToEmfConversion ( <nl> + bytes , params . page_size , params . content_area ) ; <nl> } <nl> # endif / / ! OS_WIN <nl> } <nl> new file mode 100644 <nl> index 000000000000 . . c2992abcc11d <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . h " <nl> + <nl> + # include " build / build_config . h " <nl> + # include " chrome / browser / renderer_host / pepper / pepper_broker_message_filter . h " <nl> + # include " chrome / browser / renderer_host / pepper / pepper_flash_browser_host . h " <nl> + # include " chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . h " <nl> + # include " chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . h " <nl> + # include " content / public / browser / browser_ppapi_host . h " <nl> + # include " ppapi / host / message_filter_host . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / shared_impl / ppapi_permissions . h " <nl> + <nl> + using ppapi : : host : : MessageFilterHost ; <nl> + using ppapi : : host : : ResourceHost ; <nl> + using ppapi : : host : : ResourceMessageFilter ; <nl> + <nl> + namespace chrome { <nl> + <nl> + ChromeBrowserPepperHostFactory : : ChromeBrowserPepperHostFactory ( <nl> + content : : BrowserPpapiHost * host ) <nl> + : host_ ( host ) { } <nl> + <nl> + ChromeBrowserPepperHostFactory : : ~ ChromeBrowserPepperHostFactory ( ) { } <nl> + <nl> + scoped_ptr < ResourceHost > ChromeBrowserPepperHostFactory : : CreateResourceHost ( <nl> + ppapi : : host : : PpapiHost * host , <nl> + PP_Resource resource , <nl> + PP_Instance instance , <nl> + const IPC : : Message & message ) { <nl> + DCHECK ( host = = host_ - > GetPpapiHost ( ) ) ; <nl> + <nl> + / / Make sure the plugin is giving us a valid instance for this resource . <nl> + if ( ! host_ - > IsValidInstance ( instance ) ) <nl> + return scoped_ptr < ResourceHost > ( ) ; <nl> + <nl> + / / Private interfaces . <nl> + if ( host_ - > GetPpapiHost ( ) - > permissions ( ) . HasPermission ( <nl> + ppapi : : PERMISSION_PRIVATE ) ) { <nl> + switch ( message . type ( ) ) { <nl> + case PpapiHostMsg_Broker_Create : : ID : { <nl> + scoped_refptr < ResourceMessageFilter > broker_filter ( <nl> + new PepperBrokerMessageFilter ( instance , host_ ) ) ; <nl> + return scoped_ptr < ResourceHost > ( new MessageFilterHost ( <nl> + host_ - > GetPpapiHost ( ) , instance , resource , broker_filter ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Flash interfaces . <nl> + if ( host_ - > GetPpapiHost ( ) - > permissions ( ) . HasPermission ( <nl> + ppapi : : PERMISSION_FLASH ) ) { <nl> + switch ( message . type ( ) ) { <nl> + case PpapiHostMsg_Flash_Create : : ID : <nl> + return scoped_ptr < ResourceHost > ( <nl> + new PepperFlashBrowserHost ( host_ , instance , resource ) ) ; <nl> + case PpapiHostMsg_FlashClipboard_Create : : ID : { <nl> + scoped_refptr < ResourceMessageFilter > clipboard_filter ( <nl> + new PepperFlashClipboardMessageFilter ) ; <nl> + return scoped_ptr < ResourceHost > ( new MessageFilterHost ( <nl> + host_ - > GetPpapiHost ( ) , instance , resource , clipboard_filter ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Permissions for the following interfaces will be checked at the <nl> + / / time of the corresponding instance ' s methods calls ( because <nl> + / / permission check can be performed only on the UI <nl> + / / thread ) . Currently these interfaces are available only for <nl> + / / whitelisted apps which may not have access to the other private <nl> + / / interfaces . <nl> + if ( message . type ( ) = = PpapiHostMsg_IsolatedFileSystem_Create : : ID ) { <nl> + PepperIsolatedFileSystemMessageFilter * isolated_fs_filter = <nl> + PepperIsolatedFileSystemMessageFilter : : Create ( instance , host_ ) ; <nl> + if ( ! isolated_fs_filter ) <nl> + return scoped_ptr < ResourceHost > ( ) ; <nl> + return scoped_ptr < ResourceHost > ( <nl> + new MessageFilterHost ( host , instance , resource , isolated_fs_filter ) ) ; <nl> + } <nl> + <nl> + return scoped_ptr < ResourceHost > ( ) ; <nl> + } <nl> + <nl> + } / / namespace chrome <nl> new file mode 100644 <nl> index 000000000000 . . b817953b54dc <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_CHROME_BROWSER_PEPPER_HOST_FACTORY_H_ <nl> + # define CHROME_BROWSER_RENDERER_HOST_PEPPER_CHROME_BROWSER_PEPPER_HOST_FACTORY_H_ <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / host / host_factory . h " <nl> + <nl> + namespace content { <nl> + class BrowserPpapiHost ; <nl> + } / / namespace content <nl> + <nl> + namespace chrome { <nl> + <nl> + class ChromeBrowserPepperHostFactory : public ppapi : : host : : HostFactory { <nl> + public : <nl> + / / Non - owning pointer to the filter must outlive this class . <nl> + explicit ChromeBrowserPepperHostFactory ( content : : BrowserPpapiHost * host ) ; <nl> + ~ ChromeBrowserPepperHostFactory ( ) override ; <nl> + <nl> + scoped_ptr < ppapi : : host : : ResourceHost > CreateResourceHost ( <nl> + ppapi : : host : : PpapiHost * host , <nl> + PP_Resource resource , <nl> + PP_Instance instance , <nl> + const IPC : : Message & message ) override ; <nl> + <nl> + private : <nl> + / / Non - owning pointer . <nl> + content : : BrowserPpapiHost * host_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( ChromeBrowserPepperHostFactory ) ; <nl> + } ; <nl> + <nl> + } / / namespace chrome <nl> + <nl> + # endif / / CHROME_BROWSER_RENDERER_HOST_PEPPER_CHROME_BROWSER_PEPPER_HOST_FACTORY_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 224b55d4cac5 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_broker_message_filter . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / renderer_host / pepper / pepper_broker_message_filter . h " <nl> + <nl> + # include < string > <nl> + <nl> + # include " content / public / browser / browser_ppapi_host . h " <nl> + # include " content / public / browser / browser_thread . h " <nl> + # include " content / public / browser / render_process_host . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " url / gurl . h " <nl> + <nl> + using content : : BrowserPpapiHost ; <nl> + using content : : BrowserThread ; <nl> + using content : : RenderProcessHost ; <nl> + <nl> + namespace chrome { <nl> + <nl> + PepperBrokerMessageFilter : : PepperBrokerMessageFilter ( PP_Instance instance , <nl> + BrowserPpapiHost * host ) <nl> + : document_url_ ( host - > GetDocumentURLForInstance ( instance ) ) { <nl> + int unused ; <nl> + host - > GetRenderFrameIDsForInstance ( instance , & render_process_id_ , & unused ) ; <nl> + } <nl> + <nl> + PepperBrokerMessageFilter : : ~ PepperBrokerMessageFilter ( ) { } <nl> + <nl> + scoped_refptr < base : : TaskRunner > <nl> + PepperBrokerMessageFilter : : OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & message ) { <nl> + return BrowserThread : : GetMessageLoopProxyForThread ( BrowserThread : : UI ) ; <nl> + } <nl> + <nl> + int32_t PepperBrokerMessageFilter : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperBrokerMessageFilter , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL_0 ( PpapiHostMsg_Broker_IsAllowed , <nl> + OnIsAllowed ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperBrokerMessageFilter : : OnIsAllowed ( <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + return PP_OK ; <nl> + } <nl> + <nl> + } / / namespace chrome <nl> new file mode 100644 <nl> index 000000000000 . . 44627c6a3556 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_broker_message_filter . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_BROKER_MESSAGE_FILTER_H_ <nl> + # define CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_BROKER_MESSAGE_FILTER_H_ <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / c / pp_instance . h " <nl> + # include " ppapi / host / resource_message_filter . h " <nl> + # include " url / gurl . h " <nl> + <nl> + namespace content { <nl> + class BrowserPpapiHost ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace host { <nl> + struct HostMessageContext ; <nl> + } <nl> + } <nl> + <nl> + namespace chrome { <nl> + <nl> + / / This filter handles messages for the PepperBrokerHost on the UI thread . <nl> + class PepperBrokerMessageFilter : public ppapi : : host : : ResourceMessageFilter { <nl> + public : <nl> + PepperBrokerMessageFilter ( PP_Instance instance , <nl> + content : : BrowserPpapiHost * host ) ; <nl> + <nl> + private : <nl> + ~ PepperBrokerMessageFilter ( ) override ; <nl> + <nl> + / / ppapi : : host : : ResourceMessageFilter overrides . <nl> + scoped_refptr < base : : TaskRunner > OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & message ) override ; <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + int32_t OnIsAllowed ( ppapi : : host : : HostMessageContext * context ) ; <nl> + <nl> + int render_process_id_ ; <nl> + GURL document_url_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperBrokerMessageFilter ) ; <nl> + } ; <nl> + <nl> + } / / namespace chrome <nl> + <nl> + # endif / / CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_BROKER_MESSAGE_FILTER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 43179c68d485 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_browser_host . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / renderer_host / pepper / pepper_flash_browser_host . h " <nl> + <nl> + # include " base / time / time . h " <nl> + # include " content / public / browser / browser_context . h " <nl> + # include " content / public / browser / browser_ppapi_host . h " <nl> + # include " content / public / browser / browser_thread . h " <nl> + # include " content / public / browser / render_process_host . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / c / private / ppb_flash . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / proxy / resource_message_params . h " <nl> + # include " ppapi / shared_impl / time_conversion . h " <nl> + # include " url / gurl . h " <nl> + <nl> + # if defined ( OS_WIN ) <nl> + # include < windows . h > <nl> + # elif defined ( OS_MACOSX ) <nl> + # include < CoreServices / CoreServices . h > <nl> + # endif <nl> + <nl> + using content : : BrowserPpapiHost ; <nl> + using content : : BrowserThread ; <nl> + using content : : RenderProcessHost ; <nl> + <nl> + namespace chrome { <nl> + <nl> + PepperFlashBrowserHost : : PepperFlashBrowserHost ( BrowserPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) <nl> + : ResourceHost ( host - > GetPpapiHost ( ) , instance , resource ) , <nl> + host_ ( host ) , <nl> + weak_factory_ ( this ) { <nl> + int unused ; <nl> + host - > GetRenderFrameIDsForInstance ( instance , & render_process_id_ , & unused ) ; <nl> + } <nl> + <nl> + PepperFlashBrowserHost : : ~ PepperFlashBrowserHost ( ) { } <nl> + <nl> + int32_t PepperFlashBrowserHost : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashBrowserHost , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL_0 ( PpapiHostMsg_Flash_UpdateActivity , <nl> + OnUpdateActivity ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_GetLocalTimeZoneOffset , <nl> + OnGetLocalTimeZoneOffset ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL_0 ( <nl> + PpapiHostMsg_Flash_GetLocalDataRestrictions , OnGetLocalDataRestrictions ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashBrowserHost : : OnUpdateActivity ( <nl> + ppapi : : host : : HostMessageContext * host_context ) { <nl> + # if defined ( OS_WIN ) <nl> + / / Reading then writing back the same value to the screensaver timeout system <nl> + / / setting resets the countdown which prevents the screensaver from turning <nl> + / / on " for a while " . As long as the plugin pings us with this message faster <nl> + / / than the screensaver timeout , it won ' t go on . <nl> + int value = 0 ; <nl> + if ( SystemParametersInfo ( SPI_GETSCREENSAVETIMEOUT , 0 , & value , 0 ) ) <nl> + SystemParametersInfo ( SPI_SETSCREENSAVETIMEOUT , value , NULL , 0 ) ; <nl> + # elif defined ( OS_MACOSX ) <nl> + / / UpdateSystemActivity ( OverallAct ) ; <nl> + # else <nl> + / / TODO ( brettw ) implement this for other platforms . <nl> + # endif <nl> + return PP_OK ; <nl> + } <nl> + <nl> + int32_t PepperFlashBrowserHost : : OnGetLocalTimeZoneOffset ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const base : : Time & t ) { <nl> + / / The reason for this processing being in the browser process is that on <nl> + / / Linux , the localtime calls require filesystem access prohibited by the <nl> + / / sandbox . <nl> + host_context - > reply_msg = PpapiPluginMsg_Flash_GetLocalTimeZoneOffsetReply ( <nl> + ppapi : : PPGetLocalTimeZoneOffset ( t ) ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + int32_t PepperFlashBrowserHost : : OnGetLocalDataRestrictions ( <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + / / Getting the Flash LSO settings requires using the CookieSettings which <nl> + / / belong to the profile which lives on the UI thread . We lazily initialize <nl> + / / | cookie_settings_ | by grabbing the reference from the UI thread and then <nl> + / / call | GetLocalDataRestrictions | with it . <nl> + GURL document_url = host_ - > GetDocumentURLForInstance ( pp_instance ( ) ) ; <nl> + GURL plugin_url = host_ - > GetPluginURLForInstance ( pp_instance ( ) ) ; <nl> + GetLocalDataRestrictions ( context - > MakeReplyMessageContext ( ) , <nl> + document_url , <nl> + plugin_url ) ; <nl> + return PP_OK_COMPLETIONPENDING ; <nl> + } <nl> + <nl> + void PepperFlashBrowserHost : : GetLocalDataRestrictions ( <nl> + ppapi : : host : : ReplyMessageContext reply_context , <nl> + const GURL & document_url , <nl> + const GURL & plugin_url ) { <nl> + DCHECK ( BrowserThread : : CurrentlyOn ( BrowserThread : : IO ) ) ; <nl> + <nl> + PP_FlashLSORestrictions restrictions = PP_FLASHLSORESTRICTIONS_NONE ; <nl> + SendReply ( reply_context , <nl> + PpapiPluginMsg_Flash_GetLocalDataRestrictionsReply ( <nl> + static_cast < int32_t > ( restrictions ) ) ) ; <nl> + } <nl> + <nl> + } / / namespace chrome <nl> new file mode 100644 <nl> index 000000000000 . . 6fb4aced1819 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_browser_host . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_BROWSER_HOST_H_ <nl> + # define CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_BROWSER_HOST_H_ <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / memory / ref_counted . h " <nl> + # include " base / memory / weak_ptr . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + <nl> + namespace base { <nl> + class Time ; <nl> + } <nl> + <nl> + namespace content { <nl> + class BrowserPpapiHost ; <nl> + class ResourceContext ; <nl> + } <nl> + <nl> + class GURL ; <nl> + <nl> + namespace chrome { <nl> + <nl> + class PepperFlashBrowserHost : public ppapi : : host : : ResourceHost { <nl> + public : <nl> + PepperFlashBrowserHost ( content : : BrowserPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) ; <nl> + ~ PepperFlashBrowserHost ( ) override ; <nl> + <nl> + / / ppapi : : host : : ResourceHost override . <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + int32_t OnUpdateActivity ( ppapi : : host : : HostMessageContext * host_context ) ; <nl> + int32_t OnGetLocalTimeZoneOffset ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const base : : Time & t ) ; <nl> + int32_t OnGetLocalDataRestrictions ( ppapi : : host : : HostMessageContext * context ) ; <nl> + <nl> + void GetLocalDataRestrictions ( ppapi : : host : : ReplyMessageContext reply_context , <nl> + const GURL & document_url , <nl> + const GURL & plugin_url ) ; <nl> + <nl> + content : : BrowserPpapiHost * host_ ; <nl> + int render_process_id_ ; <nl> + / / For fetching the Flash LSO settings . <nl> + base : : WeakPtrFactory < PepperFlashBrowserHost > weak_factory_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashBrowserHost ) ; <nl> + } ; <nl> + <nl> + } / / namespace chrome <nl> + <nl> + # endif / / CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_BROWSER_HOST_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 4499b21aefe3 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . h " <nl> + <nl> + # include " base / pickle . h " <nl> + # include " base / strings / utf_string_conversions . h " <nl> + # include " content / public / browser / browser_thread . h " <nl> + # include " ipc / ipc_message . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / c / private / ppb_flash_clipboard . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / proxy / resource_message_params . h " <nl> + # include " ui / base / clipboard / scoped_clipboard_writer . h " <nl> + <nl> + using content : : BrowserThread ; <nl> + <nl> + namespace chrome { <nl> + <nl> + namespace { <nl> + <nl> + const size_t kMaxClipboardWriteSize = 1000000 ; <nl> + <nl> + ui : : ClipboardType ConvertClipboardType ( uint32_t type ) { <nl> + switch ( type ) { <nl> + case PP_FLASH_CLIPBOARD_TYPE_STANDARD : <nl> + return ui : : CLIPBOARD_TYPE_COPY_PASTE ; <nl> + case PP_FLASH_CLIPBOARD_TYPE_SELECTION : <nl> + return ui : : CLIPBOARD_TYPE_SELECTION ; <nl> + } <nl> + NOTREACHED ( ) ; <nl> + return ui : : CLIPBOARD_TYPE_COPY_PASTE ; <nl> + } <nl> + <nl> + / / Functions to pack / unpack custom data from a pickle . See the header file for <nl> + / / more detail on custom formats in Pepper . <nl> + / / TODO ( raymes ) : Currently pepper custom formats are stored in their own <nl> + / / native format type . However we should be able to store them in the same way <nl> + / / as " Web Custom " formats are . This would allow clipboard data to be shared <nl> + / / between pepper applications and web applications . However currently web apps <nl> + / / assume all data that is placed on the clipboard is UTF16 and pepper allows <nl> + / / arbitrary data so this change would require some reworking of the chrome <nl> + / / clipboard interface for custom data . <nl> + bool JumpToFormatInPickle ( const base : : string16 & format , PickleIterator * iter ) { <nl> + size_t size = 0 ; <nl> + if ( ! iter - > ReadSizeT ( & size ) ) <nl> + return false ; <nl> + for ( size_t i = 0 ; i < size ; + + i ) { <nl> + base : : string16 stored_format ; <nl> + if ( ! iter - > ReadString16 ( & stored_format ) ) <nl> + return false ; <nl> + if ( stored_format = = format ) <nl> + return true ; <nl> + int skip_length ; <nl> + if ( ! iter - > ReadLength ( & skip_length ) ) <nl> + return false ; <nl> + if ( ! iter - > SkipBytes ( skip_length ) ) <nl> + return false ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + bool IsFormatAvailableInPickle ( const base : : string16 & format , <nl> + const Pickle & pickle ) { <nl> + PickleIterator iter ( pickle ) ; <nl> + return JumpToFormatInPickle ( format , & iter ) ; <nl> + } <nl> + <nl> + std : : string ReadDataFromPickle ( const base : : string16 & format , <nl> + const Pickle & pickle ) { <nl> + std : : string result ; <nl> + PickleIterator iter ( pickle ) ; <nl> + if ( ! JumpToFormatInPickle ( format , & iter ) | | ! iter . ReadString ( & result ) ) <nl> + return std : : string ( ) ; <nl> + return result ; <nl> + } <nl> + <nl> + bool WriteDataToPickle ( const std : : map < base : : string16 , std : : string > & data , <nl> + Pickle * pickle ) { <nl> + pickle - > WriteSizeT ( data . size ( ) ) ; <nl> + for ( std : : map < base : : string16 , std : : string > : : const_iterator it = data . begin ( ) ; <nl> + it ! = data . end ( ) ; <nl> + + + it ) { <nl> + if ( ! pickle - > WriteString16 ( it - > first ) ) <nl> + return false ; <nl> + if ( ! pickle - > WriteString ( it - > second ) ) <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + PepperFlashClipboardMessageFilter : : PepperFlashClipboardMessageFilter ( ) { } <nl> + <nl> + PepperFlashClipboardMessageFilter : : ~ PepperFlashClipboardMessageFilter ( ) { } <nl> + <nl> + scoped_refptr < base : : TaskRunner > <nl> + PepperFlashClipboardMessageFilter : : OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & msg ) { <nl> + / / Clipboard writes should always occur on the UI thread due to the <nl> + / / restrictions of various platform APIs . In general , the clipboard is not <nl> + / / thread - safe , so all clipboard calls should be serviced from the UI thread . <nl> + if ( msg . type ( ) = = PpapiHostMsg_FlashClipboard_WriteData : : ID ) <nl> + return BrowserThread : : GetMessageLoopProxyForThread ( BrowserThread : : UI ) ; <nl> + <nl> + / / Windows needs clipboard reads to be serviced from the IO thread because <nl> + / / these are sync IPCs which can result in deadlocks with plugins if serviced <nl> + / / from the UI thread . Note that Windows clipboard calls ARE thread - safe so it <nl> + / / is ok for reads and writes to be serviced from different threads . <nl> + # if ! defined ( OS_WIN ) <nl> + return BrowserThread : : GetMessageLoopProxyForThread ( BrowserThread : : UI ) ; <nl> + # else <nl> + return BrowserThread : : GetMessageLoopProxyForThread ( BrowserThread : : IO ) ; <nl> + # endif <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashClipboardMessageFilter , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( <nl> + PpapiHostMsg_FlashClipboard_RegisterCustomFormat , <nl> + OnMsgRegisterCustomFormat ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( <nl> + PpapiHostMsg_FlashClipboard_IsFormatAvailable , OnMsgIsFormatAvailable ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_FlashClipboard_ReadData , <nl> + OnMsgReadData ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_FlashClipboard_WriteData , <nl> + OnMsgWriteData ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( <nl> + PpapiHostMsg_FlashClipboard_GetSequenceNumber , OnMsgGetSequenceNumber ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnMsgRegisterCustomFormat ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const std : : string & format_name ) { <nl> + uint32_t format = custom_formats_ . RegisterFormat ( format_name ) ; <nl> + if ( format = = PP_FLASH_CLIPBOARD_FORMAT_INVALID ) <nl> + return PP_ERROR_FAILED ; <nl> + host_context - > reply_msg = <nl> + PpapiPluginMsg_FlashClipboard_RegisterCustomFormatReply ( format ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnMsgIsFormatAvailable ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type , <nl> + uint32_t format ) { <nl> + if ( clipboard_type ! = PP_FLASH_CLIPBOARD_TYPE_STANDARD ) { <nl> + NOTIMPLEMENTED ( ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + ui : : Clipboard * clipboard = ui : : Clipboard : : GetForCurrentThread ( ) ; <nl> + ui : : ClipboardType type = ConvertClipboardType ( clipboard_type ) ; <nl> + bool available = false ; <nl> + switch ( format ) { <nl> + case PP_FLASH_CLIPBOARD_FORMAT_PLAINTEXT : { <nl> + bool plain = clipboard - > IsFormatAvailable ( <nl> + ui : : Clipboard : : GetPlainTextFormatType ( ) , type ) ; <nl> + bool plainw = clipboard - > IsFormatAvailable ( <nl> + ui : : Clipboard : : GetPlainTextWFormatType ( ) , type ) ; <nl> + available = plain | | plainw ; <nl> + break ; <nl> + } <nl> + case PP_FLASH_CLIPBOARD_FORMAT_HTML : <nl> + available = clipboard - > IsFormatAvailable ( <nl> + ui : : Clipboard : : GetHtmlFormatType ( ) , type ) ; <nl> + break ; <nl> + case PP_FLASH_CLIPBOARD_FORMAT_RTF : <nl> + available = <nl> + clipboard - > IsFormatAvailable ( ui : : Clipboard : : GetRtfFormatType ( ) , type ) ; <nl> + break ; <nl> + case PP_FLASH_CLIPBOARD_FORMAT_INVALID : <nl> + break ; <nl> + default : <nl> + if ( custom_formats_ . IsFormatRegistered ( format ) ) { <nl> + std : : string format_name = custom_formats_ . GetFormatName ( format ) ; <nl> + std : : string clipboard_data ; <nl> + clipboard - > ReadData ( ui : : Clipboard : : GetPepperCustomDataFormatType ( ) , <nl> + & clipboard_data ) ; <nl> + Pickle pickle ( clipboard_data . data ( ) , clipboard_data . size ( ) ) ; <nl> + available = <nl> + IsFormatAvailableInPickle ( base : : UTF8ToUTF16 ( format_name ) , pickle ) ; <nl> + } <nl> + break ; <nl> + } <nl> + <nl> + return available ? PP_OK : PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnMsgReadData ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type , <nl> + uint32_t format ) { <nl> + if ( clipboard_type ! = PP_FLASH_CLIPBOARD_TYPE_STANDARD ) { <nl> + NOTIMPLEMENTED ( ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + ui : : Clipboard * clipboard = ui : : Clipboard : : GetForCurrentThread ( ) ; <nl> + ui : : ClipboardType type = ConvertClipboardType ( clipboard_type ) ; <nl> + std : : string clipboard_string ; <nl> + int32_t result = PP_ERROR_FAILED ; <nl> + switch ( format ) { <nl> + case PP_FLASH_CLIPBOARD_FORMAT_PLAINTEXT : { <nl> + if ( clipboard - > IsFormatAvailable ( ui : : Clipboard : : GetPlainTextWFormatType ( ) , <nl> + type ) ) { <nl> + base : : string16 text ; <nl> + clipboard - > ReadText ( type , & text ) ; <nl> + if ( ! text . empty ( ) ) { <nl> + result = PP_OK ; <nl> + clipboard_string = base : : UTF16ToUTF8 ( text ) ; <nl> + break ; <nl> + } <nl> + } <nl> + / / If the PlainTextW format isn ' t available or is empty , take the <nl> + / / ASCII text format . <nl> + if ( clipboard - > IsFormatAvailable ( ui : : Clipboard : : GetPlainTextFormatType ( ) , <nl> + type ) ) { <nl> + result = PP_OK ; <nl> + clipboard - > ReadAsciiText ( type , & clipboard_string ) ; <nl> + } <nl> + break ; <nl> + } <nl> + case PP_FLASH_CLIPBOARD_FORMAT_HTML : { <nl> + if ( ! clipboard - > IsFormatAvailable ( ui : : Clipboard : : GetHtmlFormatType ( ) , <nl> + type ) ) { <nl> + break ; <nl> + } <nl> + <nl> + base : : string16 html ; <nl> + std : : string url ; <nl> + uint32 fragment_start ; <nl> + uint32 fragment_end ; <nl> + clipboard - > ReadHTML ( type , & html , & url , & fragment_start , & fragment_end ) ; <nl> + result = PP_OK ; <nl> + clipboard_string = base : : UTF16ToUTF8 ( <nl> + html . substr ( fragment_start , fragment_end - fragment_start ) ) ; <nl> + break ; <nl> + } <nl> + case PP_FLASH_CLIPBOARD_FORMAT_RTF : { <nl> + if ( ! clipboard - > IsFormatAvailable ( ui : : Clipboard : : GetRtfFormatType ( ) , <nl> + type ) ) { <nl> + break ; <nl> + } <nl> + result = PP_OK ; <nl> + clipboard - > ReadRTF ( type , & clipboard_string ) ; <nl> + break ; <nl> + } <nl> + case PP_FLASH_CLIPBOARD_FORMAT_INVALID : <nl> + break ; <nl> + default : { <nl> + if ( custom_formats_ . IsFormatRegistered ( format ) ) { <nl> + base : : string16 format_name = <nl> + base : : UTF8ToUTF16 ( custom_formats_ . GetFormatName ( format ) ) ; <nl> + std : : string clipboard_data ; <nl> + clipboard - > ReadData ( ui : : Clipboard : : GetPepperCustomDataFormatType ( ) , <nl> + & clipboard_data ) ; <nl> + Pickle pickle ( clipboard_data . data ( ) , clipboard_data . size ( ) ) ; <nl> + if ( IsFormatAvailableInPickle ( format_name , pickle ) ) { <nl> + result = PP_OK ; <nl> + clipboard_string = ReadDataFromPickle ( format_name , pickle ) ; <nl> + } <nl> + } <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( result = = PP_OK ) { <nl> + host_context - > reply_msg = <nl> + PpapiPluginMsg_FlashClipboard_ReadDataReply ( clipboard_string ) ; <nl> + } <nl> + return result ; <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnMsgWriteData ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type , <nl> + const std : : vector < uint32_t > & formats , <nl> + const std : : vector < std : : string > & data ) { <nl> + if ( clipboard_type ! = PP_FLASH_CLIPBOARD_TYPE_STANDARD ) { <nl> + NOTIMPLEMENTED ( ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + if ( formats . size ( ) ! = data . size ( ) ) <nl> + return PP_ERROR_FAILED ; <nl> + <nl> + ui : : Clipboard * clipboard = ui : : Clipboard : : GetForCurrentThread ( ) ; <nl> + ui : : ClipboardType type = ConvertClipboardType ( clipboard_type ) ; <nl> + / / If no formats are passed in clear the clipboard . <nl> + if ( formats . size ( ) = = 0 ) { <nl> + clipboard - > Clear ( type ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + ui : : ScopedClipboardWriter scw ( type ) ; <nl> + std : : map < base : : string16 , std : : string > custom_data_map ; <nl> + int32_t res = PP_OK ; <nl> + for ( uint32_t i = 0 ; i < formats . size ( ) ; + + i ) { <nl> + if ( data [ i ] . length ( ) > kMaxClipboardWriteSize ) { <nl> + res = PP_ERROR_NOSPACE ; <nl> + break ; <nl> + } <nl> + <nl> + switch ( formats [ i ] ) { <nl> + case PP_FLASH_CLIPBOARD_FORMAT_PLAINTEXT : <nl> + scw . WriteText ( base : : UTF8ToUTF16 ( data [ i ] ) ) ; <nl> + break ; <nl> + case PP_FLASH_CLIPBOARD_FORMAT_HTML : <nl> + scw . WriteHTML ( base : : UTF8ToUTF16 ( data [ i ] ) , std : : string ( ) ) ; <nl> + break ; <nl> + case PP_FLASH_CLIPBOARD_FORMAT_RTF : <nl> + scw . WriteRTF ( data [ i ] ) ; <nl> + break ; <nl> + case PP_FLASH_CLIPBOARD_FORMAT_INVALID : <nl> + res = PP_ERROR_BADARGUMENT ; <nl> + break ; <nl> + default : <nl> + if ( custom_formats_ . IsFormatRegistered ( formats [ i ] ) ) { <nl> + std : : string format_name = custom_formats_ . GetFormatName ( formats [ i ] ) ; <nl> + custom_data_map [ base : : UTF8ToUTF16 ( format_name ) ] = data [ i ] ; <nl> + } else { <nl> + / / Invalid format . <nl> + res = PP_ERROR_BADARGUMENT ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + if ( res ! = PP_OK ) <nl> + break ; <nl> + } <nl> + <nl> + if ( custom_data_map . size ( ) > 0 ) { <nl> + Pickle pickle ; <nl> + if ( WriteDataToPickle ( custom_data_map , & pickle ) ) { <nl> + scw . WritePickledData ( pickle , <nl> + ui : : Clipboard : : GetPepperCustomDataFormatType ( ) ) ; <nl> + } else { <nl> + res = PP_ERROR_BADARGUMENT ; <nl> + } <nl> + } <nl> + <nl> + if ( res ! = PP_OK ) { <nl> + / / Need to clear the objects so nothing is written . <nl> + scw . Reset ( ) ; <nl> + } <nl> + <nl> + return res ; <nl> + } <nl> + <nl> + int32_t PepperFlashClipboardMessageFilter : : OnMsgGetSequenceNumber ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type ) { <nl> + if ( clipboard_type ! = PP_FLASH_CLIPBOARD_TYPE_STANDARD ) { <nl> + NOTIMPLEMENTED ( ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + ui : : Clipboard * clipboard = ui : : Clipboard : : GetForCurrentThread ( ) ; <nl> + ui : : ClipboardType type = ConvertClipboardType ( clipboard_type ) ; <nl> + int64_t sequence_number = clipboard - > GetSequenceNumber ( type ) ; <nl> + host_context - > reply_msg = <nl> + PpapiPluginMsg_FlashClipboard_GetSequenceNumberReply ( sequence_number ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + } / / namespace chrome <nl> new file mode 100644 <nl> index 000000000000 . . ff07eb73750c <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_CLIPBOARD_MESSAGE_FILTER_H_ <nl> + # define CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_CLIPBOARD_MESSAGE_FILTER_H_ <nl> + <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / host / resource_message_filter . h " <nl> + # include " ppapi / shared_impl / flash_clipboard_format_registry . h " <nl> + <nl> + namespace ppapi { <nl> + namespace host { <nl> + struct HostMessageContext ; <nl> + } <nl> + } <nl> + <nl> + namespace ui { <nl> + class ScopedClipboardWriter ; <nl> + } <nl> + <nl> + namespace chrome { <nl> + <nl> + / / Resource message filter for accessing the clipboard in Pepper . Pepper <nl> + / / supports reading / writing custom formats from the clipboard . Currently , all <nl> + / / custom formats that are read / written from the clipboard through pepper are <nl> + / / stored in a single real clipboard format ( in the same way the " web custom " <nl> + / / clipboard formats are ) . This is done so that we don ' t have to have use real <nl> + / / clipboard types for each custom clipboard format which may be a limited <nl> + / / resource on a particular platform . <nl> + class PepperFlashClipboardMessageFilter <nl> + : public ppapi : : host : : ResourceMessageFilter { <nl> + public : <nl> + PepperFlashClipboardMessageFilter ( ) ; <nl> + <nl> + protected : <nl> + / / ppapi : : host : : ResourceMessageFilter overrides . <nl> + scoped_refptr < base : : TaskRunner > OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & msg ) override ; <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + ~ PepperFlashClipboardMessageFilter ( ) override ; <nl> + <nl> + int32_t OnMsgRegisterCustomFormat ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const std : : string & format_name ) ; <nl> + int32_t OnMsgIsFormatAvailable ( ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type , <nl> + uint32_t format ) ; <nl> + int32_t OnMsgReadData ( ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipoard_type , <nl> + uint32_t format ) ; <nl> + int32_t OnMsgWriteData ( ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type , <nl> + const std : : vector < uint32_t > & formats , <nl> + const std : : vector < std : : string > & data ) ; <nl> + int32_t OnMsgGetSequenceNumber ( ppapi : : host : : HostMessageContext * host_context , <nl> + uint32_t clipboard_type ) ; <nl> + <nl> + int32_t WriteClipboardDataItem ( uint32_t format , <nl> + const std : : string & data , <nl> + ui : : ScopedClipboardWriter * scw ) ; <nl> + <nl> + ppapi : : FlashClipboardFormatRegistry custom_formats_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashClipboardMessageFilter ) ; <nl> + } ; <nl> + <nl> + } / / namespace chrome <nl> + <nl> + # endif / / CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_CLIPBOARD_MESSAGE_FILTER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 10c07906af9b <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . cc <nl> <nl> + / / Copyright 2013 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . h " <nl> + <nl> + # include " content / public / browser / browser_ppapi_host . h " <nl> + # include " content / public / browser / browser_thread . h " <nl> + # include " content / public / browser / child_process_security_policy . h " <nl> + # include " content / public / browser / render_view_host . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / shared_impl / file_system_util . h " <nl> + # include " storage / browser / fileapi / isolated_context . h " <nl> + <nl> + namespace chrome { <nl> + <nl> + / / static <nl> + PepperIsolatedFileSystemMessageFilter * <nl> + PepperIsolatedFileSystemMessageFilter : : Create ( PP_Instance instance , <nl> + content : : BrowserPpapiHost * host ) { <nl> + int render_process_id ; <nl> + int unused_render_frame_id ; <nl> + if ( ! host - > GetRenderFrameIDsForInstance ( <nl> + instance , & render_process_id , & unused_render_frame_id ) ) { <nl> + return NULL ; <nl> + } <nl> + return new PepperIsolatedFileSystemMessageFilter ( <nl> + render_process_id , <nl> + host - > GetProfileDataDirectory ( ) , <nl> + host - > GetDocumentURLForInstance ( instance ) , <nl> + host - > GetPpapiHost ( ) ) ; <nl> + } <nl> + <nl> + PepperIsolatedFileSystemMessageFilter : : PepperIsolatedFileSystemMessageFilter ( <nl> + int render_process_id , <nl> + const base : : FilePath & profile_directory , <nl> + const GURL & document_url , <nl> + ppapi : : host : : PpapiHost * ppapi_host ) <nl> + : render_process_id_ ( render_process_id ) , <nl> + profile_directory_ ( profile_directory ) , <nl> + document_url_ ( document_url ) , <nl> + ppapi_host_ ( ppapi_host ) { <nl> + } <nl> + <nl> + PepperIsolatedFileSystemMessageFilter : : <nl> + ~ PepperIsolatedFileSystemMessageFilter ( ) { } <nl> + <nl> + scoped_refptr < base : : TaskRunner > <nl> + PepperIsolatedFileSystemMessageFilter : : OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & msg ) { <nl> + / / In order to reach ExtensionSystem , we need to get ProfileManager first . <nl> + / / ProfileManager lives in UI thread , so we need to do this in UI thread . <nl> + return content : : BrowserThread : : GetMessageLoopProxyForThread ( <nl> + content : : BrowserThread : : UI ) ; <nl> + } <nl> + <nl> + int32_t PepperIsolatedFileSystemMessageFilter : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperIsolatedFileSystemMessageFilter , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( <nl> + PpapiHostMsg_IsolatedFileSystem_BrowserOpen , <nl> + OnOpenFileSystem ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperIsolatedFileSystemMessageFilter : : OnOpenFileSystem ( <nl> + ppapi : : host : : HostMessageContext * context , <nl> + PP_IsolatedFileSystemType_Private type ) { <nl> + switch ( type ) { <nl> + case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_INVALID : <nl> + case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_CRX : <nl> + break ; <nl> + case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_PLUGINPRIVATE : <nl> + return OpenPluginPrivateFileSystem ( context ) ; <nl> + } <nl> + NOTREACHED ( ) ; <nl> + context - > reply_msg = <nl> + PpapiPluginMsg_IsolatedFileSystem_BrowserOpenReply ( std : : string ( ) ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperIsolatedFileSystemMessageFilter : : OpenPluginPrivateFileSystem ( <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + DCHECK ( ppapi_host_ ) ; <nl> + / / Only plugins with private permission can open the filesystem . <nl> + if ( ! ppapi_host_ - > permissions ( ) . HasPermission ( ppapi : : PERMISSION_PRIVATE ) ) <nl> + return PP_ERROR_NOACCESS ; <nl> + <nl> + const std : : string & root_name = ppapi : : IsolatedFileSystemTypeToRootName ( <nl> + PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_PLUGINPRIVATE ) ; <nl> + const std : : string & fsid = <nl> + storage : : IsolatedContext : : GetInstance ( ) - > RegisterFileSystemForVirtualPath ( <nl> + storage : : kFileSystemTypePluginPrivate , root_name , base : : FilePath ( ) ) ; <nl> + <nl> + / / Grant full access of isolated filesystem to renderer process . <nl> + content : : ChildProcessSecurityPolicy * policy = <nl> + content : : ChildProcessSecurityPolicy : : GetInstance ( ) ; <nl> + policy - > GrantCreateReadWriteFileSystem ( render_process_id_ , fsid ) ; <nl> + <nl> + context - > reply_msg = PpapiPluginMsg_IsolatedFileSystem_BrowserOpenReply ( fsid ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + } / / namespace chrome <nl> new file mode 100644 <nl> index 000000000000 . . 6a24feadd150 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . h <nl> <nl> + / / Copyright 2013 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H_ <nl> + # define CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H_ <nl> + <nl> + # include < set > <nl> + # include < string > <nl> + <nl> + # include " base / files / file_path . h " <nl> + # include " ppapi / c / pp_instance . h " <nl> + # include " ppapi / c / pp_resource . h " <nl> + # include " ppapi / c / private / ppb_isolated_file_system_private . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + # include " ppapi / host / resource_message_filter . h " <nl> + # include " url / gurl . h " <nl> + <nl> + class Profile ; <nl> + <nl> + namespace content { <nl> + class BrowserPpapiHost ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace host { <nl> + struct HostMessageContext ; <nl> + } / / namespace host <nl> + } / / namespace ppapi <nl> + <nl> + namespace chrome { <nl> + <nl> + class PepperIsolatedFileSystemMessageFilter <nl> + : public ppapi : : host : : ResourceMessageFilter { <nl> + public : <nl> + static PepperIsolatedFileSystemMessageFilter * Create ( <nl> + PP_Instance instance , <nl> + content : : BrowserPpapiHost * host ) ; <nl> + <nl> + / / ppapi : : host : : ResourceMessageFilter implementation . <nl> + scoped_refptr < base : : TaskRunner > OverrideTaskRunnerForMessage ( <nl> + const IPC : : Message & msg ) override ; <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + PepperIsolatedFileSystemMessageFilter ( int render_process_id , <nl> + const base : : FilePath & profile_directory , <nl> + const GURL & document_url , <nl> + ppapi : : host : : PpapiHost * ppapi_host_ ) ; <nl> + <nl> + ~ PepperIsolatedFileSystemMessageFilter ( ) override ; <nl> + <nl> + / / Returns filesystem id of isolated filesystem if valid , or empty string <nl> + / / otherwise . This must run on the UI thread because ProfileManager only <nl> + / / allows access on that thread . <nl> + <nl> + int32_t OnOpenFileSystem ( ppapi : : host : : HostMessageContext * context , <nl> + PP_IsolatedFileSystemType_Private type ) ; <nl> + int32_t OpenPluginPrivateFileSystem ( ppapi : : host : : HostMessageContext * context ) ; <nl> + <nl> + const int render_process_id_ ; <nl> + / / Keep a copy from original thread . <nl> + const base : : FilePath profile_directory_ ; <nl> + const GURL document_url_ ; <nl> + <nl> + / / Not owned by this object . <nl> + ppapi : : host : : PpapiHost * ppapi_host_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperIsolatedFileSystemMessageFilter ) ; <nl> + } ; <nl> + <nl> + } / / namespace chrome <nl> + <nl> + # endif / / CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_ISOLATED_FILE_SYSTEM_MESSAGE_FILTER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 1de0756c0d58 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / common / chrome_utility_messages . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + / / Multiply - included message file , so no include guard . <nl> + <nl> + # if defined ( OS_WIN ) <nl> + # include < Windows . h > <nl> + # endif / / defined ( OS_WIN ) <nl> + <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include " base / files / file_path . h " <nl> + # include " base / strings / string16 . h " <nl> + # include " base / tuple . h " <nl> + # include " base / values . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + # include " ipc / ipc_platform_file . h " <nl> + # include " third_party / skia / include / core / SkBitmap . h " <nl> + # include " ui / gfx / ipc / gfx_param_traits . h " <nl> + <nl> + / / Singly - included section for typedefs . <nl> + # ifndef CHROME_COMMON_CHROME_UTILITY_MESSAGES_H_ <nl> + # define CHROME_COMMON_CHROME_UTILITY_MESSAGES_H_ <nl> + <nl> + # if defined ( OS_WIN ) <nl> + / / A vector of filters , each being a Tuple containing a display string ( i . e . <nl> + / / " Text Files " ) and a filter pattern ( i . e . " * . txt " ) . <nl> + typedef std : : vector < Tuple < base : : string16 , base : : string16 > > <nl> + GetOpenFileNameFilter ; <nl> + # endif / / OS_WIN <nl> + <nl> + # endif / / CHROME_COMMON_CHROME_UTILITY_MESSAGES_H_ <nl> + <nl> + # define IPC_MESSAGE_START ChromeUtilityMsgStart <nl> + <nl> + <nl> + # if defined ( OS_WIN ) <nl> + IPC_STRUCT_BEGIN ( ChromeUtilityMsg_GetSaveFileName_Params ) <nl> + IPC_STRUCT_MEMBER ( HWND , owner ) <nl> + IPC_STRUCT_MEMBER ( DWORD , flags ) <nl> + IPC_STRUCT_MEMBER ( GetOpenFileNameFilter , filters ) <nl> + IPC_STRUCT_MEMBER ( int , one_based_filter_index ) <nl> + IPC_STRUCT_MEMBER ( base : : FilePath , suggested_filename ) <nl> + IPC_STRUCT_MEMBER ( base : : FilePath , initial_directory ) <nl> + IPC_STRUCT_MEMBER ( base : : string16 , default_extension ) <nl> + IPC_STRUCT_END ( ) <nl> + # endif / / OS_WIN <nl> + <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + / / Utility process messages : <nl> + / / These are messages from the browser to the utility process . <nl> + <nl> + / / Tell the utility process to parse a JSON string into a Value object . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityMsg_ParseJSON , <nl> + std : : string / * JSON to parse * / ) <nl> + <nl> + / / Tell the utility process to decode the given image data . <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityMsg_DecodeImage , <nl> + std : : vector < unsigned char > / * encoded image contents * / , <nl> + bool / * shrink image if needed for IPC msg limit * / ) <nl> + <nl> + / / Tell the utility process to decode the given JPEG image data with a robust <nl> + / / libjpeg codec . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityMsg_RobustJPEGDecodeImage , <nl> + std : : vector < unsigned char > ) / / encoded image contents <nl> + <nl> + / / Tell the utility process to patch the given | input_file | using | patch_file | <nl> + / / and place the output in | output_file | . The patch should use the bsdiff <nl> + / / algorithm ( Courgette ' s version ) . <nl> + IPC_MESSAGE_CONTROL3 ( ChromeUtilityMsg_PatchFileBsdiff , <nl> + base : : FilePath / * input_file * / , <nl> + base : : FilePath / * patch_file * / , <nl> + base : : FilePath / * output_file * / ) <nl> + <nl> + / / Tell the utility process to patch the given | input_file | using | patch_file | <nl> + / / and place the output in | output_file | . The patch should use the Courgette <nl> + / / algorithm . <nl> + IPC_MESSAGE_CONTROL3 ( ChromeUtilityMsg_PatchFileCourgette , <nl> + base : : FilePath / * input_file * / , <nl> + base : : FilePath / * patch_file * / , <nl> + base : : FilePath / * output_file * / ) <nl> + <nl> + <nl> + / / Requests the utility process to respond with a <nl> + / / ChromeUtilityHostMsg_ProcessStarted message once it has started . This may <nl> + / / be used if the host process needs a handle to the running utility process . <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityMsg_StartupPing ) <nl> + <nl> + <nl> + # if defined ( OS_WIN ) <nl> + / / Invokes ui : : base : : win : : OpenFileViaShell from the utility process . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityMsg_OpenFileViaShell , <nl> + base : : FilePath / * full_path * / ) <nl> + <nl> + / / Invokes ui : : base : : win : : OpenFolderViaShell from the utility process . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityMsg_OpenFolderViaShell , <nl> + base : : FilePath / * full_path * / ) <nl> + <nl> + / / Instructs the utility process to invoke GetOpenFileName . | owner | is the <nl> + / / parent of the modal dialog , | flags | are OFN_ * flags . | filter | constrains the <nl> + / / user ' s file choices . | initial_directory | and | filename | select the directory <nl> + / / to be displayed and the file to be initially selected . <nl> + / / <nl> + / / Either ChromeUtilityHostMsg_GetOpenFileName_Failed or <nl> + / / ChromeUtilityHostMsg_GetOpenFileName_Result will be returned when the <nl> + / / operation completes whether due to error or user action . <nl> + IPC_MESSAGE_CONTROL5 ( ChromeUtilityMsg_GetOpenFileName , <nl> + HWND / * owner * / , <nl> + DWORD / * flags * / , <nl> + GetOpenFileNameFilter / * filter * / , <nl> + base : : FilePath / * initial_directory * / , <nl> + base : : FilePath / * filename * / ) <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityMsg_GetSaveFileName , <nl> + ChromeUtilityMsg_GetSaveFileName_Params / * params * / ) <nl> + # endif / / defined ( OS_WIN ) <nl> + <nl> + <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + / / Utility process host messages : <nl> + / / These are messages from the utility process to the browser . <nl> + <nl> + / / Reply when the utility process successfully parsed a JSON string . <nl> + / / <nl> + / / WARNING : The result can be of any Value subclass type , but we can ' t easily <nl> + / / pass indeterminate value types by const object reference with our IPC macros , <nl> + / / so we put the result Value into a ListValue . Handlers should examine the <nl> + / / first ( and only ) element of the ListValue for the actual result . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_ParseJSON_Succeeded , <nl> + base : : ListValue ) <nl> + <nl> + / / Reply when the utility process failed in parsing a JSON string . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_ParseJSON_Failed , <nl> + std : : string / * error message , if any * / ) <nl> + <nl> + / / Reply when the utility process has failed while unpacking and parsing a <nl> + / / web resource . | error_message | is a user - readable explanation of what <nl> + / / went wrong . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_UnpackWebResource_Failed , <nl> + std : : string / * error_message , if any * / ) <nl> + <nl> + / / Reply when the utility process has succeeded in decoding the image . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_DecodeImage_Succeeded , <nl> + SkBitmap ) / / decoded image <nl> + <nl> + / / Reply when an error occurred decoding the image . <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityHostMsg_DecodeImage_Failed ) <nl> + <nl> + / / Reply when a file has been patched . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_PatchFile_Finished , int / * result * / ) <nl> + <nl> + <nl> + / / Reply when the utility process has started . <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityHostMsg_ProcessStarted ) <nl> + <nl> + <nl> + # if defined ( OS_WIN ) <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityHostMsg_GetOpenFileName_Failed ) <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityHostMsg_GetOpenFileName_Result , <nl> + base : : FilePath / * directory * / , <nl> + std : : vector < base : : FilePath > / * filenames * / ) <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityHostMsg_GetSaveFileName_Failed ) <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityHostMsg_GetSaveFileName_Result , <nl> + base : : FilePath / * path * / , <nl> + int / * one_based_filter_index * / ) <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_BuildDirectWriteFontCache , <nl> + base : : FilePath / * cache file path * / ) <nl> + # endif / / defined ( OS_WIN ) <nl> mmm a / chromium_src / chrome / common / print_messages . h <nl> ppp b / chromium_src / chrome / common / print_messages . h <nl> <nl> # include " ui / gfx / native_widget_types . h " <nl> # include " ui / gfx / geometry / rect . h " <nl> <nl> + # if defined ( OS_WIN ) <nl> + # include " ipc / ipc_platform_file . h " <nl> + # include " printing / backend / print_backend . h " <nl> + # include " printing / page_range . h " <nl> + # include " printing / pdf_render_settings . h " <nl> + # endif <nl> + <nl> # ifndef CHROME_COMMON_PRINT_MESSAGES_H_ <nl> # define CHROME_COMMON_PRINT_MESSAGES_H_ <nl> <nl> IPC_MESSAGE_ROUTED0 ( PrintHostMsg_ShowInvalidPrinterSettingsError ) <nl> / / Tell the browser printing failed . <nl> IPC_MESSAGE_ROUTED1 ( PrintHostMsg_PrintingFailed , <nl> int / * document cookie * / ) <nl> + <nl> + <nl> + # if defined ( OS_WIN ) <nl> + / / Tell the utility process to start rendering the given PDF into a metafile . <nl> + / / Utility process would be alive until <nl> + / / ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop message . <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityMsg_RenderPDFPagesToMetafiles , <nl> + IPC : : PlatformFileForTransit , / * input_file * / <nl> + printing : : PdfRenderSettings / * settings * / ) <nl> + <nl> + / / Requests conversion of the next page . <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage , <nl> + int / * page_number * / , <nl> + IPC : : PlatformFileForTransit / * output_file * / ) <nl> + <nl> + / / Requests utility process to stop conversion and exit . <nl> + IPC_MESSAGE_CONTROL0 ( ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop ) <nl> + <nl> + / / Reply when the utility process loaded PDF . | page_count | is 0 , if loading <nl> + / / failed . <nl> + IPC_MESSAGE_CONTROL1 ( ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount , <nl> + int / * page_count * / ) <nl> + <nl> + / / Reply when the utility process rendered the PDF page . <nl> + IPC_MESSAGE_CONTROL2 ( ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone , <nl> + bool / * success * / , <nl> + float / * scale_factor * / ) <nl> + # endif <nl> new file mode 100644 <nl> index 000000000000 . . dd83b8191c06 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / chrome_renderer_pepper_host_factory . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / chrome_renderer_pepper_host_factory . h " <nl> + <nl> + # include " base / logging . h " <nl> + # include " chrome / renderer / pepper / pepper_flash_font_file_host . h " <nl> + # include " chrome / renderer / pepper / pepper_flash_fullscreen_host . h " <nl> + # include " chrome / renderer / pepper / pepper_flash_menu_host . h " <nl> + # include " chrome / renderer / pepper / pepper_flash_renderer_host . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + # include " ppapi / proxy / ppapi_message_utils . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / shared_impl / ppapi_permissions . h " <nl> + <nl> + using ppapi : : host : : ResourceHost ; <nl> + <nl> + ChromeRendererPepperHostFactory : : ChromeRendererPepperHostFactory ( <nl> + content : : RendererPpapiHost * host ) <nl> + : host_ ( host ) { } <nl> + <nl> + ChromeRendererPepperHostFactory : : ~ ChromeRendererPepperHostFactory ( ) { } <nl> + <nl> + scoped_ptr < ResourceHost > ChromeRendererPepperHostFactory : : CreateResourceHost ( <nl> + ppapi : : host : : PpapiHost * host , <nl> + PP_Resource resource , <nl> + PP_Instance instance , <nl> + const IPC : : Message & message ) { <nl> + DCHECK_EQ ( host_ - > GetPpapiHost ( ) , host ) ; <nl> + <nl> + / / Make sure the plugin is giving us a valid instance for this resource . <nl> + if ( ! host_ - > IsValidInstance ( instance ) ) <nl> + return scoped_ptr < ResourceHost > ( ) ; <nl> + <nl> + if ( host_ - > GetPpapiHost ( ) - > permissions ( ) . HasPermission ( <nl> + ppapi : : PERMISSION_FLASH ) ) { <nl> + switch ( message . type ( ) ) { <nl> + case PpapiHostMsg_Flash_Create : : ID : { <nl> + return scoped_ptr < ResourceHost > ( <nl> + new PepperFlashRendererHost ( host_ , instance , resource ) ) ; <nl> + } <nl> + case PpapiHostMsg_FlashFullscreen_Create : : ID : { <nl> + return scoped_ptr < ResourceHost > ( <nl> + new PepperFlashFullscreenHost ( host_ , instance , resource ) ) ; <nl> + } <nl> + case PpapiHostMsg_FlashMenu_Create : : ID : { <nl> + ppapi : : proxy : : SerializedFlashMenu serialized_menu ; <nl> + if ( ppapi : : UnpackMessage < PpapiHostMsg_FlashMenu_Create > ( <nl> + message , & serialized_menu ) ) { <nl> + return scoped_ptr < ResourceHost > ( new PepperFlashMenuHost ( <nl> + host_ , instance , resource , serialized_menu ) ) ; <nl> + } <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / TODO ( raymes ) : PDF also needs access to the FlashFontFileHost currently . <nl> + / / We should either rename PPB_FlashFont_File to PPB_FontFile_Private or get <nl> + / / rid of its use in PDF if possible . <nl> + if ( host_ - > GetPpapiHost ( ) - > permissions ( ) . HasPermission ( <nl> + ppapi : : PERMISSION_FLASH ) | | <nl> + host_ - > GetPpapiHost ( ) - > permissions ( ) . HasPermission ( <nl> + ppapi : : PERMISSION_PRIVATE ) ) { <nl> + switch ( message . type ( ) ) { <nl> + case PpapiHostMsg_FlashFontFile_Create : : ID : { <nl> + ppapi : : proxy : : SerializedFontDescription description ; <nl> + PP_PrivateFontCharset charset ; <nl> + if ( ppapi : : UnpackMessage < PpapiHostMsg_FlashFontFile_Create > ( <nl> + message , & description , & charset ) ) { <nl> + return scoped_ptr < ResourceHost > ( new PepperFlashFontFileHost ( <nl> + host_ , instance , resource , description , charset ) ) ; <nl> + } <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + return scoped_ptr < ResourceHost > ( ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 13ab2853a356 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / chrome_renderer_pepper_host_factory . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_CHROME_RENDERER_PEPPER_HOST_FACTORY_H_ <nl> + # define CHROME_RENDERER_PEPPER_CHROME_RENDERER_PEPPER_HOST_FACTORY_H_ <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / host / host_factory . h " <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + } <nl> + <nl> + class ChromeRendererPepperHostFactory : public ppapi : : host : : HostFactory { <nl> + public : <nl> + explicit ChromeRendererPepperHostFactory ( content : : RendererPpapiHost * host ) ; <nl> + ~ ChromeRendererPepperHostFactory ( ) override ; <nl> + <nl> + / / HostFactory . <nl> + scoped_ptr < ppapi : : host : : ResourceHost > CreateResourceHost ( <nl> + ppapi : : host : : PpapiHost * host , <nl> + PP_Resource resource , <nl> + PP_Instance instance , <nl> + const IPC : : Message & message ) override ; <nl> + <nl> + private : <nl> + / / Not owned by this object . <nl> + content : : RendererPpapiHost * host_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( ChromeRendererPepperHostFactory ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_CHROME_RENDERER_PEPPER_HOST_FACTORY_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 305b6ec56c07 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_font_file_host . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_flash_font_file_host . h " <nl> + <nl> + # include " build / build_config . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / proxy / serialized_structs . h " <nl> + <nl> + # if defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + # include " content / public / common / child_process_sandbox_support_linux . h " <nl> + # endif <nl> + <nl> + PepperFlashFontFileHost : : PepperFlashFontFileHost ( <nl> + content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource , <nl> + const ppapi : : proxy : : SerializedFontDescription & description , <nl> + PP_PrivateFontCharset charset ) <nl> + : ResourceHost ( host - > GetPpapiHost ( ) , instance , resource ) { <nl> + # if defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + fd_ . reset ( content : : MatchFontWithFallback ( <nl> + description . face . c_str ( ) , <nl> + description . weight > = PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD , <nl> + description . italic , <nl> + charset , <nl> + PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT ) ) ; <nl> + # endif / / defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + } <nl> + <nl> + PepperFlashFontFileHost : : ~ PepperFlashFontFileHost ( ) { } <nl> + <nl> + int32_t PepperFlashFontFileHost : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashFontFileHost , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_FlashFontFile_GetFontTable , <nl> + OnGetFontTable ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashFontFileHost : : OnGetFontTable ( <nl> + ppapi : : host : : HostMessageContext * context , <nl> + uint32_t table ) { <nl> + std : : string contents ; <nl> + int32_t result = PP_ERROR_FAILED ; <nl> + # if defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + int fd = fd_ . get ( ) ; <nl> + if ( fd ! = - 1 ) { <nl> + size_t length = 0 ; <nl> + if ( content : : GetFontTable ( fd , table , 0 / * offset * / , NULL , & length ) ) { <nl> + contents . resize ( length ) ; <nl> + uint8_t * contents_ptr = <nl> + reinterpret_cast < uint8_t * > ( const_cast < char * > ( contents . c_str ( ) ) ) ; <nl> + if ( content : : GetFontTable ( <nl> + fd , table , 0 / * offset * / , contents_ptr , & length ) ) { <nl> + result = PP_OK ; <nl> + } else { <nl> + contents . clear ( ) ; <nl> + } <nl> + } <nl> + } <nl> + # endif / / defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + <nl> + context - > reply_msg = PpapiPluginMsg_FlashFontFile_GetFontTableReply ( contents ) ; <nl> + return result ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 02bb30f315fd <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_font_file_host . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / c / private / pp_private_font_charset . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + <nl> + # if defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + # include " base / files / scoped_file . h " <nl> + # endif <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace proxy { <nl> + struct SerializedFontDescription ; <nl> + } <nl> + } <nl> + <nl> + class PepperFlashFontFileHost : public ppapi : : host : : ResourceHost { <nl> + public : <nl> + PepperFlashFontFileHost ( <nl> + content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource , <nl> + const ppapi : : proxy : : SerializedFontDescription & description , <nl> + PP_PrivateFontCharset charset ) ; <nl> + ~ PepperFlashFontFileHost ( ) override ; <nl> + <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + int32_t OnGetFontTable ( ppapi : : host : : HostMessageContext * context , <nl> + uint32_t table ) ; <nl> + <nl> + # if defined ( OS_LINUX ) | | defined ( OS_OPENBSD ) <nl> + base : : ScopedFD fd_ ; <nl> + # endif <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashFontFileHost ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ <nl> new file mode 100644 <nl> index 000000000000 . . d590cde3a4a5 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_fullscreen_host . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_flash_fullscreen_host . h " <nl> + <nl> + # include " content / public / renderer / pepper_plugin_instance . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + <nl> + PepperFlashFullscreenHost : : PepperFlashFullscreenHost ( <nl> + content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) <nl> + : ResourceHost ( host - > GetPpapiHost ( ) , instance , resource ) , <nl> + renderer_ppapi_host_ ( host ) { } <nl> + <nl> + PepperFlashFullscreenHost : : ~ PepperFlashFullscreenHost ( ) { } <nl> + <nl> + int32_t PepperFlashFullscreenHost : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashFullscreenHost , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( <nl> + PpapiHostMsg_FlashFullscreen_SetFullscreen , <nl> + OnSetFullscreen ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashFullscreenHost : : OnSetFullscreen ( <nl> + ppapi : : host : : HostMessageContext * context , <nl> + bool fullscreen ) { <nl> + content : : PepperPluginInstance * plugin_instance = <nl> + renderer_ppapi_host_ - > GetPluginInstance ( pp_instance ( ) ) ; <nl> + if ( plugin_instance & & plugin_instance - > FlashSetFullscreen ( fullscreen , true ) ) <nl> + return PP_OK ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 3550ea136631 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_fullscreen_host . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_FULLSCREEN_HOST_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_FLASH_FULLSCREEN_HOST_H_ <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + } <nl> + <nl> + class PepperFlashFullscreenHost : public ppapi : : host : : ResourceHost { <nl> + public : <nl> + PepperFlashFullscreenHost ( content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) ; <nl> + ~ PepperFlashFullscreenHost ( ) override ; <nl> + <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + int32_t OnSetFullscreen ( ppapi : : host : : HostMessageContext * context , <nl> + bool fullscreen ) ; <nl> + <nl> + / / Non - owning pointer . <nl> + content : : RendererPpapiHost * renderer_ppapi_host_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashFullscreenHost ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_FLASH_FULLSCREEN_HOST_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 3b7a438f7220 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_menu_host . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_flash_menu_host . h " <nl> + <nl> + # include " base / strings / utf_string_conversions . h " <nl> + # include " content / public / common / context_menu_params . h " <nl> + # include " content / public / renderer / render_frame . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ipc / ipc_message . h " <nl> + # include " ppapi / c / private / ppb_flash_menu . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / proxy / serialized_flash_menu . h " <nl> + # include " ui / gfx / geometry / point . h " <nl> + <nl> + namespace { <nl> + <nl> + / / Maximum depth of submenus allowed ( e . g . , 1 indicates that submenus are <nl> + / / allowed , but not sub - submenus ) . <nl> + const size_t kMaxMenuDepth = 2 ; <nl> + <nl> + / / Maximum number of entries in any single menu ( including separators ) . <nl> + const size_t kMaxMenuEntries = 50 ; <nl> + <nl> + / / Maximum total number of entries in the | menu_id_map | ( see below ) . <nl> + / / ( Limit to 500 real entries ; reserve the 0 action as an invalid entry . ) <nl> + const size_t kMaxMenuIdMapEntries = 501 ; <nl> + <nl> + / / Converts menu data from one form to another . <nl> + / / - | depth | is the current nested depth ( call it starting with 0 ) . <nl> + / / - | menu_id_map | is such that | menu_id_map [ output_item . action ] = = <nl> + / / input_item . id | ( where | action | is what a | MenuItem | has , | id | is what a <nl> + / / | PP_Flash_MenuItem | has ) . <nl> + bool ConvertMenuData ( const PP_Flash_Menu * in_menu , <nl> + size_t depth , <nl> + std : : vector < content : : MenuItem > * out_menu , <nl> + std : : vector < int32_t > * menu_id_map ) { <nl> + if ( depth > kMaxMenuDepth | | ! in_menu ) <nl> + return false ; <nl> + <nl> + / / Clear the output , just in case . <nl> + out_menu - > clear ( ) ; <nl> + <nl> + if ( ! in_menu - > count ) <nl> + return true ; / / Nothing else to do . <nl> + <nl> + if ( ! in_menu - > items | | in_menu - > count > kMaxMenuEntries ) <nl> + return false ; <nl> + for ( uint32_t i = 0 ; i < in_menu - > count ; i + + ) { <nl> + content : : MenuItem item ; <nl> + <nl> + PP_Flash_MenuItem_Type type = in_menu - > items [ i ] . type ; <nl> + switch ( type ) { <nl> + case PP_FLASH_MENUITEM_TYPE_NORMAL : <nl> + item . type = content : : MenuItem : : OPTION ; <nl> + break ; <nl> + case PP_FLASH_MENUITEM_TYPE_CHECKBOX : <nl> + item . type = content : : MenuItem : : CHECKABLE_OPTION ; <nl> + break ; <nl> + case PP_FLASH_MENUITEM_TYPE_SEPARATOR : <nl> + item . type = content : : MenuItem : : SEPARATOR ; <nl> + break ; <nl> + case PP_FLASH_MENUITEM_TYPE_SUBMENU : <nl> + item . type = content : : MenuItem : : SUBMENU ; <nl> + break ; <nl> + default : <nl> + return false ; <nl> + } <nl> + if ( in_menu - > items [ i ] . name ) <nl> + item . label = base : : UTF8ToUTF16 ( in_menu - > items [ i ] . name ) ; <nl> + if ( menu_id_map - > size ( ) > = kMaxMenuIdMapEntries ) <nl> + return false ; <nl> + item . action = static_cast < unsigned > ( menu_id_map - > size ( ) ) ; <nl> + / / This sets | ( * menu_id_map ) [ item . action ] = in_menu - > items [ i ] . id | . <nl> + menu_id_map - > push_back ( in_menu - > items [ i ] . id ) ; <nl> + item . enabled = PP_ToBool ( in_menu - > items [ i ] . enabled ) ; <nl> + item . checked = PP_ToBool ( in_menu - > items [ i ] . checked ) ; <nl> + if ( type = = PP_FLASH_MENUITEM_TYPE_SUBMENU ) { <nl> + if ( ! ConvertMenuData ( <nl> + in_menu - > items [ i ] . submenu , depth + 1 , & item . submenu , menu_id_map ) ) <nl> + return false ; <nl> + } <nl> + <nl> + out_menu - > push_back ( item ) ; <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + PepperFlashMenuHost : : PepperFlashMenuHost ( <nl> + content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource , <nl> + const ppapi : : proxy : : SerializedFlashMenu & serial_menu ) <nl> + : ppapi : : host : : ResourceHost ( host - > GetPpapiHost ( ) , instance , resource ) , <nl> + renderer_ppapi_host_ ( host ) , <nl> + showing_context_menu_ ( false ) , <nl> + context_menu_request_id_ ( 0 ) , <nl> + has_saved_context_menu_action_ ( false ) , <nl> + saved_context_menu_action_ ( 0 ) { <nl> + menu_id_map_ . push_back ( 0 ) ; / / Reserve | menu_id_map_ [ 0 ] | . <nl> + if ( ! ConvertMenuData ( serial_menu . pp_menu ( ) , 0 , & menu_data_ , & menu_id_map_ ) ) { <nl> + menu_data_ . clear ( ) ; <nl> + menu_id_map_ . clear ( ) ; <nl> + } <nl> + } <nl> + <nl> + PepperFlashMenuHost : : ~ PepperFlashMenuHost ( ) { <nl> + if ( showing_context_menu_ ) { <nl> + content : : RenderFrame * render_frame = <nl> + renderer_ppapi_host_ - > GetRenderFrameForInstance ( pp_instance ( ) ) ; <nl> + if ( render_frame ) <nl> + render_frame - > CancelContextMenu ( context_menu_request_id_ ) ; <nl> + } <nl> + } <nl> + <nl> + int32_t PepperFlashMenuHost : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashMenuHost , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_FlashMenu_Show , <nl> + OnHostMsgShow ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashMenuHost : : OnHostMsgShow ( <nl> + ppapi : : host : : HostMessageContext * context , <nl> + const PP_Point & location ) { <nl> + / / Note that all early returns must do a SendMenuReply . The sync result for <nl> + / / this message isn ' t used , so to forward the error to the plugin , we need to <nl> + / / additionally call SendMenuReply explicitly . <nl> + if ( menu_data_ . empty ( ) ) { <nl> + SendMenuReply ( PP_ERROR_FAILED , - 1 ) ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + if ( showing_context_menu_ ) { <nl> + SendMenuReply ( PP_ERROR_INPROGRESS , - 1 ) ; <nl> + return PP_ERROR_INPROGRESS ; <nl> + } <nl> + <nl> + content : : RenderFrame * render_frame = <nl> + renderer_ppapi_host_ - > GetRenderFrameForInstance ( pp_instance ( ) ) ; <nl> + <nl> + content : : ContextMenuParams params ; <nl> + params . x = location . x ; <nl> + params . y = location . y ; <nl> + params . custom_context . is_pepper_menu = true ; <nl> + params . custom_context . render_widget_id = <nl> + renderer_ppapi_host_ - > GetRoutingIDForWidget ( pp_instance ( ) ) ; <nl> + params . custom_items = menu_data_ ; <nl> + <nl> + / / Transform the position to be in render frame ' s coordinates . <nl> + gfx : : Point render_frame_pt = renderer_ppapi_host_ - > PluginPointToRenderFrame ( <nl> + pp_instance ( ) , gfx : : Point ( location . x , location . y ) ) ; <nl> + params . x = render_frame_pt . x ( ) ; <nl> + params . y = render_frame_pt . y ( ) ; <nl> + <nl> + showing_context_menu_ = true ; <nl> + context_menu_request_id_ = render_frame - > ShowContextMenu ( this , params ) ; <nl> + <nl> + / / Note : the show message is sync so this OK is for the sync reply which we <nl> + / / don ' t actually use ( see the comment in the resource file for this ) . The <nl> + / / async message containing the context menu action will be sent in the <nl> + / / future . <nl> + return PP_OK ; <nl> + } <nl> + <nl> + void PepperFlashMenuHost : : OnMenuAction ( int request_id , unsigned action ) { <nl> + / / Just save the action . <nl> + DCHECK ( ! has_saved_context_menu_action_ ) ; <nl> + has_saved_context_menu_action_ = true ; <nl> + saved_context_menu_action_ = action ; <nl> + } <nl> + <nl> + void PepperFlashMenuHost : : OnMenuClosed ( int request_id ) { <nl> + if ( has_saved_context_menu_action_ & & <nl> + saved_context_menu_action_ < menu_id_map_ . size ( ) ) { <nl> + SendMenuReply ( PP_OK , menu_id_map_ [ saved_context_menu_action_ ] ) ; <nl> + has_saved_context_menu_action_ = false ; <nl> + saved_context_menu_action_ = 0 ; <nl> + } else { <nl> + SendMenuReply ( PP_ERROR_USERCANCEL , - 1 ) ; <nl> + } <nl> + <nl> + showing_context_menu_ = false ; <nl> + context_menu_request_id_ = 0 ; <nl> + } <nl> + <nl> + void PepperFlashMenuHost : : SendMenuReply ( int32_t result , int action ) { <nl> + ppapi : : host : : ReplyMessageContext reply_context ( <nl> + ppapi : : proxy : : ResourceMessageReplyParams ( pp_resource ( ) , 0 ) , <nl> + NULL , <nl> + MSG_ROUTING_NONE ) ; <nl> + reply_context . params . set_result ( result ) ; <nl> + host ( ) - > SendReply ( reply_context , PpapiPluginMsg_FlashMenu_ShowReply ( action ) ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 3aa730a6afc3 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_menu_host . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_MENU_HOST_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_FLASH_MENU_HOST_H_ <nl> + <nl> + # include < vector > <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " content / public / renderer / context_menu_client . h " <nl> + # include " ppapi / c / pp_point . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + struct MenuItem ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace proxy { <nl> + class SerializedFlashMenu ; <nl> + } <nl> + } <nl> + <nl> + class PepperFlashMenuHost : public ppapi : : host : : ResourceHost , <nl> + public content : : ContextMenuClient { <nl> + public : <nl> + PepperFlashMenuHost ( content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource , <nl> + const ppapi : : proxy : : SerializedFlashMenu & serial_menu ) ; <nl> + ~ PepperFlashMenuHost ( ) override ; <nl> + <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + int32_t OnHostMsgShow ( ppapi : : host : : HostMessageContext * context , <nl> + const PP_Point & location ) ; <nl> + <nl> + / / ContextMenuClient implementation . <nl> + void OnMenuAction ( int request_id , unsigned action ) override ; <nl> + void OnMenuClosed ( int request_id ) override ; <nl> + <nl> + void SendMenuReply ( int32_t result , int action ) ; <nl> + <nl> + content : : RendererPpapiHost * renderer_ppapi_host_ ; <nl> + <nl> + bool showing_context_menu_ ; <nl> + int context_menu_request_id_ ; <nl> + <nl> + std : : vector < content : : MenuItem > menu_data_ ; <nl> + <nl> + / / We send | MenuItem | s , which have an | unsigned | " action " field instead of <nl> + / / an | int32_t | ID . ( CONTENT also limits the range of valid values for <nl> + / / actions . ) This maps actions to IDs . <nl> + std : : vector < int32_t > menu_id_map_ ; <nl> + <nl> + / / Used to send a single context menu " completion " upon menu close . <nl> + bool has_saved_context_menu_action_ ; <nl> + unsigned saved_context_menu_action_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashMenuHost ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_FLASH_MENU_HOST_H_ <nl> new file mode 100644 <nl> index 000000000000 . . fe5e28ebbeb8 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_renderer_host . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_flash_renderer_host . h " <nl> + <nl> + # include < map > <nl> + # include < vector > <nl> + <nl> + # include " base / lazy_instance . h " <nl> + # include " base / metrics / histogram . h " <nl> + # include " base / strings / string_util . h " <nl> + # include " content / public / renderer / pepper_plugin_instance . h " <nl> + # include " content / public / renderer / render_thread . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ipc / ipc_message_macros . h " <nl> + # include " net / http / http_util . h " <nl> + # include " ppapi / c / pp_errors . h " <nl> + # include " ppapi / c / trusted / ppb_browser_font_trusted . h " <nl> + # include " ppapi / host / dispatch_host_message . h " <nl> + # include " ppapi / proxy / host_dispatcher . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / proxy / resource_message_params . h " <nl> + # include " ppapi / proxy / serialized_structs . h " <nl> + # include " ppapi / thunk / enter . h " <nl> + # include " ppapi / thunk / ppb_image_data_api . h " <nl> + # include " skia / ext / platform_canvas . h " <nl> + # include " third_party / skia / include / core / SkCanvas . h " <nl> + # include " third_party / skia / include / core / SkMatrix . h " <nl> + # include " third_party / skia / include / core / SkPaint . h " <nl> + # include " third_party / skia / include / core / SkPoint . h " <nl> + # include " third_party / skia / include / core / SkTemplates . h " <nl> + # include " third_party / skia / include / core / SkTypeface . h " <nl> + # include " ui / gfx / geometry / rect . h " <nl> + # include " url / gurl . h " <nl> + <nl> + using ppapi : : thunk : : EnterResourceNoLock ; <nl> + using ppapi : : thunk : : PPB_ImageData_API ; <nl> + <nl> + namespace { <nl> + <nl> + / / Some non - simple HTTP request headers that Flash may set . <nl> + / / ( Please see http : / / www . w3 . org / TR / cors / # simple - header for the definition of <nl> + / / simple headers . ) <nl> + / / <nl> + / / The list and the enum defined below are used to collect data about request <nl> + / / headers used in PPB_Flash . Navigate ( ) calls , in order to understand the impact <nl> + / / of rejecting PPB_Flash . Navigate ( ) requests with non - simple headers . <nl> + / / <nl> + / / TODO ( yzshen ) : We should be able to remove the histogram recording code once <nl> + / / we get the answer . <nl> + const char * const kRejectedHttpRequestHeaders [ ] = { <nl> + " authorization " , / / <nl> + " cache - control " , / / <nl> + " content - encoding " , / / <nl> + " content - md5 " , / / <nl> + " content - type " , / / If the media type is not one of those covered by the <nl> + / / simple header definition . <nl> + " expires " , / / <nl> + " from " , / / <nl> + " if - match " , / / <nl> + " if - none - match " , / / <nl> + " if - range " , / / <nl> + " if - unmodified - since " , / / <nl> + " pragma " , / / <nl> + " referer " / / <nl> + } ; <nl> + <nl> + / / Please note that new entries should be added right above <nl> + / / FLASH_NAVIGATE_USAGE_ENUM_COUNT , and existing entries shouldn ' t be re - ordered <nl> + / / or removed , since this ordering is used in a histogram . <nl> + enum FlashNavigateUsage { <nl> + / / This section must be in the same order as kRejectedHttpRequestHeaders . <nl> + REJECT_AUTHORIZATION = 0 , <nl> + REJECT_CACHE_CONTROL , <nl> + REJECT_CONTENT_ENCODING , <nl> + REJECT_CONTENT_MD5 , <nl> + REJECT_CONTENT_TYPE , <nl> + REJECT_EXPIRES , <nl> + REJECT_FROM , <nl> + REJECT_IF_MATCH , <nl> + REJECT_IF_NONE_MATCH , <nl> + REJECT_IF_RANGE , <nl> + REJECT_IF_UNMODIFIED_SINCE , <nl> + REJECT_PRAGMA , <nl> + REJECT_REFERER , <nl> + <nl> + / / The navigate request is rejected because of headers not listed above <nl> + / / ( e . g . , custom headers ) . <nl> + REJECT_OTHER_HEADERS , <nl> + <nl> + / / Total number of rejected navigate requests . <nl> + TOTAL_REJECTED_NAVIGATE_REQUESTS , <nl> + <nl> + / / Total number of navigate requests . <nl> + TOTAL_NAVIGATE_REQUESTS , <nl> + FLASH_NAVIGATE_USAGE_ENUM_COUNT <nl> + } ; <nl> + <nl> + static base : : LazyInstance < std : : map < std : : string , FlashNavigateUsage > > <nl> + g_rejected_headers = LAZY_INSTANCE_INITIALIZER ; <nl> + <nl> + bool IsSimpleHeader ( const std : : string & lower_case_header_name , <nl> + const std : : string & header_value ) { <nl> + if ( lower_case_header_name = = " accept " | | <nl> + lower_case_header_name = = " accept - language " | | <nl> + lower_case_header_name = = " content - language " ) { <nl> + return true ; <nl> + } <nl> + <nl> + if ( lower_case_header_name = = " content - type " ) { <nl> + std : : string lower_case_mime_type ; <nl> + std : : string lower_case_charset ; <nl> + bool had_charset = false ; <nl> + net : : HttpUtil : : ParseContentType ( header_value , <nl> + & lower_case_mime_type , <nl> + & lower_case_charset , <nl> + & had_charset , <nl> + NULL ) ; <nl> + return lower_case_mime_type = = " application / x - www - form - urlencoded " | | <nl> + lower_case_mime_type = = " multipart / form - data " | | <nl> + lower_case_mime_type = = " text / plain " ; <nl> + } <nl> + <nl> + return false ; <nl> + } <nl> + <nl> + void RecordFlashNavigateUsage ( FlashNavigateUsage usage ) { <nl> + DCHECK_NE ( FLASH_NAVIGATE_USAGE_ENUM_COUNT , usage ) ; <nl> + UMA_HISTOGRAM_ENUMERATION ( <nl> + " Plugin . FlashNavigateUsage " , usage , FLASH_NAVIGATE_USAGE_ENUM_COUNT ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + PepperFlashRendererHost : : PepperFlashRendererHost ( <nl> + content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) <nl> + : ResourceHost ( host - > GetPpapiHost ( ) , instance , resource ) , <nl> + host_ ( host ) , <nl> + weak_factory_ ( this ) { } <nl> + <nl> + PepperFlashRendererHost : : ~ PepperFlashRendererHost ( ) { <nl> + / / This object may be destroyed in the middle of a sync message . If that is <nl> + / / the case , make sure we respond to all the pending navigate calls . <nl> + std : : vector < ppapi : : host : : ReplyMessageContext > : : reverse_iterator it ; <nl> + for ( it = navigate_replies_ . rbegin ( ) ; it ! = navigate_replies_ . rend ( ) ; + + it ) <nl> + SendReply ( * it , IPC : : Message ( ) ) ; <nl> + } <nl> + <nl> + int32_t PepperFlashRendererHost : : OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) { <nl> + PPAPI_BEGIN_MESSAGE_MAP ( PepperFlashRendererHost , msg ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_GetProxyForURL , <nl> + OnGetProxyForURL ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_SetInstanceAlwaysOnTop , <nl> + OnSetInstanceAlwaysOnTop ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_DrawGlyphs , <nl> + OnDrawGlyphs ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_Navigate , OnNavigate ) <nl> + PPAPI_DISPATCH_HOST_RESOURCE_CALL ( PpapiHostMsg_Flash_IsRectTopmost , <nl> + OnIsRectTopmost ) <nl> + PPAPI_END_MESSAGE_MAP ( ) <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> + <nl> + int32_t PepperFlashRendererHost : : OnGetProxyForURL ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const std : : string & url ) { <nl> + GURL gurl ( url ) ; <nl> + if ( ! gurl . is_valid ( ) ) <nl> + return PP_ERROR_FAILED ; <nl> + std : : string proxy ; <nl> + bool result = content : : RenderThread : : Get ( ) - > ResolveProxy ( gurl , & proxy ) ; <nl> + if ( ! result ) <nl> + return PP_ERROR_FAILED ; <nl> + host_context - > reply_msg = PpapiPluginMsg_Flash_GetProxyForURLReply ( proxy ) ; <nl> + return PP_OK ; <nl> + } <nl> + <nl> + int32_t PepperFlashRendererHost : : OnSetInstanceAlwaysOnTop ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + bool on_top ) { <nl> + content : : PepperPluginInstance * plugin_instance = <nl> + host_ - > GetPluginInstance ( pp_instance ( ) ) ; <nl> + if ( plugin_instance ) <nl> + plugin_instance - > SetAlwaysOnTop ( on_top ) ; <nl> + / / Since no reply is sent for this message , it doesn ' t make sense to return an <nl> + / / error . <nl> + return PP_OK ; <nl> + } <nl> + <nl> + int32_t PepperFlashRendererHost : : OnDrawGlyphs ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + ppapi : : proxy : : PPBFlash_DrawGlyphs_Params params ) { <nl> + if ( params . glyph_indices . size ( ) ! = params . glyph_advances . size ( ) | | <nl> + params . glyph_indices . empty ( ) ) <nl> + return PP_ERROR_FAILED ; <nl> + <nl> + / / Set up the typeface . <nl> + int style = SkTypeface : : kNormal ; <nl> + if ( static_cast < PP_BrowserFont_Trusted_Weight > ( params . font_desc . weight ) > = <nl> + PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD ) <nl> + style | = SkTypeface : : kBold ; <nl> + if ( params . font_desc . italic ) <nl> + style | = SkTypeface : : kItalic ; <nl> + skia : : RefPtr < SkTypeface > typeface = skia : : AdoptRef ( SkTypeface : : CreateFromName ( <nl> + params . font_desc . face . c_str ( ) , static_cast < SkTypeface : : Style > ( style ) ) ) ; <nl> + if ( ! typeface ) <nl> + return PP_ERROR_FAILED ; <nl> + <nl> + EnterResourceNoLock < PPB_ImageData_API > enter ( <nl> + params . image_data . host_resource ( ) , true ) ; <nl> + if ( enter . failed ( ) ) <nl> + return PP_ERROR_FAILED ; <nl> + <nl> + / / Set up the canvas . <nl> + PPB_ImageData_API * image = static_cast < PPB_ImageData_API * > ( enter . object ( ) ) ; <nl> + SkCanvas * canvas = image - > GetCanvas ( ) ; <nl> + bool needs_unmapping = false ; <nl> + if ( ! canvas ) { <nl> + needs_unmapping = true ; <nl> + image - > Map ( ) ; <nl> + canvas = image - > GetCanvas ( ) ; <nl> + if ( ! canvas ) <nl> + return PP_ERROR_FAILED ; / / Failure mapping . <nl> + } <nl> + <nl> + SkAutoCanvasRestore acr ( canvas , true ) ; <nl> + <nl> + / / Clip is applied in pixels before the transform . <nl> + SkRect clip_rect = { <nl> + SkIntToScalar ( params . clip . point . x ) , SkIntToScalar ( params . clip . point . y ) , <nl> + SkIntToScalar ( params . clip . point . x + params . clip . size . width ) , <nl> + SkIntToScalar ( params . clip . point . y + params . clip . size . height ) } ; <nl> + canvas - > clipRect ( clip_rect ) ; <nl> + <nl> + / / Convert & set the matrix . <nl> + SkMatrix matrix ; <nl> + matrix . set ( SkMatrix : : kMScaleX , SkFloatToScalar ( params . transformation [ 0 ] [ 0 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMSkewX , SkFloatToScalar ( params . transformation [ 0 ] [ 1 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMTransX , SkFloatToScalar ( params . transformation [ 0 ] [ 2 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMSkewY , SkFloatToScalar ( params . transformation [ 1 ] [ 0 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMScaleY , SkFloatToScalar ( params . transformation [ 1 ] [ 1 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMTransY , SkFloatToScalar ( params . transformation [ 1 ] [ 2 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMPersp0 , SkFloatToScalar ( params . transformation [ 2 ] [ 0 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMPersp1 , SkFloatToScalar ( params . transformation [ 2 ] [ 1 ] ) ) ; <nl> + matrix . set ( SkMatrix : : kMPersp2 , SkFloatToScalar ( params . transformation [ 2 ] [ 2 ] ) ) ; <nl> + canvas - > concat ( matrix ) ; <nl> + <nl> + SkPaint paint ; <nl> + paint . setColor ( params . color ) ; <nl> + paint . setTextEncoding ( SkPaint : : kGlyphID_TextEncoding ) ; <nl> + paint . setAntiAlias ( true ) ; <nl> + paint . setHinting ( SkPaint : : kFull_Hinting ) ; <nl> + paint . setTextSize ( SkIntToScalar ( params . font_desc . size ) ) ; <nl> + paint . setTypeface ( typeface . get ( ) ) ; / / Takes a ref and manages lifetime . <nl> + if ( params . allow_subpixel_aa ) { <nl> + paint . setSubpixelText ( true ) ; <nl> + paint . setLCDRenderText ( true ) ; <nl> + } <nl> + <nl> + SkScalar x = SkIntToScalar ( params . position . x ) ; <nl> + SkScalar y = SkIntToScalar ( params . position . y ) ; <nl> + <nl> + / / Build up the skia advances . <nl> + size_t glyph_count = params . glyph_indices . size ( ) ; <nl> + if ( glyph_count ) { <nl> + std : : vector < SkPoint > storage ; <nl> + storage . resize ( glyph_count ) ; <nl> + SkPoint * sk_positions = & storage [ 0 ] ; <nl> + for ( uint32_t i = 0 ; i < glyph_count ; i + + ) { <nl> + sk_positions [ i ] . set ( x , y ) ; <nl> + x + = SkFloatToScalar ( params . glyph_advances [ i ] . x ) ; <nl> + y + = SkFloatToScalar ( params . glyph_advances [ i ] . y ) ; <nl> + } <nl> + <nl> + canvas - > drawPosText ( <nl> + & params . glyph_indices [ 0 ] , glyph_count * 2 , sk_positions , paint ) ; <nl> + } <nl> + <nl> + if ( needs_unmapping ) <nl> + image - > Unmap ( ) ; <nl> + <nl> + return PP_OK ; <nl> + } <nl> + <nl> + / / CAUTION : This code is subtle because Navigate is a sync call which may <nl> + / / cause re - entrancy or cause the instance to be destroyed . If the instance <nl> + / / is destroyed we need to ensure that we respond to all outstanding sync <nl> + / / messages so that the plugin process does not remain blocked . <nl> + int32_t PepperFlashRendererHost : : OnNavigate ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const ppapi : : URLRequestInfoData & data , <nl> + const std : : string & target , <nl> + bool from_user_action ) { <nl> + / / If our PepperPluginInstance is already destroyed , just return a failure . <nl> + content : : PepperPluginInstance * plugin_instance = <nl> + host_ - > GetPluginInstance ( pp_instance ( ) ) ; <nl> + if ( ! plugin_instance ) <nl> + return PP_ERROR_FAILED ; <nl> + <nl> + std : : map < std : : string , FlashNavigateUsage > & rejected_headers = <nl> + g_rejected_headers . Get ( ) ; <nl> + if ( rejected_headers . empty ( ) ) { <nl> + for ( size_t i = 0 ; i < arraysize ( kRejectedHttpRequestHeaders ) ; + + i ) <nl> + rejected_headers [ kRejectedHttpRequestHeaders [ i ] ] = <nl> + static_cast < FlashNavigateUsage > ( i ) ; <nl> + } <nl> + <nl> + net : : HttpUtil : : HeadersIterator header_iter ( <nl> + data . headers . begin ( ) , data . headers . end ( ) , " \ n \ r " ) ; <nl> + bool rejected = false ; <nl> + while ( header_iter . GetNext ( ) ) { <nl> + std : : string lower_case_header_name = <nl> + base : : StringToLowerASCII ( header_iter . name ( ) ) ; <nl> + if ( ! IsSimpleHeader ( lower_case_header_name , header_iter . values ( ) ) ) { <nl> + rejected = true ; <nl> + <nl> + std : : map < std : : string , FlashNavigateUsage > : : const_iterator iter = <nl> + rejected_headers . find ( lower_case_header_name ) ; <nl> + FlashNavigateUsage usage = <nl> + iter ! = rejected_headers . end ( ) ? iter - > second : REJECT_OTHER_HEADERS ; <nl> + RecordFlashNavigateUsage ( usage ) ; <nl> + } <nl> + } <nl> + <nl> + RecordFlashNavigateUsage ( TOTAL_NAVIGATE_REQUESTS ) ; <nl> + if ( rejected ) { <nl> + RecordFlashNavigateUsage ( TOTAL_REJECTED_NAVIGATE_REQUESTS ) ; <nl> + return PP_ERROR_NOACCESS ; <nl> + } <nl> + <nl> + / / Navigate may call into Javascript ( e . g . with a " javascript : " URL ) , <nl> + / / or do things like navigate away from the page , either one of which will <nl> + / / need to re - enter into the plugin . It is safe , because it is essentially <nl> + / / equivalent to NPN_GetURL , where Flash would expect re - entrancy . <nl> + ppapi : : proxy : : HostDispatcher * host_dispatcher = <nl> + ppapi : : proxy : : HostDispatcher : : GetForInstance ( pp_instance ( ) ) ; <nl> + host_dispatcher - > set_allow_plugin_reentrancy ( ) ; <nl> + <nl> + / / Grab a weak pointer to ourselves on the stack so we can check if we are <nl> + / / still alive . <nl> + base : : WeakPtr < PepperFlashRendererHost > weak_ptr = weak_factory_ . GetWeakPtr ( ) ; <nl> + / / Keep track of reply contexts in case we are destroyed during a Navigate <nl> + / / call . Even if we are destroyed , we still need to send these replies to <nl> + / / unblock the plugin process . <nl> + navigate_replies_ . push_back ( host_context - > MakeReplyMessageContext ( ) ) ; <nl> + plugin_instance - > Navigate ( data , target . c_str ( ) , from_user_action ) ; <nl> + / / This object might have been destroyed by this point . If it is destroyed <nl> + / / the reply will be sent in the destructor . Otherwise send the reply here . <nl> + if ( weak_ptr . get ( ) ) { <nl> + SendReply ( navigate_replies_ . back ( ) , IPC : : Message ( ) ) ; <nl> + navigate_replies_ . pop_back ( ) ; <nl> + } <nl> + <nl> + / / Return PP_OK_COMPLETIONPENDING so that no reply is automatically sent . <nl> + return PP_OK_COMPLETIONPENDING ; <nl> + } <nl> + <nl> + int32_t PepperFlashRendererHost : : OnIsRectTopmost ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + const PP_Rect & rect ) { <nl> + content : : PepperPluginInstance * plugin_instance = <nl> + host_ - > GetPluginInstance ( pp_instance ( ) ) ; <nl> + if ( plugin_instance & & <nl> + plugin_instance - > IsRectTopmost ( gfx : : Rect ( <nl> + rect . point . x , rect . point . y , rect . size . width , rect . size . height ) ) ) <nl> + return PP_OK ; <nl> + return PP_ERROR_FAILED ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . de22f46045a5 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_flash_renderer_host . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_RENDERER_HOST_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_FLASH_RENDERER_HOST_H_ <nl> + <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / memory / weak_ptr . h " <nl> + # include " ppapi / host / host_message_context . h " <nl> + # include " ppapi / host / resource_host . h " <nl> + <nl> + struct PP_Rect ; <nl> + <nl> + namespace ppapi { <nl> + struct URLRequestInfoData ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace proxy { <nl> + struct PPBFlash_DrawGlyphs_Params ; <nl> + } <nl> + } <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + } <nl> + <nl> + class PepperFlashRendererHost : public ppapi : : host : : ResourceHost { <nl> + public : <nl> + PepperFlashRendererHost ( content : : RendererPpapiHost * host , <nl> + PP_Instance instance , <nl> + PP_Resource resource ) ; <nl> + ~ PepperFlashRendererHost ( ) override ; <nl> + <nl> + / / ppapi : : host : : ResourceHost override . <nl> + int32_t OnResourceMessageReceived ( <nl> + const IPC : : Message & msg , <nl> + ppapi : : host : : HostMessageContext * context ) override ; <nl> + <nl> + private : <nl> + int32_t OnGetProxyForURL ( ppapi : : host : : HostMessageContext * host_context , <nl> + const std : : string & url ) ; <nl> + int32_t OnSetInstanceAlwaysOnTop ( <nl> + ppapi : : host : : HostMessageContext * host_context , <nl> + bool on_top ) ; <nl> + int32_t OnDrawGlyphs ( ppapi : : host : : HostMessageContext * host_context , <nl> + ppapi : : proxy : : PPBFlash_DrawGlyphs_Params params ) ; <nl> + int32_t OnNavigate ( ppapi : : host : : HostMessageContext * host_context , <nl> + const ppapi : : URLRequestInfoData & data , <nl> + const std : : string & target , <nl> + bool from_user_action ) ; <nl> + int32_t OnIsRectTopmost ( ppapi : : host : : HostMessageContext * host_context , <nl> + const PP_Rect & rect ) ; <nl> + <nl> + / / A stack of ReplyMessageContexts to track Navigate ( ) calls which have not <nl> + / / yet been replied to . <nl> + std : : vector < ppapi : : host : : ReplyMessageContext > navigate_replies_ ; <nl> + <nl> + content : : RendererPpapiHost * host_ ; <nl> + base : : WeakPtrFactory < PepperFlashRendererHost > weak_factory_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperFlashRendererHost ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_FLASH_RENDERER_HOST_H_ <nl> new file mode 100644 <nl> index 000000000000 . . a610a30dfff5 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_helper . cc <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_helper . h " <nl> + <nl> + # include " chrome / renderer / pepper / chrome_renderer_pepper_host_factory . h " <nl> + # include " chrome / renderer / pepper / pepper_shared_memory_message_filter . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + <nl> + PepperHelper : : PepperHelper ( content : : RenderFrame * render_frame ) <nl> + : RenderFrameObserver ( render_frame ) { } <nl> + <nl> + PepperHelper : : ~ PepperHelper ( ) { } <nl> + <nl> + void PepperHelper : : DidCreatePepperPlugin ( content : : RendererPpapiHost * host ) { <nl> + / / TODO ( brettw ) figure out how to hook up the host factory . It needs some <nl> + / / kind of filter - like system to allow dynamic additions . <nl> + host - > GetPpapiHost ( ) - > AddHostFactoryFilter ( <nl> + scoped_ptr < ppapi : : host : : HostFactory > ( <nl> + new ChromeRendererPepperHostFactory ( host ) ) ) ; <nl> + host - > GetPpapiHost ( ) - > AddInstanceMessageFilter ( <nl> + scoped_ptr < ppapi : : host : : InstanceMessageFilter > ( <nl> + new PepperSharedMemoryMessageFilter ( host ) ) ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . b3e850b2481b <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_helper . h <nl> <nl> + / / Copyright ( c ) 2012 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_HELPER_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_HELPER_H_ <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " content / public / renderer / render_frame_observer . h " <nl> + <nl> + / / This class listens for Pepper creation events from the RenderFrame and <nl> + / / attaches the parts required for Chrome - specific plugin support . <nl> + class PepperHelper : public content : : RenderFrameObserver { <nl> + public : <nl> + explicit PepperHelper ( content : : RenderFrame * render_frame ) ; <nl> + ~ PepperHelper ( ) override ; <nl> + <nl> + / / RenderFrameObserver . <nl> + void DidCreatePepperPlugin ( content : : RendererPpapiHost * host ) override ; <nl> + <nl> + private : <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperHelper ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_HELPER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . e01aea741fc8 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_shared_memory_message_filter . cc <nl> <nl> + / / Copyright ( c ) 2013 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / renderer / pepper / pepper_shared_memory_message_filter . h " <nl> + <nl> + # include " base / memory / scoped_ptr . h " <nl> + # include " base / memory / shared_memory . h " <nl> + # include " base / process / process_handle . h " <nl> + # include " content / public / common / content_client . h " <nl> + # include " content / public / renderer / pepper_plugin_instance . h " <nl> + # include " content / public / renderer / render_thread . h " <nl> + # include " content / public / renderer / renderer_ppapi_host . h " <nl> + # include " ppapi / host / ppapi_host . h " <nl> + # include " ppapi / proxy / ppapi_messages . h " <nl> + # include " ppapi / shared_impl / var_tracker . h " <nl> + <nl> + PepperSharedMemoryMessageFilter : : PepperSharedMemoryMessageFilter ( <nl> + content : : RendererPpapiHost * host ) <nl> + : InstanceMessageFilter ( host - > GetPpapiHost ( ) ) , host_ ( host ) { } <nl> + <nl> + PepperSharedMemoryMessageFilter : : ~ PepperSharedMemoryMessageFilter ( ) { } <nl> + <nl> + bool PepperSharedMemoryMessageFilter : : OnInstanceMessageReceived ( <nl> + const IPC : : Message & msg ) { <nl> + bool handled = true ; <nl> + IPC_BEGIN_MESSAGE_MAP ( PepperSharedMemoryMessageFilter , msg ) <nl> + IPC_MESSAGE_HANDLER ( PpapiHostMsg_SharedMemory_CreateSharedMemory , <nl> + OnHostMsgCreateSharedMemory ) <nl> + IPC_MESSAGE_UNHANDLED ( handled = false ) <nl> + IPC_END_MESSAGE_MAP ( ) <nl> + return handled ; <nl> + } <nl> + <nl> + bool PepperSharedMemoryMessageFilter : : Send ( IPC : : Message * msg ) { <nl> + return host_ - > GetPpapiHost ( ) - > Send ( msg ) ; <nl> + } <nl> + <nl> + void PepperSharedMemoryMessageFilter : : OnHostMsgCreateSharedMemory ( <nl> + PP_Instance instance , <nl> + uint32_t size , <nl> + int * host_handle_id , <nl> + ppapi : : proxy : : SerializedHandle * plugin_handle ) { <nl> + plugin_handle - > set_null_shmem ( ) ; <nl> + * host_handle_id = - 1 ; <nl> + scoped_ptr < base : : SharedMemory > shm ( content : : RenderThread : : Get ( ) <nl> + - > HostAllocateSharedMemoryBuffer ( size ) <nl> + . Pass ( ) ) ; <nl> + if ( ! shm . get ( ) ) <nl> + return ; <nl> + <nl> + base : : SharedMemoryHandle host_shm_handle ; <nl> + shm - > ShareToProcess ( base : : GetCurrentProcessHandle ( ) , & host_shm_handle ) ; <nl> + * host_handle_id = <nl> + content : : PepperPluginInstance : : Get ( instance ) <nl> + - > GetVarTracker ( ) <nl> + - > TrackSharedMemoryHandle ( instance , host_shm_handle , size ) ; <nl> + <nl> + base : : PlatformFile host_handle = <nl> + # if defined ( OS_WIN ) <nl> + host_shm_handle ; <nl> + # elif defined ( OS_POSIX ) <nl> + host_shm_handle . fd ; <nl> + # else <nl> + # error Not implemented . <nl> + # endif <nl> + / / We set auto_close to false since we need our file descriptor to <nl> + / / actually be duplicated on linux . The shared memory destructor will <nl> + / / close the original handle for us . <nl> + plugin_handle - > set_shmem ( host_ - > ShareHandleWithRemote ( host_handle , false ) , <nl> + size ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . d7e0934cd6ec <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / renderer / pepper / pepper_shared_memory_message_filter . h <nl> <nl> + / / Copyright ( c ) 2013 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_RENDERER_PEPPER_PEPPER_SHARED_MEMORY_MESSAGE_FILTER_H_ <nl> + # define CHROME_RENDERER_PEPPER_PEPPER_SHARED_MEMORY_MESSAGE_FILTER_H_ <nl> + <nl> + # include " base / basictypes . h " <nl> + # include " base / compiler_specific . h " <nl> + # include " ppapi / c / pp_instance . h " <nl> + # include " ppapi / host / instance_message_filter . h " <nl> + <nl> + namespace content { <nl> + class RendererPpapiHost ; <nl> + } <nl> + <nl> + namespace ppapi { <nl> + namespace proxy { <nl> + class SerializedHandle ; <nl> + } <nl> + } <nl> + <nl> + / / Implements the backend for shared memory messages from a plugin process . <nl> + class PepperSharedMemoryMessageFilter <nl> + : public ppapi : : host : : InstanceMessageFilter { <nl> + public : <nl> + explicit PepperSharedMemoryMessageFilter ( content : : RendererPpapiHost * host ) ; <nl> + ~ PepperSharedMemoryMessageFilter ( ) override ; <nl> + <nl> + / / InstanceMessageFilter : <nl> + bool OnInstanceMessageReceived ( const IPC : : Message & msg ) override ; <nl> + <nl> + bool Send ( IPC : : Message * msg ) ; <nl> + <nl> + private : <nl> + / / Message handlers . <nl> + void OnHostMsgCreateSharedMemory ( <nl> + PP_Instance instance , <nl> + uint32_t size , <nl> + int * host_shm_handle_id , <nl> + ppapi : : proxy : : SerializedHandle * plugin_shm_handle ) ; <nl> + <nl> + content : : RendererPpapiHost * host_ ; <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PepperSharedMemoryMessageFilter ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_RENDERER_PEPPER_PEPPER_SHARED_MEMORY_MESSAGE_FILTER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . db6d9533cf51 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / utility / printing_handler . cc <nl> <nl> + / / Copyright 2014 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # include " chrome / utility / printing_handler . h " <nl> + <nl> + # include " base / files / file_util . h " <nl> + # include " base / lazy_instance . h " <nl> + # include " base / path_service . h " <nl> + # include " base / scoped_native_library . h " <nl> + # include " chrome / common / print_messages . h " <nl> + # include " content / public / utility / utility_thread . h " <nl> + # include " pdf / pdf . h " <nl> + # include " printing / page_range . h " <nl> + # include " printing / pdf_render_settings . h " <nl> + <nl> + # if defined ( OS_WIN ) <nl> + # include " printing / emf_win . h " <nl> + # include " ui / gfx / gdi_util . h " <nl> + # endif <nl> + <nl> + <nl> + namespace { <nl> + <nl> + bool Send ( IPC : : Message * message ) { <nl> + return content : : UtilityThread : : Get ( ) - > Send ( message ) ; <nl> + } <nl> + <nl> + void ReleaseProcessIfNeeded ( ) { <nl> + content : : UtilityThread : : Get ( ) - > ReleaseProcessIfNeeded ( ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + PrintingHandler : : PrintingHandler ( ) { } <nl> + <nl> + PrintingHandler : : ~ PrintingHandler ( ) { } <nl> + <nl> + bool PrintingHandler : : OnMessageReceived ( const IPC : : Message & message ) { <nl> + bool handled = true ; <nl> + IPC_BEGIN_MESSAGE_MAP ( PrintingHandler , message ) <nl> + # if defined ( OS_WIN ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityMsg_RenderPDFPagesToMetafiles , <nl> + OnRenderPDFPagesToMetafile ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage , <nl> + OnRenderPDFPagesToMetafileGetPage ) <nl> + IPC_MESSAGE_HANDLER ( ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop , <nl> + OnRenderPDFPagesToMetafileStop ) <nl> + # endif / / OS_WIN <nl> + IPC_MESSAGE_UNHANDLED ( handled = false ) <nl> + IPC_END_MESSAGE_MAP ( ) <nl> + return handled ; <nl> + } <nl> + <nl> + # if defined ( OS_WIN ) <nl> + void PrintingHandler : : OnRenderPDFPagesToMetafile ( <nl> + IPC : : PlatformFileForTransit pdf_transit , <nl> + const printing : : PdfRenderSettings & settings ) { <nl> + pdf_rendering_settings_ = settings ; <nl> + base : : File pdf_file = IPC : : PlatformFileForTransitToFile ( pdf_transit ) ; <nl> + int page_count = LoadPDF ( pdf_file . Pass ( ) ) ; <nl> + / / int page_count = 1 ; <nl> + Send ( <nl> + new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount ( page_count ) ) ; <nl> + } <nl> + <nl> + void PrintingHandler : : OnRenderPDFPagesToMetafileGetPage ( <nl> + int page_number , <nl> + IPC : : PlatformFileForTransit output_file ) { <nl> + base : : File emf_file = IPC : : PlatformFileForTransitToFile ( output_file ) ; <nl> + float scale_factor = 1 . 0f ; <nl> + bool success = <nl> + RenderPdfPageToMetafile ( page_number , emf_file . Pass ( ) , & scale_factor ) ; <nl> + Send ( new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone ( <nl> + success , scale_factor ) ) ; <nl> + } <nl> + <nl> + void PrintingHandler : : OnRenderPDFPagesToMetafileStop ( ) { <nl> + ReleaseProcessIfNeeded ( ) ; <nl> + } <nl> + <nl> + int PrintingHandler : : LoadPDF ( base : : File pdf_file ) { <nl> + int64 length64 = pdf_file . GetLength ( ) ; <nl> + if ( length64 < = 0 | | length64 > std : : numeric_limits < int > : : max ( ) ) <nl> + return 0 ; <nl> + int length = static_cast < int > ( length64 ) ; <nl> + <nl> + pdf_data_ . resize ( length ) ; <nl> + if ( length ! = pdf_file . Read ( 0 , pdf_data_ . data ( ) , pdf_data_ . size ( ) ) ) <nl> + return 0 ; <nl> + <nl> + int total_page_count = 0 ; <nl> + if ( ! chrome_pdf : : GetPDFDocInfo ( <nl> + & pdf_data_ . front ( ) , pdf_data_ . size ( ) , & total_page_count , NULL ) ) { <nl> + return 0 ; <nl> + } <nl> + return total_page_count ; <nl> + } <nl> + <nl> + bool PrintingHandler : : RenderPdfPageToMetafile ( int page_number , <nl> + base : : File output_file , <nl> + float * scale_factor ) { <nl> + printing : : Emf metafile ; <nl> + metafile . Init ( ) ; <nl> + <nl> + / / We need to scale down DC to fit an entire page into DC available area . <nl> + / / Current metafile is based on screen DC and have current screen size . <nl> + / / Writing outside of those boundaries will result in the cut - off output . <nl> + / / On metafiles ( this is the case here ) , scaling down will still record <nl> + / / original coordinates and we ' ll be able to print in full resolution . <nl> + / / Before playback we ' ll need to counter the scaling up that will happen <nl> + / / in the service ( print_system_win . cc ) . <nl> + * scale_factor = <nl> + gfx : : CalculatePageScale ( metafile . context ( ) , <nl> + pdf_rendering_settings_ . area ( ) . right ( ) , <nl> + pdf_rendering_settings_ . area ( ) . bottom ( ) ) ; <nl> + gfx : : ScaleDC ( metafile . context ( ) , * scale_factor ) ; <nl> + <nl> + / / The underlying metafile is of type Emf and ignores the arguments passed <nl> + / / to StartPage . <nl> + metafile . StartPage ( gfx : : Size ( ) , gfx : : Rect ( ) , 1 ) ; <nl> + if ( ! chrome_pdf : : RenderPDFPageToDC ( <nl> + & pdf_data_ . front ( ) , <nl> + pdf_data_ . size ( ) , <nl> + page_number , <nl> + metafile . context ( ) , <nl> + pdf_rendering_settings_ . dpi ( ) , <nl> + pdf_rendering_settings_ . area ( ) . x ( ) , <nl> + pdf_rendering_settings_ . area ( ) . y ( ) , <nl> + pdf_rendering_settings_ . area ( ) . width ( ) , <nl> + pdf_rendering_settings_ . area ( ) . height ( ) , <nl> + true , <nl> + false , <nl> + true , <nl> + true , <nl> + pdf_rendering_settings_ . autorotate ( ) ) ) { <nl> + return false ; <nl> + } <nl> + metafile . FinishPage ( ) ; <nl> + metafile . FinishDocument ( ) ; <nl> + return metafile . SaveTo ( & output_file ) ; <nl> + } <nl> + <nl> + # endif / / OS_WIN <nl> new file mode 100644 <nl> index 000000000000 . . b1f09acb9cc9 <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / utility / printing_handler . h <nl> <nl> + / / Copyright 2014 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_UTILITY_PRINTING_HANDLER_H_ <nl> + # define CHROME_UTILITY_PRINTING_HANDLER_H_ <nl> + <nl> + # include " base / compiler_specific . h " <nl> + # include " base / macros . h " <nl> + # include " chrome / utility / utility_message_handler . h " <nl> + # include " ipc / ipc_platform_file . h " <nl> + # include " printing / pdf_render_settings . h " <nl> + <nl> + # if ! defined ( ENABLE_PRINT_PREVIEW ) & & ! defined ( OS_WIN ) <nl> + # error " Windows or full printing must be enabled " <nl> + # endif <nl> + <nl> + namespace printing { <nl> + class PdfRenderSettings ; <nl> + struct PwgRasterSettings ; <nl> + struct PageRange ; <nl> + } <nl> + <nl> + / / Dispatches IPCs for printing . <nl> + class PrintingHandler : public UtilityMessageHandler { <nl> + public : <nl> + PrintingHandler ( ) ; <nl> + ~ PrintingHandler ( ) override ; <nl> + <nl> + / / IPC : : Listener : <nl> + bool OnMessageReceived ( const IPC : : Message & message ) override ; <nl> + <nl> + private : <nl> + / / IPC message handlers . <nl> + # if defined ( OS_WIN ) <nl> + void OnRenderPDFPagesToMetafile ( IPC : : PlatformFileForTransit pdf_transit , <nl> + const printing : : PdfRenderSettings & settings ) ; <nl> + void OnRenderPDFPagesToMetafileGetPage ( <nl> + int page_number , <nl> + IPC : : PlatformFileForTransit output_file ) ; <nl> + void OnRenderPDFPagesToMetafileStop ( ) ; <nl> + # endif / / OS_WIN <nl> + <nl> + # if defined ( OS_WIN ) <nl> + int LoadPDF ( base : : File pdf_file ) ; <nl> + bool RenderPdfPageToMetafile ( int page_number , <nl> + base : : File output_file , <nl> + float * scale_factor ) ; <nl> + # endif / / OS_WIN <nl> + <nl> + # if defined ( OS_WIN ) <nl> + std : : vector < char > pdf_data_ ; <nl> + printing : : PdfRenderSettings pdf_rendering_settings_ ; <nl> + # endif <nl> + <nl> + DISALLOW_COPY_AND_ASSIGN ( PrintingHandler ) ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_UTILITY_PRINTING_HANDLER_H_ <nl> new file mode 100644 <nl> index 000000000000 . . 3ccff1a0fbed <nl> mmm / dev / null <nl> ppp b / chromium_src / chrome / utility / utility_message_handler . h <nl> <nl> + / / Copyright 2013 The Chromium Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + # ifndef CHROME_UTILITY_UTILITY_MESSAGE_HANDLER_H_ <nl> + # define CHROME_UTILITY_UTILITY_MESSAGE_HANDLER_H_ <nl> + <nl> + namespace IPC { <nl> + class Message ; <nl> + } <nl> + <nl> + class UtilityMessageHandler { <nl> + public : <nl> + virtual ~ UtilityMessageHandler ( ) { } <nl> + <nl> + / / Called when a message is received . Returns true iff the message was <nl> + / / handled . <nl> + virtual bool OnMessageReceived ( const IPC : : Message & message ) = 0 ; <nl> + } ; <nl> + <nl> + # endif / / CHROME_UTILITY_UTILITY_MESSAGE_HANDLER_H_ <nl> mmm a / docs / api / accelerator . md <nl> ppp b / docs / api / accelerator . md <nl> On Linux and Windows , the ` Command ` key would not have any effect , you can <nl> use ` CommandOrControl ` which represents ` Command ` on OS X and ` Control ` on <nl> Linux and Windows to define some accelerators . <nl> <nl> + The ` Super ` key is mapped to the ` Windows ` key on Windows and Linux and <nl> + ` Cmd ` on OS X . <nl> + <nl> # # Available modifiers <nl> <nl> * ` Command ` ( or ` Cmd ` for short ) <nl> Linux and Windows to define some accelerators . <nl> * ` CommandOrControl ` ( or ` CmdOrCtrl ` for short ) <nl> * ` Alt ` <nl> * ` Shift ` <nl> + * ` Super ` <nl> <nl> # # Available key codes <nl> <nl> mmm a / docs / api / app . md <nl> ppp b / docs / api / app . md <nl> This method guarantees all ` beforeunload ` and ` unload ` handlers are correctly <nl> executed . It is possible that a window cancels the quitting by returning <nl> ` false ` in ` beforeunload ` handler . <nl> <nl> - # # app . terminate ( ) <nl> - <nl> - Quit the application directly , it will not try to close all windows so cleanup <nl> - code will not run . <nl> - <nl> # # app . getPath ( name ) <nl> <nl> * ` name ` String <nl> mmm a / docs / api / browser - window . md <nl> ppp b / docs / api / browser - window . md <nl> You can also create a window without chrome by using <nl> * ` type ` String - Specifies the type of the window , possible types are <nl> ` desktop ` , ` dock ` , ` toolbar ` , ` splash ` , ` notification ` . This only works on <nl> Linux . <nl> + * ` standard - window ` Boolean - Uses the OS X ' s standard window instead of the <nl> + textured window . Defaults to ` true ` . <nl> * ` web - preferences ` Object - Settings of web page ' s features <nl> * ` javascript ` Boolean <nl> * ` web - security ` Boolean <nl> Returns URL of current web page . <nl> <nl> Returns the title of web page . <nl> <nl> - # # # WebContents . getFavicon ( ) <nl> - <nl> - Returns the favicon of web page as [ NativeImage ] ( native - image . md ) . <nl> - <nl> # # # WebContents . isLoading ( ) <nl> <nl> Returns whether web page is still loading resources . <nl> mmm a / docs / api / chrome - command - line - switches . md <nl> ppp b / docs / api / chrome - command - line - switches . md <nl> Like ` - - host - rules ` but these ` rules ` only apply to the host resolver . <nl> <nl> Ignore certificate related errors . <nl> <nl> + # # - - ppapi - flash - path <nl> + <nl> + Set path to pepper flash plugin for use . <nl> + <nl> + # # - - ppapi - flash - version <nl> + <nl> + Set the pepper flash version . <nl> + <nl> # # - - v = ` log_level ` <nl> <nl> Gives the default maximal active V - logging level ; 0 is the default . Normally <nl> mmm a / docs / api / protocol . md <nl> ppp b / docs / api / protocol . md <nl> Create a request job which sends a string as response . <nl> * ` encoding ` String - Default is ` UTF - 8 ` <nl> * ` data ` Buffer <nl> <nl> - Create a request job which accepts a buffer and sends a string as response . <nl> + Create a request job which sends a buffer as response . <nl> + <nl> + # # Class : protocol . RequestErrorJob ( code ) <nl> + <nl> + * ` code ` Integer <nl> + <nl> + Create a request job which sets appropriate network error message to console . <nl> + Default message is ` net : : ERR_NOT_IMPLEMENTED ` . Code should be in the following <nl> + range . <nl> + <nl> + * Ranges : <nl> + * 0 - 99 System related errors <nl> + * 100 - 199 Connection related errors <nl> + * 200 - 299 Certificate errors <nl> + * 300 - 399 HTTP errors <nl> + * 400 - 499 Cache errors <nl> + * 500 - 599 ? <nl> + * 600 - 699 FTP errors <nl> + * 700 - 799 Certificate manager errors <nl> + * 800 - 899 DNS resolver errors <nl> + <nl> + Check the [ network error list ] ( https : / / code . google . com / p / chromium / codesearch # chromium / src / net / base / net_error_list . h ) for code and message relations . <nl> mmm a / docs / api / remote . md <nl> ppp b / docs / api / remote . md <nl> Primary value types like strings and numbers , however , are sent by copy . <nl> <nl> # # Passing callbacks to the main process <nl> <nl> - Some APIs in the main process accept callbacks , and it would be attempting to <nl> + Some APIs in the main process accept callbacks , and it would be tempting to <nl> pass callbacks when calling a remote function . The ` remote ` module does support <nl> doing this , but you should also be extremely careful with this . <nl> <nl> Returns the object returned by ` require ( module ) ` in the main process . <nl> Returns the [ BrowserWindow ] ( browser - window . md ) object which this web page <nl> belongs to . <nl> <nl> + # # remote . getCurrentWebContent ( ) <nl> + <nl> + Returns the WebContents object of this web page . <nl> + <nl> # # remote . getGlobal ( name ) <nl> <nl> * ` name ` String <nl> mmm a / docs / api / web - view - tag . md <nl> ppp b / docs / api / web - view - tag . md <nl> Returns URL of guest page . <nl> <nl> Returns the title of guest page . <nl> <nl> - # # # ` < webview > ` . getFavicon ( ) <nl> - <nl> - Returns the favicon of guest page as dataUrl . <nl> - <nl> # # # ` < webview > ` . isLoading ( ) <nl> <nl> Returns whether guest page is still loading resources . <nl> mmm a / filenames . gypi <nl> ppp b / filenames . gypi <nl> <nl> ' atom / renderer / atom_renderer_client . h ' , <nl> ' atom / renderer / guest_view_container . cc ' , <nl> ' atom / renderer / guest_view_container . h ' , <nl> + ' atom / utility / atom_content_utility_client . cc ' , <nl> + ' atom / utility / atom_content_utility_client . h ' , <nl> ' chromium_src / chrome / browser / browser_process . cc ' , <nl> ' chromium_src / chrome / browser / browser_process . h ' , <nl> ' chromium_src / chrome / browser / chrome_notification_types . h ' , <nl> <nl> ' chromium_src / chrome / browser / printing / printer_query . h ' , <nl> ' chromium_src / chrome / browser / printing / printing_message_filter . cc ' , <nl> ' chromium_src / chrome / browser / printing / printing_message_filter . h ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . cc ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / chrome_browser_pepper_host_factory . h ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_broker_message_filter . cc ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_broker_message_filter . h ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_browser_host . cc ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_browser_host . h ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . cc ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_flash_clipboard_message_filter . h ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . cc ' , <nl> + ' chromium_src / chrome / browser / renderer_host / pepper / pepper_isolated_file_system_message_filter . h ' , <nl> ' chromium_src / chrome / browser / speech / tts_controller . h ' , <nl> ' chromium_src / chrome / browser / speech / tts_controller_impl . cc ' , <nl> ' chromium_src / chrome / browser / speech / tts_controller_impl . h ' , <nl> <nl> ' chromium_src / chrome / browser / ui / views / color_chooser_aura . h ' , <nl> ' chromium_src / chrome / browser / ui / views / frame / global_menu_bar_registrar_x11 . cc ' , <nl> ' chromium_src / chrome / browser / ui / views / frame / global_menu_bar_registrar_x11 . h ' , <nl> + ' chromium_src / chrome / common / chrome_utility_messages . h ' , <nl> ' chromium_src / chrome / common / print_messages . cc ' , <nl> ' chromium_src / chrome / common / print_messages . h ' , <nl> ' chromium_src / chrome / common / tts_messages . h ' , <nl> ' chromium_src / chrome / common / tts_utterance_request . cc ' , <nl> ' chromium_src / chrome / common / tts_utterance_request . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / chrome_renderer_pepper_host_factory . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / chrome_renderer_pepper_host_factory . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_font_file_host . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_font_file_host . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_fullscreen_host . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_fullscreen_host . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_menu_host . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_menu_host . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_renderer_host . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_flash_renderer_host . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_helper . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_helper . h ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_shared_memory_message_filter . cc ' , <nl> + ' chromium_src / chrome / renderer / pepper / pepper_shared_memory_message_filter . h ' , <nl> ' chromium_src / chrome / renderer / printing / print_web_view_helper . cc ' , <nl> ' chromium_src / chrome / renderer / printing / print_web_view_helper_linux . cc ' , <nl> ' chromium_src / chrome / renderer / printing / print_web_view_helper_mac . mm ' , <nl> <nl> ' chromium_src / chrome / renderer / spellchecker / spellcheck_worditerator . h ' , <nl> ' chromium_src / chrome / renderer / tts_dispatcher . cc ' , <nl> ' chromium_src / chrome / renderer / tts_dispatcher . h ' , <nl> + ' chromium_src / chrome / utility / utility_message_handler . h ' , <nl> ' chromium_src / library_loaders / libspeechd_loader . cc ' , <nl> ' chromium_src / library_loaders / libspeechd . h ' , <nl> ' < @ ( native_mate_files ) ' , <nl> <nl> ' chromium_src / chrome / browser / ui / views / color_chooser_dialog . cc ' , <nl> ' chromium_src / chrome / browser / ui / views / color_chooser_dialog . h ' , <nl> ' chromium_src / chrome / browser / ui / views / color_chooser_win . cc ' , <nl> + ' chromium_src / chrome / browser / printing / pdf_to_emf_converter . cc ' , <nl> + ' chromium_src / chrome / browser / printing / pdf_to_emf_converter . h ' , <nl> + ' chromium_src / chrome / utility / printing_handler . cc ' , <nl> + ' chromium_src / chrome / utility / printing_handler . h ' , <nl> ] , <nl> ' framework_sources ' : [ <nl> ' atom / app / atom_library_main . h ' , <nl> mmm a / script / create - dist . py <nl> ppp b / script / create - dist . py <nl> <nl> ' icudtl . dat ' , <nl> ' libEGL . dll ' , <nl> ' libGLESv2 . dll ' , <nl> + ' msvcp120 . dll ' , <nl> + ' msvcr120 . dll ' , <nl> ' node . dll ' , <nl> ' content_resources_200_percent . pak ' , <nl> ' ui_resources_200_percent . pak ' , <nl> ' xinput1_3 . dll ' , <nl> ' natives_blob . bin ' , <nl> ' snapshot_blob . bin ' , <nl> + ' vccorlib120 . dll ' , <nl> ] , <nl> ' linux ' : [ <nl> PROJECT_NAME , # ' electron ' <nl> def main ( ) : <nl> force_build ( ) <nl> create_symbols ( ) <nl> copy_binaries ( ) <nl> - copy_chromedriver ( ) <nl> + copy_chrome_binary ( ' chromedriver ' ) <nl> + copy_chrome_binary ( ' mksnapshot ' ) <nl> copy_license ( ) <nl> <nl> if PLATFORM = = ' linux ' : <nl> def main ( ) : <nl> <nl> create_version ( ) <nl> create_dist_zip ( ) <nl> - create_chromedriver_zip ( ) <nl> + create_chrome_binary_zip ( ' chromedriver ' , get_chromedriver_version ( ) ) <nl> + create_chrome_binary_zip ( ' mksnapshot ' , ATOM_SHELL_VERSION ) <nl> create_symbols_zip ( ) <nl> <nl> <nl> def copy_binaries ( ) : <nl> symlinks = True ) <nl> <nl> <nl> - def copy_chromedriver ( ) : <nl> + def copy_chrome_binary ( binary ) : <nl> if PLATFORM = = ' win32 ' : <nl> - chromedriver = ' chromedriver . exe ' <nl> - else : <nl> - chromedriver = ' chromedriver ' <nl> - src = os . path . join ( CHROMIUM_DIR , chromedriver ) <nl> - dest = os . path . join ( DIST_DIR , chromedriver ) <nl> + binary + = ' . exe ' <nl> + src = os . path . join ( CHROMIUM_DIR , binary ) <nl> + dest = os . path . join ( DIST_DIR , binary ) <nl> <nl> # Copy file and keep the executable bit . <nl> shutil . copyfile ( src , dest ) <nl> def create_dist_zip ( ) : <nl> make_zip ( zip_file , files , dirs ) <nl> <nl> <nl> - def create_chromedriver_zip ( ) : <nl> - dist_name = ' chromedriver - { 0 } - { 1 } - { 2 } . zip ' . format ( get_chromedriver_version ( ) , <nl> - PLATFORM , get_target_arch ( ) ) <nl> + def create_chrome_binary_zip ( binary , version ) : <nl> + dist_name = ' { 0 } - { 1 } - { 2 } - { 3 } . zip ' . format ( binary , version , PLATFORM , <nl> + get_target_arch ( ) ) <nl> zip_file = os . path . join ( SOURCE_ROOT , ' dist ' , dist_name ) <nl> <nl> with scoped_cwd ( DIST_DIR ) : <nl> files = [ ' LICENSE ' ] <nl> if PLATFORM = = ' win32 ' : <nl> - files + = [ ' chromedriver . exe ' ] <nl> + files + = [ binary + ' . exe ' ] <nl> else : <nl> - files + = [ ' chromedriver ' ] <nl> + files + = [ binary ] <nl> make_zip ( zip_file , files , [ ] ) <nl> <nl> <nl> mmm a / script / lib / config . py <nl> ppp b / script / lib / config . py <nl> <nl> <nl> <nl> BASE_URL = ' http : / / gh - contractor - zcbenz . s3 . amazonaws . com / libchromiumcontent ' <nl> - LIBCHROMIUMCONTENT_COMMIT = ' 07a73a610496e4a1b4f3abc3c2fb0516187ec460 ' <nl> + LIBCHROMIUMCONTENT_COMMIT = ' 90a5b9c3792645067ad9517e60cf5eb99730e0f9 ' <nl> <nl> PLATFORM = { <nl> ' cygwin ' : ' win32 ' , <nl> mmm a / script / update - external - binaries . py <nl> ppp b / script / update - external - binaries . py <nl> <nl> import sys <nl> import os <nl> <nl> + from lib . config import get_target_arch <nl> from lib . util import safe_mkdir , rm_rf , extract_zip , tempdir , download <nl> <nl> <nl> - VERSION = ' v0 . 5 . 0 ' <nl> + VERSION = ' v0 . 7 . 0 ' <nl> SOURCE_ROOT = os . path . abspath ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) <nl> FRAMEWORKS_URL = ' http : / / github . com / atom / atom - shell - frameworks / releases ' \ <nl> ' / download / ' + VERSION <nl> def main ( ) : <nl> download_and_unzip ( ' ReactiveCocoa ' ) <nl> download_and_unzip ( ' Squirrel ' ) <nl> elif sys . platform in [ ' cygwin ' , ' win32 ' ] : <nl> - download_and_unzip ( ' directxsdk ' ) <nl> + download_and_unzip ( ' directxsdk - ' + get_target_arch ( ) ) <nl> + download_and_unzip ( ' vs2012 - crt - ' + get_target_arch ( ) ) <nl> <nl> with open ( version_file , ' w ' ) as f : <nl> f . write ( VERSION ) <nl> mmm a / script / upload . py <nl> ppp b / script / upload . py <nl> <nl> CHROMEDRIVER_NAME = ' chromedriver - { 0 } - { 1 } - { 2 } . zip ' . format ( CHROMEDRIVER_VERSION , <nl> PLATFORM , <nl> get_target_arch ( ) ) <nl> + MKSNAPSHOT_NAME = ' mksnapshot - { 0 } - { 1 } - { 2 } . zip ' . format ( ATOM_SHELL_VERSION , <nl> + PLATFORM , <nl> + get_target_arch ( ) ) <nl> <nl> <nl> def main ( ) : <nl> def main ( ) : <nl> upload_atom_shell ( github , release_id , os . path . join ( DIST_DIR , DIST_NAME ) ) <nl> upload_atom_shell ( github , release_id , os . path . join ( DIST_DIR , SYMBOLS_NAME ) ) <nl> <nl> - # Upload chromedriver for minor version update . <nl> + # Upload chromedriver and mksnapshot for minor version update . <nl> if parse_version ( args . version ) [ 2 ] = = ' 0 ' : <nl> upload_atom_shell ( github , release_id , <nl> os . path . join ( DIST_DIR , CHROMEDRIVER_NAME ) ) <nl> + upload_atom_shell ( github , release_id , <nl> + os . path . join ( DIST_DIR , MKSNAPSHOT_NAME ) ) <nl> <nl> if PLATFORM = = ' win32 ' : <nl> # Upload PDBs to Windows symbol server . <nl> mmm a / spec / api - browser - window - spec . coffee <nl> ppp b / spec / api - browser - window - spec . coffee <nl> path = require ' path ' <nl> remote = require ' remote ' <nl> http = require ' http ' <nl> url = require ' url ' <nl> + auth = require ' basic - auth ' <nl> <nl> BrowserWindow = remote . require ' browser - window ' <nl> <nl> describe ' browser - window module ' , - > <nl> w . webContents . on ' did - finish - load ' , - > <nl> w . close ( ) <nl> w . loadUrl " file : / / # { fixtures } / pages / f . html " <nl> + <nl> + describe ' basic auth ' , - > <nl> + it ' should authenticate with correct credentials ' , ( done ) - > <nl> + ipc = remote . require ' ipc ' <nl> + server = http . createServer ( req , res ) - > <nl> + action = url . parse ( req . url , true ) . pathname <nl> + if action = = ' / ' <nl> + credentials = auth ( req ) <nl> + if credentials . name = = ' test ' and credentials . pass = = ' test ' <nl> + res . end ( ' Authenticated ' ) <nl> + server . close ( ) <nl> + else if action = = ' / jquery . js ' <nl> + js = fs . readFileSync ( path . join ( __dirname , ' static ' , ' jquery - 2 . 0 . 3 . min . js ' ) ) <nl> + res . writeHead ( 200 , { ' Content - Type ' : ' text / javascript ' } ) <nl> + res . end ( js , ' utf - 8 ' ) <nl> + server . listen 62342 , ' 127 . 0 . 0 . 1 ' <nl> + ipc . on ' console - message ' , ( e , message ) - > <nl> + ipc . removeAllListeners ' console - message ' <nl> + assert . equal message , ' Authenticated ' <nl> + done ( ) <nl> + w . webContents . on ' did - finish - load ' , - > <nl> + w . close ( ) <nl> + w . loadUrl " file : / / # { fixtures } / pages / basic - auth . html " <nl> mmm a / spec / api - protocol - spec . coffee <nl> ppp b / spec / api - protocol - spec . coffee <nl> describe ' protocol module ' , - > <nl> assert false , ' Got error : ' + errorType + ' ' + error <nl> protocol . unregisterProtocol ' atom - string - job ' <nl> <nl> + it ' returns RequestErrorJob should send error ' , ( done ) - > <nl> + data = ' valar morghulis ' <nl> + job = new protocol . RequestErrorJob ( - 6 ) <nl> + handler = remote . createFunctionWithReturnValue job <nl> + protocol . registerProtocol ' atom - error - job ' , handler <nl> + <nl> + $ . ajax <nl> + url : ' atom - error - job : / / fake - host ' <nl> + success : ( response ) - > <nl> + assert false , ' should not reach here ' <nl> + error : ( xhr , errorType , error ) - > <nl> + assert errorType , ' error ' <nl> + protocol . unregisterProtocol ' atom - error - job ' <nl> + done ( ) <nl> + <nl> it ' returns RequestBufferJob should send buffer ' , ( done ) - > <nl> data = new Buffer ( " hello " ) <nl> job = new protocol . RequestBufferJob ( data : data ) <nl> new file mode 100644 <nl> index 000000000000 . . 81d5bd209cee <nl> mmm / dev / null <nl> ppp b / spec / fixtures / pages / basic - auth . html <nl> <nl> + < html > <nl> + < body > <nl> + < script src = ' http : / / 127 . 0 . 0 . 1 : 62342 / jquery . js ' > < / script > <nl> + < script type = " text / javascript " charset = " utf - 8 " > <nl> + $ . ajax ( { <nl> + type : " GET " , <nl> + url : " http : / / 127 . 0 . 0 . 1 : 62342 " , <nl> + headers : { <nl> + " Authorization " : " Basic " + btoa ( " test : test " ) <nl> + } , <nl> + success : function ( result ) { <nl> + require ( ' ipc ' ) . send ( ' console - message ' , result ) ; <nl> + } <nl> + } ) ; <nl> + < / script > <nl> + < / body > <nl> + < / html > <nl> mmm a / spec / package . json <nl> ppp b / spec / package . json <nl> <nl> " main " : " static / main . js " , <nl> " version " : " 0 . 1 . 0 " , <nl> " devDependencies " : { <nl> + " basic - auth " : " ^ 1 . 0 . 0 " , <nl> " formidable " : " 1 . 0 . 16 " , <nl> " graceful - fs " : " 3 . 0 . 5 " , <nl> " mocha " : " 2 . 1 . 0 " , <nl> mmm a / vendor / brightray <nl> ppp b / vendor / brightray <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 32ba91f830a12f6f37017797b9b65d55037ad29d <nl> + Subproject commit a929d75829270def615e342c79ea17634e8c5989 <nl>
Merge remote - tracking branch ' atom / master '
electron/electron
1c97fc79add4f4c7a0249907deee793ce08b111c
2015-05-13T00:48:15Z
mmm a / admin / static / coffee / sidebar . html <nl> ppp b / admin / static / coffee / sidebar . html <nl> < h4 > No issues < / h4 > <nl> { { # if no_issues } } <nl> < p class = " message " > All issues have been successfully resolved . < / p > <nl> { { else } } <nl> - < p class = " message " > < strong > { { num_issues } } { { pluralize_noun " issue " num_issues } } < / strong > need to be resolved < / p > <nl> + < p class = " message " > < strong > { { num_issues } } { { pluralize_noun " issue " num_issues } } < / strong > { { pluralize_verb " need " num_issues } } to be resolved < / p > <nl> { { / if } } <nl> < / div > <nl> < / div > <nl>
Fixing sidebar pluralization
rethinkdb/rethinkdb
4e442b9da1fb0839fb1c53d3815f655a00562e2d
2012-11-01T01:46:46Z
mmm a / lib / SILGen / CMakeLists . txt <nl> ppp b / lib / SILGen / CMakeLists . txt <nl> add_swift_host_library ( swiftSILGen STATIC <nl> SILGenPoly . cpp <nl> SILGenProlog . cpp <nl> SILGenStmt . cpp <nl> + SILGenSILBuilder . cpp <nl> SILGenThunk . cpp <nl> SILGenType . cpp ) <nl> target_link_libraries ( swiftSILGen PRIVATE <nl> mmm a / lib / SILGen / SILGenBuilder . cpp <nl> ppp b / lib / SILGen / SILGenBuilder . cpp <nl> SILGenModule & SILGenBuilder : : getSILGenModule ( ) const { return SGF . SGM ; } <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> SILGenBuilder : : SILGenBuilder ( SILGenFunction & SGF ) <nl> - : SILBuilder ( SGF . F ) , SGF ( SGF ) { } <nl> + : SILGenSILBuilder ( SGF ) , SGF ( SGF ) { } <nl> <nl> SILGenBuilder : : SILGenBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> SmallVectorImpl < SILInstruction * > * insertedInsts ) <nl> - : SILBuilder ( insertBB , insertedInsts ) , SGF ( SGF ) { } <nl> + : SILGenSILBuilder ( SGF , insertBB , insertedInsts ) , SGF ( SGF ) { } <nl> <nl> SILGenBuilder : : SILGenBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> SILBasicBlock : : iterator insertInst ) <nl> - : SILBuilder ( insertBB , insertInst ) , SGF ( SGF ) { } <nl> - <nl> - / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> - / / Instruction Emission + Conformance Endowed APIs <nl> - / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> - / / <nl> - / / This section contains wrappers around SILBuilder SILValue APIs that add extra <nl> - / / conformances . These are the only places where we should be accessing <nl> - / / SILBuilder APIs directly . <nl> - / / <nl> - <nl> - MetatypeInst * SILGenBuilder : : createMetatype ( SILLocation loc , SILType metatype ) { <nl> - auto theMetatype = metatype . castTo < MetatypeType > ( ) ; <nl> - / / Getting a nontrivial metatype requires forcing any conformances necessary <nl> - / / to instantiate the type . <nl> - switch ( theMetatype - > getRepresentation ( ) ) { <nl> - case MetatypeRepresentation : : Thin : <nl> - break ; <nl> - case MetatypeRepresentation : : Thick : <nl> - case MetatypeRepresentation : : ObjC : { <nl> - / / Walk the type recursively to look for substitutions we may need . <nl> - theMetatype . getInstanceType ( ) . findIf ( [ & ] ( Type t ) - > bool { <nl> - auto * decl = t - > getAnyNominal ( ) ; <nl> - if ( ! decl ) <nl> - return false ; <nl> - <nl> - if ( isa < ProtocolDecl > ( decl ) ) <nl> - return false ; <nl> - <nl> - auto * genericSig = decl - > getGenericSignature ( ) ; <nl> - if ( ! genericSig ) <nl> - return false ; <nl> - <nl> - auto subMap = t - > getContextSubstitutionMap ( getSILGenModule ( ) . SwiftModule , <nl> - decl ) ; <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subMap ) ; <nl> - return false ; <nl> - } ) ; <nl> - <nl> - break ; <nl> - } <nl> - } <nl> - <nl> - return SILBuilder : : createMetatype ( loc , metatype ) ; <nl> - } <nl> - <nl> - ApplyInst * SILGenBuilder : : createApply ( SILLocation loc , SILValue fn , <nl> - SILType substFnTy , SILType result , <nl> - SubstitutionMap subs , <nl> - ArrayRef < SILValue > args ) { <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> - return SILBuilder : : createApply ( loc , fn , subs , args , false ) ; <nl> - } <nl> - <nl> - TryApplyInst * <nl> - SILGenBuilder : : createTryApply ( SILLocation loc , SILValue fn , SILType substFnTy , <nl> - SubstitutionMap subs , ArrayRef < SILValue > args , <nl> - SILBasicBlock * normalBB , SILBasicBlock * errorBB ) { <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> - return SILBuilder : : createTryApply ( loc , fn , subs , args , normalBB , errorBB ) ; <nl> - } <nl> - <nl> - BeginApplyInst * <nl> - SILGenBuilder : : createBeginApply ( SILLocation loc , SILValue fn , <nl> - SubstitutionMap subs , <nl> - ArrayRef < SILValue > args ) { <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> - return SILBuilder : : createBeginApply ( loc , fn , subs , args , false ) ; <nl> - } <nl> - <nl> - PartialApplyInst * <nl> - SILGenBuilder : : createPartialApply ( SILLocation loc , SILValue fn , <nl> - SILType substFnTy , SubstitutionMap subs , <nl> - ArrayRef < SILValue > args , SILType closureTy ) { <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> - return SILBuilder : : createPartialApply ( <nl> - loc , fn , subs , args , <nl> - closureTy . getAs < SILFunctionType > ( ) - > getCalleeConvention ( ) ) ; <nl> - } <nl> - <nl> - <nl> - BuiltinInst * SILGenBuilder : : createBuiltin ( SILLocation loc , Identifier name , <nl> - SILType resultTy , <nl> - SubstitutionMap subs , <nl> - ArrayRef < SILValue > args ) { <nl> - getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> - return SILBuilder : : createBuiltin ( loc , name , resultTy , subs , args ) ; <nl> - } <nl> - <nl> - InitExistentialAddrInst * SILGenBuilder : : createInitExistentialAddr ( <nl> - SILLocation loc , SILValue existential , CanType formalConcreteType , <nl> - SILType loweredConcreteType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - for ( auto conformance : conformances ) <nl> - getSILGenModule ( ) . useConformance ( conformance ) ; <nl> - <nl> - return SILBuilder : : createInitExistentialAddr ( <nl> - loc , existential , formalConcreteType , loweredConcreteType , conformances ) ; <nl> - } <nl> - <nl> - InitExistentialValueInst * SILGenBuilder : : createInitExistentialValue ( <nl> - SILLocation Loc , SILType ExistentialType , CanType FormalConcreteType , <nl> - SILValue Concrete , ArrayRef < ProtocolConformanceRef > Conformances ) { <nl> - for ( auto conformance : Conformances ) <nl> - getSILGenModule ( ) . useConformance ( conformance ) ; <nl> - <nl> - return SILBuilder : : createInitExistentialValue ( <nl> - Loc , ExistentialType , FormalConcreteType , Concrete , Conformances ) ; <nl> - } <nl> - <nl> - InitExistentialMetatypeInst * SILGenBuilder : : createInitExistentialMetatype ( <nl> - SILLocation loc , SILValue metatype , SILType existentialType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - for ( auto conformance : conformances ) <nl> - getSILGenModule ( ) . useConformance ( conformance ) ; <nl> - <nl> - return SILBuilder : : createInitExistentialMetatype ( <nl> - loc , metatype , existentialType , conformances ) ; <nl> - } <nl> - <nl> - InitExistentialRefInst * SILGenBuilder : : createInitExistentialRef ( <nl> - SILLocation loc , SILType existentialType , CanType formalConcreteType , <nl> - SILValue concreteValue , ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - for ( auto conformance : conformances ) <nl> - getSILGenModule ( ) . useConformance ( conformance ) ; <nl> - <nl> - return SILBuilder : : createInitExistentialRef ( <nl> - loc , existentialType , formalConcreteType , concreteValue , conformances ) ; <nl> - } <nl> - <nl> - AllocExistentialBoxInst * SILGenBuilder : : createAllocExistentialBox ( <nl> - SILLocation loc , SILType existentialType , CanType concreteType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - for ( auto conformance : conformances ) <nl> - getSILGenModule ( ) . useConformance ( conformance ) ; <nl> - <nl> - return SILBuilder : : createAllocExistentialBox ( loc , existentialType , <nl> - concreteType , conformances ) ; <nl> - } <nl> + : SILGenSILBuilder ( SGF , insertBB , insertInst ) , SGF ( SGF ) { } <nl> <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> / / Managed Value APIs <nl> SILGenBuilder : : createConvertFunction ( SILLocation loc , ManagedValue fn , <nl> SILType resultTy , <nl> bool withoutActuallyEscaping ) { <nl> CleanupCloner cloner ( * this , fn ) ; <nl> - SILValue result = SILBuilder : : createConvertFunction ( <nl> - loc , fn . forward ( getSILGenFunction ( ) ) , resultTy , withoutActuallyEscaping ) ; <nl> + SILValue result = createConvertFunction ( loc , fn . forward ( getSILGenFunction ( ) ) , <nl> + resultTy , withoutActuallyEscaping ) ; <nl> return cloner . clone ( result ) ; <nl> } <nl> <nl> ManagedValue SILGenBuilder : : createUncheckedBitCast ( SILLocation loc , <nl> CleanupCloner cloner ( * this , value ) ; <nl> SILValue cast = createUncheckedBitCast ( loc , value . getValue ( ) , type ) ; <nl> <nl> - / / Currently SILBuilder : : createUncheckedBitCast only produces these <nl> + / / Currently createUncheckedBitCast only produces these <nl> / / instructions . We assert here to make sure if this changes , this code is <nl> / / updated . <nl> assert ( ( isa < UncheckedTrivialBitCastInst > ( cast ) | | <nl> void SILGenBuilder : : emitDestructureValueOperation ( <nl> SILLocation loc , ManagedValue value , <nl> llvm : : function_ref < void ( unsigned , ManagedValue ) > func ) { <nl> CleanupCloner cloner ( * this , value ) ; <nl> - SILBuilder : : emitDestructureValueOperation ( <nl> - loc , value . forward ( SGF ) , [ & ] ( unsigned index , SILValue subValue ) { <nl> - return func ( index , cloner . clone ( subValue ) ) ; <nl> - } ) ; <nl> + emitDestructureValueOperation ( loc , value . forward ( SGF ) , <nl> + [ & ] ( unsigned index , SILValue subValue ) { <nl> + return func ( index , cloner . clone ( subValue ) ) ; <nl> + } ) ; <nl> } <nl> <nl> ManagedValue SILGenBuilder : : createProjectBox ( SILLocation loc , ManagedValue mv , <nl> unsigned index ) { <nl> - auto * pbi = SILBuilder : : createProjectBox ( loc , mv . getValue ( ) , index ) ; <nl> + auto * pbi = createProjectBox ( loc , mv . getValue ( ) , index ) ; <nl> return ManagedValue : : forUnmanaged ( pbi ) ; <nl> } <nl> mmm a / lib / SILGen / SILGenBuilder . h <nl> ppp b / lib / SILGen / SILGenBuilder . h <nl> <nl> # include " JumpDest . h " <nl> # include " ManagedValue . h " <nl> # include " RValue . h " <nl> + # include " SILGenSILBuilder . h " <nl> # include " swift / Basic / ProfileCounter . h " <nl> - # include " swift / SIL / SILBuilder . h " <nl> <nl> namespace swift { <nl> namespace Lowering { <nl> class SGFContext ; <nl> / / / <nl> / / / The goal is to make this eventually composed with SILBuilder so that all <nl> / / / APIs only vend ManagedValues . <nl> - class SILGenBuilder : public SILBuilder { <nl> + class SILGenBuilder : public SILGenSILBuilder { <nl> SILGenFunction & SGF ; <nl> <nl> public : <nl> class SILGenBuilder : public SILBuilder { <nl> / / Create a new builder , inheriting the given builder ' s context and debug <nl> / / scope . <nl> SILGenBuilder ( SILGenBuilder & builder , SILBasicBlock * insertBB ) <nl> - : SILBuilder ( insertBB , builder . getCurrentDebugScope ( ) , <nl> - builder . getBuilderContext ( ) ) , <nl> - SGF ( builder . SGF ) <nl> - { } <nl> + : SILGenSILBuilder ( builder . SGF , insertBB , builder . getCurrentDebugScope ( ) , <nl> + builder . getBuilderContext ( ) ) , <nl> + SGF ( builder . SGF ) { } <nl> <nl> SILGenModule & getSILGenModule ( ) const ; <nl> SILGenFunction & getSILGenFunction ( ) const { return SGF ; } <nl> <nl> - / / Metatype instructions use the conformances necessary to instantiate the <nl> - / / type . <nl> - <nl> - MetatypeInst * createMetatype ( SILLocation loc , SILType metatype ) ; <nl> - <nl> - / / Generic apply instructions use the conformances necessary to form the call . <nl> - <nl> - using SILBuilder : : createApply ; <nl> - <nl> - ApplyInst * createApply ( SILLocation loc , SILValue fn , SILType SubstFnTy , <nl> - SILType result , SubstitutionMap subs , <nl> - ArrayRef < SILValue > args ) ; <nl> - <nl> - TryApplyInst * createTryApply ( SILLocation loc , SILValue fn , SILType substFnTy , <nl> - SubstitutionMap subs , <nl> - ArrayRef < SILValue > args , SILBasicBlock * normalBB , <nl> - SILBasicBlock * errorBB ) ; <nl> - <nl> - BeginApplyInst * createBeginApply ( SILLocation loc , SILValue fn , <nl> - SubstitutionMap subs , <nl> - ArrayRef < SILValue > args ) ; <nl> + using SILGenSILBuilder : : createInitExistentialValue ; <nl> + ManagedValue <nl> + createInitExistentialValue ( SILLocation loc , SILType existentialType , <nl> + CanType formalConcreteType , ManagedValue concrete , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + using SILGenSILBuilder : : createInitExistentialRef ; <nl> + ManagedValue <nl> + createInitExistentialRef ( SILLocation loc , SILType existentialType , <nl> + CanType formalConcreteType , ManagedValue concrete , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> <nl> - PartialApplyInst * createPartialApply ( SILLocation loc , SILValue fn , <nl> - SILType substFnTy , SubstitutionMap subs , <nl> - ArrayRef < SILValue > args , <nl> - SILType closureTy ) ; <nl> + using SILGenSILBuilder : : createPartialApply ; <nl> ManagedValue createPartialApply ( SILLocation loc , SILValue fn , <nl> SILType substFnTy , SubstitutionMap subs , <nl> ArrayRef < ManagedValue > args , <nl> class SILGenBuilder : public SILBuilder { <nl> closureTy ) ; <nl> } <nl> <nl> - BuiltinInst * createBuiltin ( SILLocation loc , Identifier name , SILType resultTy , <nl> - SubstitutionMap subs , ArrayRef < SILValue > args ) ; <nl> - <nl> - / / Existential containers use the conformances needed by the existential <nl> - / / box . <nl> - <nl> - InitExistentialAddrInst * <nl> - createInitExistentialAddr ( SILLocation loc , SILValue existential , <nl> - CanType formalConcreteType , <nl> - SILType loweredConcreteType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - InitExistentialValueInst * <nl> - createInitExistentialValue ( SILLocation loc , SILType existentialType , <nl> - CanType formalConcreteType , SILValue concrete , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - ManagedValue <nl> - createInitExistentialValue ( SILLocation loc , SILType existentialType , <nl> - CanType formalConcreteType , ManagedValue concrete , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - InitExistentialMetatypeInst * <nl> - createInitExistentialMetatype ( SILLocation loc , SILValue metatype , <nl> - SILType existentialType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - InitExistentialRefInst * <nl> - createInitExistentialRef ( SILLocation loc , SILType existentialType , <nl> - CanType formalConcreteType , SILValue concreteValue , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - ManagedValue <nl> - createInitExistentialRef ( SILLocation loc , SILType existentialType , <nl> - CanType formalConcreteType , ManagedValue concrete , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - AllocExistentialBoxInst * <nl> - createAllocExistentialBox ( SILLocation loc , SILType existentialType , <nl> - CanType concreteType , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - / / = = = mmm <nl> - / / Ownership Endowed APIs <nl> - / / <nl> - <nl> - using SILBuilder : : createStructExtract ; <nl> + using SILGenSILBuilder : : createStructExtract ; <nl> ManagedValue createStructExtract ( SILLocation loc , ManagedValue base , <nl> VarDecl * decl ) ; <nl> <nl> - using SILBuilder : : createRefElementAddr ; <nl> + using SILGenSILBuilder : : createRefElementAddr ; <nl> ManagedValue createRefElementAddr ( SILLocation loc , ManagedValue operand , <nl> VarDecl * field , SILType resultTy ) ; <nl> <nl> - using SILBuilder : : createCopyValue ; <nl> + using SILGenSILBuilder : : createCopyValue ; <nl> <nl> / / / Emit a + 1 copy on \ p originalValue that lives until the end of the current <nl> / / / lexical scope . <nl> class SILGenBuilder : public SILBuilder { <nl> ManagedValue createFormalAccessCopyValue ( SILLocation loc , <nl> ManagedValue originalValue ) ; <nl> <nl> - # define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE ( Name , . . . ) \ <nl> - using SILBuilder : : createCopy # # Name # # Value ; \ <nl> - ManagedValue createCopy # # Name # # Value ( SILLocation loc , \ <nl> + # define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE ( Name , . . . ) \ <nl> + using SILGenSILBuilder : : createCopy # # Name # # Value ; \ <nl> + ManagedValue createCopy # # Name # # Value ( SILLocation loc , \ <nl> ManagedValue originalValue ) ; <nl> # define UNCHECKED_REF_STORAGE ( Name , . . . ) \ <nl> ManagedValue createUnsafeCopy # # Name # # Value ( SILLocation loc , \ <nl> class SILGenBuilder : public SILBuilder { <nl> ManagedValue createOwnedPhiArgument ( SILType type ) ; <nl> ManagedValue createGuaranteedPhiArgument ( SILType type ) ; <nl> <nl> - using SILBuilder : : createMarkUninitialized ; <nl> + using SILGenSILBuilder : : createMarkUninitialized ; <nl> ManagedValue createMarkUninitialized ( ValueDecl * decl , ManagedValue operand , <nl> MarkUninitializedInst : : Kind muKind ) ; <nl> <nl> - using SILBuilder : : createAllocRef ; <nl> + using SILGenSILBuilder : : createAllocRef ; <nl> ManagedValue createAllocRef ( SILLocation loc , SILType refType , bool objc , <nl> bool canAllocOnStack , <nl> ArrayRef < SILType > elementTypes , <nl> ArrayRef < ManagedValue > elementCountOperands ) ; <nl> - using SILBuilder : : createAllocRefDynamic ; <nl> + using SILGenSILBuilder : : createAllocRefDynamic ; <nl> ManagedValue <nl> createAllocRefDynamic ( SILLocation loc , ManagedValue operand , SILType refType , <nl> bool objc , ArrayRef < SILType > elementTypes , <nl> ArrayRef < ManagedValue > elementCountOperands ) ; <nl> <nl> - using SILBuilder : : createTuple ; <nl> + using SILGenSILBuilder : : createTuple ; <nl> ManagedValue createTuple ( SILLocation loc , SILType type , <nl> ArrayRef < ManagedValue > elements ) ; <nl> - using SILBuilder : : createTupleExtract ; <nl> + using SILGenSILBuilder : : createTupleExtract ; <nl> ManagedValue createTupleExtract ( SILLocation loc , ManagedValue value , <nl> unsigned index , SILType type ) ; <nl> ManagedValue createTupleExtract ( SILLocation loc , ManagedValue value , <nl> unsigned index ) ; <nl> - using SILBuilder : : createTupleElementAddr ; <nl> + using SILGenSILBuilder : : createTupleElementAddr ; <nl> ManagedValue createTupleElementAddr ( SILLocation loc , ManagedValue addr , <nl> unsigned index , SILType type ) ; <nl> ManagedValue createTupleElementAddr ( SILLocation loc , ManagedValue addr , <nl> unsigned index ) ; <nl> <nl> - using SILBuilder : : createLoadBorrow ; <nl> + using SILGenSILBuilder : : createLoadBorrow ; <nl> ManagedValue createLoadBorrow ( SILLocation loc , ManagedValue base ) ; <nl> ManagedValue createFormalAccessLoadBorrow ( SILLocation loc , ManagedValue base ) ; <nl> <nl> - using SILBuilder : : createStoreBorrow ; <nl> + using SILGenSILBuilder : : createStoreBorrow ; <nl> void createStoreBorrow ( SILLocation loc , ManagedValue value , SILValue address ) ; <nl> <nl> / / / Create a store_borrow if we have a non - trivial value and a store [ trivial ] <nl> class SILGenBuilder : public SILBuilder { <nl> const TypeLowering & lowering , SGFContext context , <nl> llvm : : function_ref < void ( SILValue ) > rvalueEmitter ) ; <nl> <nl> - using SILBuilder : : createUncheckedEnumData ; <nl> + using SILGenSILBuilder : : createUncheckedEnumData ; <nl> ManagedValue createUncheckedEnumData ( SILLocation loc , ManagedValue operand , <nl> EnumElementDecl * element ) ; <nl> <nl> - using SILBuilder : : createUncheckedTakeEnumDataAddr ; <nl> + using SILGenSILBuilder : : createUncheckedTakeEnumDataAddr ; <nl> ManagedValue createUncheckedTakeEnumDataAddr ( SILLocation loc , ManagedValue operand , <nl> EnumElementDecl * element , SILType ty ) ; <nl> <nl> class SILGenBuilder : public SILBuilder { <nl> ManagedValue createInputFunctionArgument ( SILType type , <nl> Optional < SILLocation > loc ) ; <nl> <nl> - using SILBuilder : : createEnum ; <nl> + using SILGenSILBuilder : : createEnum ; <nl> ManagedValue createEnum ( SILLocation loc , ManagedValue payload , <nl> EnumElementDecl * decl , SILType type ) ; <nl> <nl> class SILGenBuilder : public SILBuilder { <nl> const TypeLowering & lowering , SGFContext context , <nl> llvm : : function_ref < void ( SILValue ) > rvalueEmitter ) ; <nl> <nl> - using SILBuilder : : createUnconditionalCheckedCastValue ; <nl> + using SILGenSILBuilder : : createUnconditionalCheckedCastValue ; <nl> ManagedValue <nl> createUnconditionalCheckedCastValue ( SILLocation loc , <nl> ManagedValue operand , SILType type ) ; <nl> - using SILBuilder : : createUnconditionalCheckedCast ; <nl> + using SILGenSILBuilder : : createUnconditionalCheckedCast ; <nl> ManagedValue createUnconditionalCheckedCast ( SILLocation loc , <nl> ManagedValue operand , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createCheckedCastBranch ; <nl> + using SILGenSILBuilder : : createCheckedCastBranch ; <nl> void createCheckedCastBranch ( SILLocation loc , bool isExact , <nl> ManagedValue operand , SILType type , <nl> SILBasicBlock * trueBlock , <nl> class SILGenBuilder : public SILBuilder { <nl> ProfileCounter Target1Count , <nl> ProfileCounter Target2Count ) ; <nl> <nl> - using SILBuilder : : createCheckedCastValueBranch ; <nl> + using SILGenSILBuilder : : createCheckedCastValueBranch ; <nl> void createCheckedCastValueBranch ( SILLocation loc , ManagedValue operand , <nl> SILType type , SILBasicBlock * trueBlock , <nl> SILBasicBlock * falseBlock ) ; <nl> <nl> - using SILBuilder : : createUpcast ; <nl> + using SILGenSILBuilder : : createUpcast ; <nl> ManagedValue createUpcast ( SILLocation loc , ManagedValue original , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : tryCreateUncheckedRefCast ; <nl> + using SILGenSILBuilder : : tryCreateUncheckedRefCast ; <nl> ManagedValue tryCreateUncheckedRefCast ( SILLocation loc , ManagedValue original , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createUncheckedTrivialBitCast ; <nl> + using SILGenSILBuilder : : createUncheckedTrivialBitCast ; <nl> ManagedValue createUncheckedTrivialBitCast ( SILLocation loc , <nl> ManagedValue original , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createUncheckedRefCast ; <nl> + using SILGenSILBuilder : : createUncheckedRefCast ; <nl> ManagedValue createUncheckedRefCast ( SILLocation loc , ManagedValue original , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createUncheckedAddrCast ; <nl> + using SILGenSILBuilder : : createUncheckedAddrCast ; <nl> ManagedValue createUncheckedAddrCast ( SILLocation loc , ManagedValue op , <nl> SILType resultTy ) ; <nl> <nl> - using SILBuilder : : createUncheckedBitCast ; <nl> + using SILGenSILBuilder : : createUncheckedBitCast ; <nl> ManagedValue createUncheckedBitCast ( SILLocation loc , ManagedValue original , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createOpenExistentialRef ; <nl> + using SILGenSILBuilder : : createOpenExistentialRef ; <nl> ManagedValue createOpenExistentialRef ( SILLocation loc , ManagedValue arg , <nl> SILType openedType ) ; <nl> <nl> - using SILBuilder : : createOpenExistentialValue ; <nl> + using SILGenSILBuilder : : createOpenExistentialValue ; <nl> ManagedValue createOpenExistentialValue ( SILLocation loc , <nl> ManagedValue original , SILType type ) ; <nl> <nl> - using SILBuilder : : createOpenExistentialBoxValue ; <nl> + using SILGenSILBuilder : : createOpenExistentialBoxValue ; <nl> ManagedValue createOpenExistentialBoxValue ( SILLocation loc , <nl> ManagedValue original , SILType type ) ; <nl> <nl> - using SILBuilder : : createOpenExistentialMetatype ; <nl> + using SILGenSILBuilder : : createOpenExistentialMetatype ; <nl> ManagedValue createOpenExistentialMetatype ( SILLocation loc , <nl> ManagedValue value , <nl> SILType openedType ) ; <nl> class SILGenBuilder : public SILBuilder { <nl> ManagedValue createBlockToAnyObject ( SILLocation loc , ManagedValue block , <nl> SILType type ) ; <nl> <nl> - using SILBuilder : : createOptionalSome ; <nl> + using SILGenSILBuilder : : createOptionalSome ; <nl> ManagedValue createOptionalSome ( SILLocation Loc , ManagedValue Arg ) ; <nl> ManagedValue createManagedOptionalNone ( SILLocation Loc , SILType Type ) ; <nl> <nl> class SILGenBuilder : public SILBuilder { <nl> / / are removed . <nl> ManagedValue createManagedFunctionRef ( SILLocation loc , SILFunction * f ) ; <nl> <nl> - using SILBuilder : : createConvertFunction ; <nl> + using SILGenSILBuilder : : createConvertFunction ; <nl> ManagedValue createConvertFunction ( SILLocation loc , ManagedValue fn , <nl> SILType resultTy , <nl> bool WithoutActuallyEscaping = false ) ; <nl> <nl> - using SILBuilder : : createConvertEscapeToNoEscape ; <nl> + using SILGenSILBuilder : : createConvertEscapeToNoEscape ; <nl> ManagedValue <nl> createConvertEscapeToNoEscape ( SILLocation loc , ManagedValue fn , <nl> SILType resultTy ) ; <nl> <nl> - using SILBuilder : : createStore ; <nl> + using SILGenSILBuilder : : createStore ; <nl> / / / Forward \ p value into \ p address . <nl> / / / <nl> / / / This will forward value ' s cleanup ( if it has one ) into the equivalent <nl> class SILGenBuilder : public SILBuilder { <nl> ManagedValue createStore ( SILLocation loc , ManagedValue value , <nl> SILValue address , StoreOwnershipQualifier qualifier ) ; <nl> <nl> - using SILBuilder : : createSuperMethod ; <nl> + using SILGenSILBuilder : : createSuperMethod ; <nl> ManagedValue createSuperMethod ( SILLocation loc , ManagedValue operand , <nl> SILDeclRef member , SILType methodTy ) ; <nl> <nl> - using SILBuilder : : createObjCSuperMethod ; <nl> + using SILGenSILBuilder : : createObjCSuperMethod ; <nl> ManagedValue createObjCSuperMethod ( SILLocation loc , ManagedValue operand , <nl> SILDeclRef member , SILType methodTy ) ; <nl> <nl> - using SILBuilder : : createValueMetatype ; <nl> + using SILGenSILBuilder : : createValueMetatype ; <nl> ManagedValue createValueMetatype ( SILLocation loc , SILType metatype , <nl> ManagedValue base ) ; <nl> <nl> - using SILBuilder : : createBridgeObjectToRef ; <nl> + using SILGenSILBuilder : : createBridgeObjectToRef ; <nl> ManagedValue createBridgeObjectToRef ( SILLocation loc , ManagedValue mv , <nl> SILType destType ) ; <nl> <nl> - using SILBuilder : : createRefToBridgeObject ; <nl> + using SILGenSILBuilder : : createRefToBridgeObject ; <nl> ManagedValue createRefToBridgeObject ( SILLocation loc , ManagedValue mv , <nl> SILValue bits ) ; <nl> <nl> - using SILBuilder : : createBranch ; <nl> + using SILGenSILBuilder : : createBranch ; <nl> BranchInst * createBranch ( SILLocation Loc , SILBasicBlock * TargetBlock , <nl> ArrayRef < ManagedValue > Args ) ; <nl> <nl> - using SILBuilder : : createReturn ; <nl> + using SILGenSILBuilder : : createReturn ; <nl> ReturnInst * createReturn ( SILLocation Loc , ManagedValue ReturnValue ) ; <nl> <nl> - using SILBuilder : : emitDestructureValueOperation ; <nl> + using SILGenSILBuilder : : emitDestructureValueOperation ; <nl> / / / Perform either a tuple or struct destructure and then pass its components <nl> / / / as managed value one by one with an index to the closure . <nl> void emitDestructureValueOperation ( <nl> SILLocation loc , ManagedValue value , <nl> function_ref < void ( unsigned , ManagedValue ) > func ) ; <nl> <nl> - using SILBuilder : : createProjectBox ; <nl> + using SILGenSILBuilder : : createProjectBox ; <nl> ManagedValue createProjectBox ( SILLocation loc , ManagedValue mv , <nl> unsigned index ) ; <nl> } ; <nl> new file mode 100644 <nl> index 000000000000 . . 3bd7fba4387c <nl> mmm / dev / null <nl> ppp b / lib / SILGen / SILGenSILBuilder . cpp <nl> <nl> + / / = = = mmm SILGenSILBuilder . cpp mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm = = = / / <nl> + / / <nl> + / / This source file is part of the Swift . org open source project <nl> + / / <nl> + / / Copyright ( c ) 2014 - 2018 Apple Inc . and the Swift project authors <nl> + / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> + / / <nl> + / / See https : / / swift . org / LICENSE . txt for license information <nl> + / / See https : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + # include " SILGenSILBuilder . h " <nl> + # include " SILGenFunction . h " <nl> + <nl> + using namespace swift ; <nl> + using namespace Lowering ; <nl> + <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / Utility Methods <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + SILGenModule & SILGenSILBuilder : : getSILGenModule ( ) const { return SGF . SGM ; } <nl> + <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / Constructors <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + SILGenSILBuilder : : SILGenSILBuilder ( SILGenFunction & SGF ) <nl> + : SILBuilder ( SGF . F ) , SGF ( SGF ) { } <nl> + <nl> + SILGenSILBuilder : : SILGenSILBuilder ( <nl> + SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> + SmallVectorImpl < SILInstruction * > * insertedInsts ) <nl> + : SILBuilder ( insertBB , insertedInsts ) , SGF ( SGF ) { } <nl> + <nl> + SILGenSILBuilder : : SILGenSILBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> + SILBasicBlock : : iterator insertInst ) <nl> + : SILBuilder ( insertBB , insertInst ) , SGF ( SGF ) { } <nl> + <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / Instruction Emission + Conformance Endowed APIs <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / <nl> + / / This section contains wrappers around SILBuilder SILValue APIs that add extra <nl> + / / conformances . These are the only places where we should be accessing <nl> + / / SILBuilder APIs directly . <nl> + / / <nl> + <nl> + MetatypeInst * SILGenSILBuilder : : createMetatype ( SILLocation loc , <nl> + SILType metatype ) { <nl> + auto theMetatype = metatype . castTo < MetatypeType > ( ) ; <nl> + / / Getting a nontrivial metatype requires forcing any conformances necessary <nl> + / / to instantiate the type . <nl> + switch ( theMetatype - > getRepresentation ( ) ) { <nl> + case MetatypeRepresentation : : Thin : <nl> + break ; <nl> + case MetatypeRepresentation : : Thick : <nl> + case MetatypeRepresentation : : ObjC : { <nl> + / / Walk the type recursively to look for substitutions we may need . <nl> + theMetatype . getInstanceType ( ) . findIf ( [ & ] ( Type t ) - > bool { <nl> + auto * decl = t - > getAnyNominal ( ) ; <nl> + if ( ! decl ) <nl> + return false ; <nl> + <nl> + if ( isa < ProtocolDecl > ( decl ) ) <nl> + return false ; <nl> + <nl> + auto * genericSig = decl - > getGenericSignature ( ) ; <nl> + if ( ! genericSig ) <nl> + return false ; <nl> + <nl> + auto subMap = <nl> + t - > getContextSubstitutionMap ( getSILGenModule ( ) . SwiftModule , decl ) ; <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subMap ) ; <nl> + return false ; <nl> + } ) ; <nl> + <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + return SILBuilder : : createMetatype ( loc , metatype ) ; <nl> + } <nl> + <nl> + ApplyInst * SILGenSILBuilder : : createApply ( SILLocation loc , SILValue fn , <nl> + SILType substFnTy , SILType result , <nl> + SubstitutionMap subs , <nl> + ArrayRef < SILValue > args ) { <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> + return SILBuilder : : createApply ( loc , fn , subs , args , false ) ; <nl> + } <nl> + <nl> + TryApplyInst * SILGenSILBuilder : : createTryApply ( <nl> + SILLocation loc , SILValue fn , SILType substFnTy , SubstitutionMap subs , <nl> + ArrayRef < SILValue > args , SILBasicBlock * normalBB , SILBasicBlock * errorBB ) { <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> + return SILBuilder : : createTryApply ( loc , fn , subs , args , normalBB , errorBB ) ; <nl> + } <nl> + <nl> + BeginApplyInst * SILGenSILBuilder : : createBeginApply ( SILLocation loc , SILValue fn , <nl> + SubstitutionMap subs , <nl> + ArrayRef < SILValue > args ) { <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> + return SILBuilder : : createBeginApply ( loc , fn , subs , args , false ) ; <nl> + } <nl> + <nl> + PartialApplyInst * SILGenSILBuilder : : createPartialApply ( <nl> + SILLocation loc , SILValue fn , SILType substFnTy , SubstitutionMap subs , <nl> + ArrayRef < SILValue > args , SILType closureTy ) { <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> + return SILBuilder : : createPartialApply ( <nl> + loc , fn , subs , args , <nl> + closureTy . getAs < SILFunctionType > ( ) - > getCalleeConvention ( ) ) ; <nl> + } <nl> + <nl> + BuiltinInst * SILGenSILBuilder : : createBuiltin ( SILLocation loc , Identifier name , <nl> + SILType resultTy , <nl> + SubstitutionMap subs , <nl> + ArrayRef < SILValue > args ) { <nl> + getSILGenModule ( ) . useConformancesFromSubstitutions ( subs ) ; <nl> + return SILBuilder : : createBuiltin ( loc , name , resultTy , subs , args ) ; <nl> + } <nl> + <nl> + InitExistentialAddrInst * SILGenSILBuilder : : createInitExistentialAddr ( <nl> + SILLocation loc , SILValue existential , CanType formalConcreteType , <nl> + SILType loweredConcreteType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) { <nl> + for ( auto conformance : conformances ) <nl> + getSILGenModule ( ) . useConformance ( conformance ) ; <nl> + <nl> + return SILBuilder : : createInitExistentialAddr ( <nl> + loc , existential , formalConcreteType , loweredConcreteType , conformances ) ; <nl> + } <nl> + <nl> + InitExistentialValueInst * SILGenSILBuilder : : createInitExistentialValue ( <nl> + SILLocation Loc , SILType ExistentialType , CanType FormalConcreteType , <nl> + SILValue Concrete , ArrayRef < ProtocolConformanceRef > Conformances ) { <nl> + for ( auto conformance : Conformances ) <nl> + getSILGenModule ( ) . useConformance ( conformance ) ; <nl> + <nl> + return SILBuilder : : createInitExistentialValue ( <nl> + Loc , ExistentialType , FormalConcreteType , Concrete , Conformances ) ; <nl> + } <nl> + <nl> + InitExistentialMetatypeInst * SILGenSILBuilder : : createInitExistentialMetatype ( <nl> + SILLocation loc , SILValue metatype , SILType existentialType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) { <nl> + for ( auto conformance : conformances ) <nl> + getSILGenModule ( ) . useConformance ( conformance ) ; <nl> + <nl> + return SILBuilder : : createInitExistentialMetatype ( <nl> + loc , metatype , existentialType , conformances ) ; <nl> + } <nl> + <nl> + InitExistentialRefInst * SILGenSILBuilder : : createInitExistentialRef ( <nl> + SILLocation loc , SILType existentialType , CanType formalConcreteType , <nl> + SILValue concreteValue , ArrayRef < ProtocolConformanceRef > conformances ) { <nl> + for ( auto conformance : conformances ) <nl> + getSILGenModule ( ) . useConformance ( conformance ) ; <nl> + <nl> + return SILBuilder : : createInitExistentialRef ( <nl> + loc , existentialType , formalConcreteType , concreteValue , conformances ) ; <nl> + } <nl> + <nl> + AllocExistentialBoxInst * SILGenSILBuilder : : createAllocExistentialBox ( <nl> + SILLocation loc , SILType existentialType , CanType concreteType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) { <nl> + for ( auto conformance : conformances ) <nl> + getSILGenModule ( ) . useConformance ( conformance ) ; <nl> + <nl> + return SILBuilder : : createAllocExistentialBox ( loc , existentialType , <nl> + concreteType , conformances ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 9ecdbdb35ecf <nl> mmm / dev / null <nl> ppp b / lib / SILGen / SILGenSILBuilder . h <nl> <nl> + / / = = = mmm SILGenSILBuilder . h mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - = = = / / <nl> + / / <nl> + / / This source file is part of the Swift . org open source project <nl> + / / <nl> + / / Copyright ( c ) 2014 - 2018 Apple Inc . and the Swift project authors <nl> + / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> + / / <nl> + / / See https : / / swift . org / LICENSE . txt for license information <nl> + / / See https : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + # ifndef SWIFT_SILGEN_SILGENSILBUILDER_H <nl> + # define SWIFT_SILGEN_SILGENSILBUILDER_H <nl> + <nl> + # include " swift / SIL / SILBuilder . h " <nl> + <nl> + namespace swift { <nl> + namespace Lowering { <nl> + <nl> + class SILGenFunction ; <nl> + <nl> + class SILGenSILBuilder : public SILBuilder { <nl> + SILGenFunction & SGF ; <nl> + <nl> + public : <nl> + SILGenSILBuilder ( SILGenFunction & SGF ) ; <nl> + SILGenSILBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> + SmallVectorImpl < SILInstruction * > * insertedInsts = nullptr ) ; <nl> + SILGenSILBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> + SILBasicBlock : : iterator insertInst ) ; <nl> + <nl> + / / Create a new builder , inheriting the given builder ' s context and debug <nl> + / / scope . <nl> + SILGenSILBuilder ( SILGenFunction & SGF , SILBasicBlock * insertBB , <nl> + const SILDebugScope * debugScope , <nl> + SILBuilderContext & builderCtx ) <nl> + : SILBuilder ( insertBB , debugScope , builderCtx ) , SGF ( SGF ) { } <nl> + <nl> + SILGenModule & getSILGenModule ( ) const ; <nl> + <nl> + / / Metatype instructions use the conformances necessary to instantiate the <nl> + / / type . <nl> + <nl> + MetatypeInst * createMetatype ( SILLocation loc , SILType metatype ) ; <nl> + / / Generic apply instructions use the conformances necessary to form the call . <nl> + <nl> + using SILBuilder : : createApply ; <nl> + <nl> + ApplyInst * createApply ( SILLocation loc , SILValue fn , SILType SubstFnTy , <nl> + SILType result , SubstitutionMap subs , <nl> + ArrayRef < SILValue > args ) ; <nl> + <nl> + TryApplyInst * createTryApply ( SILLocation loc , SILValue fn , SILType substFnTy , <nl> + SubstitutionMap subs , ArrayRef < SILValue > args , <nl> + SILBasicBlock * normalBB , SILBasicBlock * errorBB ) ; <nl> + <nl> + BeginApplyInst * createBeginApply ( SILLocation loc , SILValue fn , <nl> + SubstitutionMap subs , <nl> + ArrayRef < SILValue > args ) ; <nl> + <nl> + PartialApplyInst * createPartialApply ( SILLocation loc , SILValue fn , <nl> + SILType substFnTy , SubstitutionMap subs , <nl> + ArrayRef < SILValue > args , <nl> + SILType closureTy ) ; <nl> + BuiltinInst * createBuiltin ( SILLocation loc , Identifier name , SILType resultTy , <nl> + SubstitutionMap subs , ArrayRef < SILValue > args ) ; <nl> + <nl> + / / Existential containers use the conformances needed by the existential <nl> + / / box . <nl> + <nl> + InitExistentialAddrInst * <nl> + createInitExistentialAddr ( SILLocation loc , SILValue existential , <nl> + CanType formalConcreteType , <nl> + SILType loweredConcreteType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + <nl> + InitExistentialValueInst * <nl> + createInitExistentialValue ( SILLocation loc , SILType existentialType , <nl> + CanType formalConcreteType , SILValue concrete , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + <nl> + InitExistentialMetatypeInst * <nl> + createInitExistentialMetatype ( SILLocation loc , SILValue metatype , <nl> + SILType existentialType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + <nl> + InitExistentialRefInst * <nl> + createInitExistentialRef ( SILLocation loc , SILType existentialType , <nl> + CanType formalConcreteType , SILValue concreteValue , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + <nl> + AllocExistentialBoxInst * <nl> + createAllocExistentialBox ( SILLocation loc , SILType existentialType , <nl> + CanType concreteType , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + } ; <nl> + <nl> + } / / namespace Lowering <nl> + } / / namespace swift <nl> + <nl> + # endif <nl>
[ silgen ] Split off SILGenSILBuilder from SILGenBuilder and have SILGenBuilder inherit from it .
apple/swift
34196628474b6a35b3726959ead88cf099e1b3a4
2019-04-06T07:53:47Z
mmm a / buildscripts / smoke . py <nl> ppp b / buildscripts / smoke . py <nl> def skipTest ( path ) : <nl> return True <nl> if parentDir = = " dur " : # SERVER - 7317 <nl> return True <nl> + if parentDir = = " disk " : # SERVER - 7356 <nl> + return True <nl> <nl> authTestsToSkip = [ ( " sharding " , " read_pref_rs_client . js " ) , # SERVER - 6972 <nl> ( " sharding " , " sync_conn_cmd . js " ) , # SERVER - 6327 <nl>
SERVER - 7356 SERVER - 4237 Skip disk tests when running with auth
mongodb/mongo
3342a6ec9cb3a79794587c8d2927257617fbf60d
2012-10-15T15:26:29Z
new file mode 100644 <nl> index 00000000000 . . e5fe0bf8a2b <nl> mmm / dev / null <nl> ppp b / folly / experimental / cron / CrontabSelector . h <nl> <nl> + / * <nl> + * Copyright 2014 Facebook , Inc . <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an " AS IS " BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * / <nl> + <nl> + # pragma once <nl> + <nl> + # include < algorithm > <nl> + # include < vector > <nl> + # include < stdexcept > <nl> + # include < string > <nl> + # include < unordered_map > <nl> + <nl> + # include " folly / Conv . h " <nl> + # include " folly / dynamic . h " <nl> + # include " folly / Format . h " <nl> + # include " folly / json . h " <nl> + <nl> + / / Add stateful Cron support for more robustness , see README for a design . <nl> + <nl> + namespace folly { namespace cron { <nl> + <nl> + / * * <nl> + * A CrontabSelector is a wildcard for matching some periodic value ( e . g . <nl> + * days of week , years , minutes , . . . ) . This is a base class , so Cron itself <nl> + * uses a bunch of specialized descendants . <nl> + * <nl> + * The periodic values being matched are integers of varying signedness and <nl> + * bit - widths . <nl> + * <nl> + * CrontabSelector is a union type , representing either : <nl> + * - A list of one or more values to match . E . g . January & March . <nl> + * - A start , an end , and an interval . This range type does not wrap : <nl> + * starting from Tuesday with an interval of 6 is equivalent to only <nl> + * Tuesday . <nl> + * <nl> + * A selector knows its minimum and maximum permissible value . For example , <nl> + * a day - of - month is between 1 and 31 , but real months may have fewer days , <nl> + * which is handled at a higher level - - the selector is meant to apply <nl> + * uniformly to all months . <nl> + * <nl> + * A selector also supports 3 - character string - prefix aliases for the <nl> + * integer value . For example , " sun " , " Sund " , and " Sunday " would all map to <nl> + * 1 , while " sAt " is 7 . In the month type , " july " maps to 7 , etc . Note <nl> + * that these strings are not localized - - specs are English - only , but this <nl> + * is a feature , since otherwise a Cron configuration might be ambiguous <nl> + * depending on the system locale . Also note that the day - of - week numbering <nl> + * is similarly unlocalized English , so the Russians who think Sunday = = 7 <nl> + * will have to cope . <nl> + * <nl> + * Selectors are specified using JSON . Here are some month selectors : <nl> + * <nl> + * 5 / / The value 5 , or May <nl> + * " Apr " / / The value 4 , or April <nl> + * [ " Jun " , " Jul " , 12 ] / / June , July , or December <nl> + * { " interval " : 1 } / / Match any of the 12 months <nl> + * { " start " : " Aug " , " end " : 11 } / / August through November , inclusive <nl> + * { " interval " : 2 , " end " : " Jul " } / / January , March , May , or July <nl> + * <nl> + * We do not implement the traditional Cron syntax because it ' s hard to read <nl> + * and verify , and implies the presence of some Cron misfeatures that we do <nl> + * not support . A reasonable patch adding such parser would be accepted , <nl> + * however . <nl> + * / <nl> + template < typename Num > <nl> + class CrontabSelector { <nl> + public : <nl> + <nl> + CrontabSelector ( const CrontabSelector & ) = delete ; / / can neither copy <nl> + CrontabSelector & operator = ( const CrontabSelector & ) = delete ; / / nor assign <nl> + virtual ~ CrontabSelector ( ) { } <nl> + <nl> + / * * <nl> + * Initialize the selector from a JSON object ( see the class docblock ) . <nl> + * / <nl> + void loadDynamic ( const folly : : dynamic & d ) { <nl> + if ( initialized_ ) { / / This restriction could be lifted if necessary . <nl> + throw std : : runtime_error ( " loadDynamic cannot be called twice " ) ; <nl> + } <nl> + switch ( d . type ( ) ) { <nl> + case folly : : dynamic : : Type : : INT64 : <nl> + case folly : : dynamic : : Type : : STRING : <nl> + sorted_values_ . emplace_back ( parseValue ( d ) ) ; <nl> + break ; <nl> + case folly : : dynamic : : Type : : ARRAY : <nl> + for ( const auto & val : d ) { <nl> + sorted_values_ . emplace_back ( parseValue ( val ) ) ; <nl> + } <nl> + / / If somebody specifies [ ] for a selector , we have to silently <nl> + / / accept it , since PHP ' s JSON library can morph { } into [ ] , and { } <nl> + / / must mean " default selector accepting all values . " <nl> + break ; <nl> + case folly : : dynamic : : Type : : OBJECT : <nl> + for ( const auto & pair : d . items ( ) ) { <nl> + / / Interval is first so that it doesn ' t accept strings like " jan " <nl> + if ( pair . first = = " interval " ) { <nl> + interval_ = pair . second . asInt ( ) ; <nl> + if ( interval_ < 1 | | interval_ > = max_val_ - min_val_ ) { <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " interval not in [ 1 , { } ] : { } " , max_val_ - min_val_ , interval_ <nl> + ) . str ( ) ) ; <nl> + } <nl> + continue ; <nl> + } <nl> + / / For start & end , we are happy to accept string names <nl> + auto val = parseValue ( pair . second ) ; <nl> + if ( pair . first = = " start " ) { <nl> + start_ = val ; <nl> + } else if ( pair . first = = " end " ) { <nl> + end_ = val ; <nl> + } else { <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " Unknown key : { } " , pair . first <nl> + ) . str ( ) ) ; <nl> + } <nl> + } <nl> + / / If we got an empty object , no problem - - this selector will <nl> + / / follow the default of " match everything " . <nl> + break ; <nl> + default : <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " Bad type for crontab selector : { } " , d . typeName ( ) <nl> + ) . str ( ) ) ; <nl> + } <nl> + std : : sort ( sorted_values_ . begin ( ) , sorted_values_ . end ( ) ) ; <nl> + initialized_ = true ; <nl> + } <nl> + <nl> + / * * <nl> + * Returns the first t_match > = t such that t_match matches this selector . <nl> + * If no match is found , wraps around to the selector ' s first element , and <nl> + * sets the " carry " bool to true . Otherwise , that value is false . <nl> + * <nl> + * Note : no modular arithmetic happens here - - as soon as we exceed end_ , <nl> + * we simply reset to start_ . This is not the full story for <nl> + * day - of - month , so StandardCrontabItem has to do some extra work there . <nl> + * The simple " wrap to start " behavior is correct because with modular <nl> + * arithmetic a " week " selector starting on Tuesday with a stride of 6 <nl> + * would accept any day of the week , which is far more surprising than <nl> + * only accepting Tuesday . <nl> + * / <nl> + std : : pair < Num , bool > findFirstMatch ( Num t ) const { <nl> + if ( ! initialized_ ) { <nl> + throw std : : runtime_error ( " Selector not initialized " ) ; <nl> + } <nl> + <nl> + if ( ! sorted_values_ . empty ( ) ) { <nl> + / / If this were stateful , we could remember where the previous item was , <nl> + / / but as is , we incur the log ( n ) search time every time . <nl> + auto i = <nl> + std : : lower_bound ( sorted_values_ . begin ( ) , sorted_values_ . end ( ) , t ) ; <nl> + if ( i = = sorted_values_ . end ( ) ) { / / Wrap to the start <nl> + return std : : make_pair ( * sorted_values_ . begin ( ) , true ) ; <nl> + } <nl> + return std : : make_pair ( * i , false ) ; <nl> + } <nl> + <nl> + if ( t < start_ ) { <nl> + return std : : make_pair ( start_ , false ) ; <nl> + } <nl> + int64_t next = t + ( interval_ - ( t - start_ ) % interval_ ) % interval_ ; <nl> + if ( next > end_ ) { <nl> + return std : : make_pair ( start_ , true ) ; <nl> + } <nl> + return std : : make_pair ( next , false ) ; <nl> + } <nl> + <nl> + bool isInitialized ( ) const { return initialized_ ; } <nl> + <nl> + / * * <nl> + * A compact string representation for unit tests or debugging , which sort <nl> + * of emulates standard cron syntax . This function is subject to change <nl> + * without notice - - send a patch with toDynamic ( ) if you need to inspect <nl> + * the contents of a selector in production code . We will NOT fix your <nl> + * code if you are using this function . You have been warned . <nl> + * / <nl> + std : : string getPrintable ( ) const { <nl> + std : : string s ; <nl> + for ( const auto & v : sorted_values_ ) { <nl> + folly : : toAppend ( v , ' , ' , & s ) ; <nl> + } <nl> + if ( start_ ! = min_val_ | | end_ ! = max_val_ | | interval_ ! = 1 ) { <nl> + if ( ! sorted_values_ . empty ( ) ) { <nl> + s [ s . size ( ) - 1 ] = ' / ' ; <nl> + } <nl> + folly : : toAppend ( start_ , ' - ' , end_ , ' : ' , interval_ , & s ) ; <nl> + } else if ( sorted_values_ . empty ( ) ) { <nl> + folly : : toAppend ( ' * ' , & s ) ; <nl> + } else { <nl> + s . pop_back ( ) ; <nl> + } <nl> + return s ; <nl> + } <nl> + <nl> + Num getMin ( ) const { return min_val_ ; } <nl> + Num getMax ( ) const { return max_val_ ; } <nl> + <nl> + protected : <nl> + typedef std : : unordered_map < std : : string , Num > PrefixMap ; <nl> + <nl> + CrontabSelector ( Num min_val , Num max_val ) <nl> + : initialized_ ( false ) , <nl> + start_ ( min_val ) , <nl> + end_ ( max_val ) , <nl> + interval_ ( 1 ) , <nl> + min_val_ ( min_val ) , <nl> + max_val_ ( max_val ) { } <nl> + <nl> + / * * <nl> + * Converts 3 - letter string prefixes to numeric values , e . g . Jan = > 1 , Wed = > 3 <nl> + * / <nl> + virtual const PrefixMap & getPrefixMap ( ) const { return emptyPrefixMap_ ; } <nl> + <nl> + private : <nl> + Num parseValue ( const folly : : dynamic & d ) { <nl> + Num res ; <nl> + if ( d . isInt ( ) ) { <nl> + res = d . asInt ( ) ; <nl> + } else if ( d . isString ( ) ) { <nl> + / / TODO : This prefix - matching could be more robust . . . we don ' t even <nl> + / / check if the prefix map is populated with 3 - character strings . <nl> + auto s = d . asString ( ) . substr ( 0 , 3 ) . toStdString ( ) ; <nl> + std : : transform ( s . begin ( ) , s . end ( ) , s . begin ( ) , : : tolower ) ; <nl> + auto prefix_map = getPrefixMap ( ) ; <nl> + auto i = prefix_map . find ( s ) ; <nl> + if ( i = = prefix_map . end ( ) ) { <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " Cannot convert prefix to int : { } " , s <nl> + ) . str ( ) ) ; <nl> + } <nl> + res = i - > second ; <nl> + } else { <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " Cannot parse { } " , folly : : toJson ( d ) <nl> + ) . str ( ) ) ; <nl> + } <nl> + if ( res < min_val_ | | res > max_val_ ) { <nl> + throw std : : runtime_error ( folly : : format ( <nl> + " Value { } out of range [ { } , { } ] " , res , min_val_ , max_val_ <nl> + ) . str ( ) ) ; <nl> + } <nl> + return res ; <nl> + } <nl> + <nl> + bool initialized_ ; <nl> + <nl> + std : : vector < Num > sorted_values_ ; <nl> + / / These three are unused when sorted_values_ is set <nl> + Num start_ ; <nl> + Num end_ ; <nl> + Num interval_ ; <nl> + <nl> + / / Default values for start & end , also used for range - checking . <nl> + const Num min_val_ ; <nl> + const Num max_val_ ; <nl> + <nl> + / / Should be static but it ' s too hard to do that with templates . <nl> + / / TODO ( agoder ) : Make this better . <nl> + const std : : unordered_map < std : : string , Num > emptyPrefixMap_ ; <nl> + } ; <nl> + <nl> + } } <nl> new file mode 100644 <nl> index 00000000000 . . 9fbd7afa750 <nl> mmm / dev / null <nl> ppp b / folly / experimental / cron / test / test_crontab_selector . cpp <nl> <nl> + / * <nl> + * Copyright 2014 Facebook , Inc . <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an " AS IS " BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * / <nl> + <nl> + # include < gtest / gtest . h > <nl> + <nl> + # include " folly / experimental / cron / CrontabSelector . h " <nl> + # include " folly / json . h " <nl> + <nl> + using namespace folly : : cron ; <nl> + using namespace folly ; <nl> + using namespace std ; <nl> + <nl> + / / Templates lead to poor error messages , so the preprocessor rules this land <nl> + <nl> + # define check_parse_impl ( Selector , json , expected_printable ) { \ <nl> + Selector c ; \ <nl> + c . loadDynamic ( parseJson ( json ) ) ; \ <nl> + EXPECT_EQ ( expected_printable , c . getPrintable ( ) ) ; \ <nl> + } <nl> + <nl> + # define check_first_match_impl ( Selector , Num , json , t , match , carry ) { \ <nl> + Num match_ = match ; / * Make the input the right type * / \ <nl> + Selector c ; \ <nl> + c . loadDynamic ( parseJson ( json ) ) ; \ <nl> + EXPECT_EQ ( make_pair ( match_ , carry ) , c . findFirstMatch ( t ) ) ; \ <nl> + } <nl> + <nl> + # define check_parse ( json , expected_printable ) \ <nl> + check_parse_impl ( ClownCrontabSelector , json , expected_printable ) <nl> + <nl> + # define check_first_match ( json , t , match , carry ) \ <nl> + check_first_match_impl ( \ <nl> + ClownCrontabSelector , unsigned short , json , t , match , carry \ <nl> + ) <nl> + <nl> + / * * <nl> + * There are 7 clowns in the world , numbered from 1 through 7 , with the <nl> + * names listed below . <nl> + * / <nl> + class ClownCrontabSelector : public CrontabSelector < unsigned short > { <nl> + public : <nl> + ClownCrontabSelector ( ) : CrontabSelector ( 1 , 7 ) { } <nl> + protected : <nl> + virtual const PrefixMap & getPrefixMap ( ) const { return clownToInt_ ; } <nl> + private : <nl> + const static PrefixMap clownToInt_ ; <nl> + } ; <nl> + const ClownCrontabSelector : : PrefixMap ClownCrontabSelector : : clownToInt_ { <nl> + { " sun " , 1 } , / / Sunny <nl> + { " mon " , 2 } , / / Monica <nl> + { " tue " , 3 } , / / Tuelly <nl> + { " wed " , 4 } , / / Wedder <nl> + { " thu " , 5 } , / / Thurmond <nl> + { " fri " , 6 } , / / Friedrich <nl> + { " sat " , 7 } , / / Satay <nl> + } ; <nl> + <nl> + TEST ( TestCrontabSelector , CheckParseRanges ) { <nl> + check_parse ( " { } " , " * " ) ; <nl> + check_parse ( " { \ " interval \ " : 3 } " , " 1 - 7 : 3 " ) ; <nl> + check_parse ( " { \ " start \ " : 2 } " , " 2 - 7 : 1 " ) ; <nl> + check_parse ( " { \ " start \ " : \ " Sunny \ " } " , " * " ) ; <nl> + check_parse ( " { \ " end \ " : \ " Thu \ " } " , " 1 - 5 : 1 " ) ; <nl> + check_parse ( " { \ " start \ " : \ " Tuelly \ " , \ " end \ " : \ " Wed \ " } " , " 3 - 4 : 1 " ) ; <nl> + check_parse ( " { \ " end \ " : \ " Fri \ " , \ " interval \ " : 2 } " , " 1 - 6 : 2 " ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckParseValues ) { <nl> + check_parse ( " 5 " , " 5 " ) ; <nl> + check_parse ( " \ " Thu \ " " , " 5 " ) ; <nl> + check_parse ( " [ \ " Sat \ " , 1 , \ " Fri \ " ] " , " 1 , 6 , 7 " ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckMatchValues ) { <nl> + for ( int64_t i = 0 ; i < 10 ; + + i ) { / / A single value never changes <nl> + check_first_match ( " 5 " , i , 5 , i > 5 ) ; <nl> + } <nl> + <nl> + / / Now check a list of values <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 0 , 2 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 1 , 2 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 2 , 2 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 3 , 4 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 4 , 4 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 5 , 5 , false ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 6 , 2 , true ) ; <nl> + check_first_match ( " [ 2 , 4 , 5 ] " , 7 , 2 , true ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckMatchDefaultRange ) { <nl> + check_first_match ( " { } " , 0 , 1 , false ) ; <nl> + check_first_match ( " [ ] " , 1 , 1 , false ) ; <nl> + check_first_match ( " [ ] " , 6 , 6 , false ) ; <nl> + check_first_match ( " { } " , 7 , 7 , false ) ; <nl> + check_first_match ( " { } " , 8 , 1 , true ) ; <nl> + check_first_match ( " [ ] " , 10 , 1 , true ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckMatchNontrivialRange ) { <nl> + string range = " { \ " start \ " : 3 , \ " end \ " : 7 , \ " interval \ " : 2 } " ; <nl> + check_first_match ( range , 1 , 3 , false ) ; <nl> + check_first_match ( range , 2 , 3 , false ) ; <nl> + check_first_match ( range , 3 , 3 , false ) ; <nl> + check_first_match ( range , 4 , 5 , false ) ; <nl> + check_first_match ( range , 5 , 5 , false ) ; <nl> + check_first_match ( range , 6 , 7 , false ) ; <nl> + check_first_match ( range , 7 , 7 , false ) ; <nl> + check_first_match ( range , 8 , 3 , true ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckInit ) { <nl> + ClownCrontabSelector s ; <nl> + <nl> + EXPECT_THROW ( s . findFirstMatch ( 5 ) , runtime_error ) ; / / Not initialized <nl> + <nl> + / / Initialized and functional <nl> + s . loadDynamic ( dynamic : : object ( ) ) ; <nl> + EXPECT_EQ ( make_pair ( ( unsigned short ) 5 , false ) , s . findFirstMatch ( 5 ) ) ; <nl> + <nl> + / / Cannot double - initialize <nl> + EXPECT_THROW ( s . loadDynamic ( dynamic : : object ( ) ) , runtime_error ) ; <nl> + } <nl> + <nl> + TEST ( TestCrontabSelector , CheckParseErrors ) { <nl> + / / Out - of - range intervals <nl> + EXPECT_THROW ( check_parse ( " { \ " interval \ " : 0 } " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " { \ " interval \ " : - 1 } " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " { \ " interval \ " : 7 } " , " " ) , runtime_error ) ; <nl> + <nl> + / / Out - of - range start or end <nl> + EXPECT_THROW ( check_parse ( " { \ " start \ " : 0 } " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " { \ " end \ " : 8 } " , " " ) , runtime_error ) ; <nl> + <nl> + / / Problematic JSON inputs <nl> + EXPECT_THROW ( check_parse ( " { \ " bad_key \ " : 3 } " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " 0 . 1 " , " " ) , runtime_error ) ; / / no floats <nl> + <nl> + / / Invalid values <nl> + EXPECT_THROW ( check_parse ( " \ " Chicken \ " " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " \ " Th \ " " , " " ) , runtime_error ) ; / / Need > = 3 chars <nl> + EXPECT_THROW ( check_parse ( " \ " S \ " " , " " ) , runtime_error ) ; <nl> + EXPECT_THROW ( check_parse ( " { \ " start \ " : 0 . 3 } " , " " ) , runtime_error ) ; / / float <nl> + } <nl>
Part 2 : Crontab selector
facebook/folly
ad1086fcd709dc3f8dae1fffd95e485148eb39df
2014-02-21T21:40:49Z
mmm a / include / swift / Syntax / RawSyntax . h <nl> ppp b / include / swift / Syntax / RawSyntax . h <nl> enum class SourcePresence { <nl> <nl> / / / The print option to specify when printing a raw syntax node . <nl> struct SyntaxPrintOptions { <nl> + bool Visual = false ; <nl> bool PrintSyntaxKind = false ; <nl> } ; <nl> <nl> mmm a / lib / Syntax / RawSyntax . cpp <nl> ppp b / lib / Syntax / RawSyntax . cpp <nl> <nl> / / <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> + # include " swift / Basic / ColorUtils . h " <nl> # include " swift / Syntax / RawSyntax . h " <nl> # include " swift / Syntax / TokenSyntax . h " <nl> # include " llvm / Support / Casting . h " <nl> static bool isTrivialSyntaxKind ( SyntaxKind Kind ) { <nl> return false ; <nl> } <nl> } <nl> + <nl> + static void printSyntaxKind ( SyntaxKind Kind , llvm : : raw_ostream & OS , <nl> + SyntaxPrintOptions Opts , bool Open ) { <nl> + std : : unique_ptr < swift : : OSColor > Color ; <nl> + if ( Opts . Visual ) { <nl> + Color . reset ( new swift : : OSColor ( OS , llvm : : raw_ostream : : GREEN ) ) ; <nl> + } <nl> + OS < < " < " ; <nl> + if ( ! Open ) <nl> + OS < < " / " ; <nl> + dumpSyntaxKind ( OS , Kind ) ; <nl> + OS < < " > " ; <nl> + } <nl> + <nl> } / / end of anonymous namespace <nl> void RawSyntax : : print ( llvm : : raw_ostream & OS , SyntaxPrintOptions Opts ) const { <nl> const bool PrintKind = Opts . PrintSyntaxKind & & ! isToken ( ) & & <nl> ! isTrivialSyntaxKind ( Kind ) ; <nl> if ( PrintKind ) { <nl> - OS < < " < " ; <nl> - dumpSyntaxKind ( OS , Kind ) ; <nl> - OS < < " > " ; <nl> + printSyntaxKind ( Kind , OS , Opts , true ) ; <nl> } <nl> <nl> if ( const auto Tok = dyn_cast < RawTokenSyntax > ( this ) ) { <nl> void RawSyntax : : print ( llvm : : raw_ostream & OS , SyntaxPrintOptions Opts ) const { <nl> LE - > print ( OS , Opts ) ; <nl> } <nl> if ( PrintKind ) { <nl> - OS < < " < / " ; <nl> - dumpSyntaxKind ( OS , Kind ) ; <nl> - OS < < " > " ; <nl> + printSyntaxKind ( Kind , OS , Opts , false ) ; <nl> } <nl> } <nl> <nl> mmm a / tools / swift - syntax - test / swift - syntax - test . cpp <nl> ppp b / tools / swift - syntax - test / swift - syntax - test . cpp <nl> PrintNodeKind ( " print - node - kind " , <nl> llvm : : cl : : desc ( " To print syntax node kind " ) , <nl> llvm : : cl : : cat ( Category ) , <nl> llvm : : cl : : init ( false ) ) ; <nl> + static llvm : : cl : : opt < bool > <nl> + Visual ( " v " , <nl> + llvm : : cl : : desc ( " Print visually " ) , <nl> + llvm : : cl : : cat ( Category ) , <nl> + llvm : : cl : : init ( false ) ) ; <nl> } / / end namespace options <nl> <nl> namespace { <nl> int dumpParserGen ( const char * MainExecutablePath , <nl> SourceFile * SF = getSourceFile ( Instance , InputFileName , MainExecutablePath ) ; <nl> SyntaxPrintOptions Opts ; <nl> Opts . PrintSyntaxKind = options : : PrintNodeKind ; <nl> + Opts . Visual = options : : Visual ; <nl> SF - > getSyntaxRoot ( ) . print ( llvm : : outs ( ) , Opts ) ; <nl> return 0 ; <nl> } <nl>
Merge remote - tracking branch ' origin / master ' into master - next
apple/swift
188cdf61d44bbef8fe3969e0a0284191b4e00e3d
2017-10-21T23:28:57Z
mmm a / README . md <nl> ppp b / README . md <nl> <nl> <nl> mmmmmmmmmmmmmmm - - <nl> <nl> - | * * ` Linux CPU ` * * | * * ` Linux GPU ` * * | * * ` Mac OS CPU ` * * | * * ` Windows CPU ` * * | * * ` Android ` * * | <nl> - | mmmmmmmmmmmmmmm - - | mmmmmmmmmmmmmmmmmmmmm | mmmmmmmmmmmmmmmmmm | mmmmmmmmmmmmmmmmmm - | mmmmmmmmmmmmmmm | <nl> - | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - cpu ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - cpu ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - linux - gpu ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - linux - gpu ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - mac ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - mac ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - win - cmake - py ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - win - cmake - py ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - android ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - android ) [ ! [ Download ] ( https : / / api . bintray . com / packages / google / tensorflow / tensorflow / images / download . svg ) ] ( https : / / bintray . com / google / tensorflow / tensorflow / _latestVersion ) | <nl> + <nl> + | * * ` Documentation ` * * | * * ` Linux CPU ` * * | * * ` Linux GPU ` * * | * * ` Mac OS CPU ` * * | * * ` Windows CPU ` * * | * * ` Android ` * * | <nl> + | mmmmmmmmmmmmmmm - - | mmmmmmmmmmmmmmmmmmmmm | mmmmmmmmmmmmmmmmmm | mmmmmmmmmmmmmmmmmm - | mmmmmmmmmmmmmmm | mmmmmmmmmmmmmmm | <nl> + | [ ! [ Documentation ] ( https : / / img . shields . io / badge / api - reference - blue . svg ) ] ( https : / / www . tensorflow . org / api_docs / ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - cpu ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - cpu ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - linux - gpu ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - linux - gpu ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - mac ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - mac ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - win - cmake - py ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - win - cmake - py ) | [ ! [ Build Status ] ( https : / / ci . tensorflow . org / buildStatus / icon ? job = tensorflow - master - android ) ] ( https : / / ci . tensorflow . org / job / tensorflow - master - android ) [ ! [ Download ] ( https : / / api . bintray . com / packages / google / tensorflow / tensorflow / images / download . svg ) ] ( https : / / bintray . com / google / tensorflow / tensorflow / _latestVersion ) <nl> <nl> * * TensorFlow * * is an open source software library for numerical computation using <nl> data flow graphs . The graph nodes represent mathematical operations , while <nl> organization for the purposes of conducting machine learning and deep neural <nl> networks research . The system is general enough to be applicable in a wide <nl> variety of other domains , as well . <nl> <nl> - * * If you want to contribute to TensorFlow , be sure to review the [ contribution <nl> - guidelines ] ( CONTRIBUTING . md ) . This project adheres to TensorFlow ' s <nl> - [ code of conduct ] ( CODE_OF_CONDUCT . md ) . By participating , you are expected to <nl> - uphold this code . * * <nl> - <nl> - * * We use [ GitHub issues ] ( https : / / github . com / tensorflow / tensorflow / issues ) for <nl> - tracking requests and bugs . So please see <nl> - [ TensorFlow Discuss ] ( https : / / groups . google . com / a / tensorflow . org / forum / # ! forum / discuss ) for general questions <nl> - and discussion , and please direct specific questions to [ Stack Overflow ] ( https : / / stackoverflow . com / questions / tagged / tensorflow ) . * * <nl> - <nl> - The TensorFlow project strives to abide by generally accepted best practices in open - source software development : <nl> - <nl> - [ ! [ CII Best Practices ] ( https : / / bestpractices . coreinfrastructure . org / projects / 1486 / badge ) ] ( https : / / bestpractices . coreinfrastructure . org / projects / 1486 ) <nl> - <nl> # # Installation <nl> * See [ Installing TensorFlow ] ( https : / / www . tensorflow . org / get_started / os_setup . html ) for instructions on how to install our release binaries or how to build from source . * <nl> <nl> $ python <nl> > > > sess . close ( ) <nl> ` ` ` <nl> <nl> + # # Contribution guidelines <nl> + <nl> + * * If you want to contribute to TensorFlow , be sure to review the [ contribution <nl> + guidelines ] ( CONTRIBUTING . md ) . This project adheres to TensorFlow ' s <nl> + [ code of conduct ] ( CODE_OF_CONDUCT . md ) . By participating , you are expected to <nl> + uphold this code . * * <nl> + <nl> + * * We use [ GitHub issues ] ( https : / / github . com / tensorflow / tensorflow / issues ) for <nl> + tracking requests and bugs . So please see <nl> + [ TensorFlow Discuss ] ( https : / / groups . google . com / a / tensorflow . org / forum / # ! forum / discuss ) for general questions <nl> + and discussion , and please direct specific questions to [ Stack Overflow ] ( https : / / stackoverflow . com / questions / tagged / tensorflow ) . * * <nl> + <nl> + The TensorFlow project strives to abide by generally accepted best practices in open - source software development : <nl> + <nl> + [ ! [ CII Best Practices ] ( https : / / bestpractices . coreinfrastructure . org / projects / 1486 / badge ) ] ( https : / / bestpractices . coreinfrastructure . org / projects / 1486 ) <nl> + <nl> # # For more information <nl> <nl> * [ TensorFlow Website ] ( https : / / www . tensorflow . org ) <nl> mmm a / SECURITY . md <nl> ppp b / SECURITY . md <nl> v / / Fw6ZeY + HmRDFdirjD7wXtIuER4vqCryIqR6Xe9X8oJXz9L / Jhslc = <nl> <nl> # # # Known vulnerabilities <nl> <nl> - | Type | Versions affected | Reported by | Additional Information | <nl> - | mmmmmm | : mmmmmmmmmmmmmmm - - : | mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm | <nl> - | out of bounds read | < = 1 . 4 | TenCent Blade Team | [ issue report ] ( https : / / github . com / tensorflow / tensorflow / issues / 14959 ) | <nl> + | Type | Versions affected | Reported by | Additional Information | <nl> + | mmmmmmmmmmmmmmmmmm - | : mmmmmmmmmmmmmmm - - : | mmmmmmmmmmmmmmmmmm - - | mmmmmmmmmmmmmmmmmmmmmmmmmmm - - | <nl> + | out of bounds read | < = 1 . 4 | TenCent Blade Team | [ issue report ] ( https : / / github . com / tensorflow / tensorflow / issues / 14959 ) | <nl> <nl> mmm a / configure <nl> ppp b / configure <nl> if [ - z " $ PYTHON_BIN_PATH " ] ; then <nl> fi <nl> <nl> # Set all env variables <nl> - " $ PYTHON_BIN_PATH " configure . py <nl> + CONFIGURE_DIR = $ ( dirname " $ 0 " ) <nl> + " $ PYTHON_BIN_PATH " " $ { CONFIGURE_DIR } / configure . py " " $ @ " <nl> <nl> echo " Configuration finished " <nl> <nl> mmm a / configure . py <nl> ppp b / configure . py <nl> <nl> from __future__ import division <nl> from __future__ import print_function <nl> <nl> + import argparse <nl> import errno <nl> import os <nl> import platform <nl> <nl> from distutils . spawn import find_executable as which <nl> # pylint : enable = g - import - not - at - top <nl> <nl> - _TF_BAZELRC = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , <nl> - ' . tf_configure . bazelrc ' ) <nl> - _TF_WORKSPACE = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , <nl> - ' WORKSPACE ' ) <nl> _DEFAULT_CUDA_VERSION = ' 9 . 0 ' <nl> _DEFAULT_CUDNN_VERSION = ' 7 ' <nl> _DEFAULT_CUDA_COMPUTE_CAPABILITIES = ' 3 . 5 , 5 . 2 ' <nl> <nl> <nl> _DEFAULT_PROMPT_ASK_ATTEMPTS = 10 <nl> <nl> + _TF_WORKSPACE_ROOT = os . path . abspath ( os . path . dirname ( __file__ ) ) <nl> + _TF_BAZELRC_FILENAME = ' . tf_configure . bazelrc ' <nl> + _TF_BAZELRC = os . path . join ( _TF_WORKSPACE_ROOT , _TF_BAZELRC_FILENAME ) <nl> + _TF_WORKSPACE = os . path . join ( _TF_WORKSPACE_ROOT , ' WORKSPACE ' ) <nl> + <nl> <nl> class UserInputError ( Exception ) : <nl> pass <nl> def sed_in_place ( filename , old , new ) : <nl> f . write ( newdata ) <nl> <nl> <nl> - def remove_line_with ( filename , token ) : <nl> - " " " Remove lines that contain token from file . <nl> - <nl> - Args : <nl> - filename : string for filename . <nl> - token : string token to check if to remove a line from file or not . <nl> - " " " <nl> - with open ( filename , ' r ' ) as f : <nl> - filedata = f . read ( ) <nl> - <nl> - with open ( filename , ' w ' ) as f : <nl> - for line in filedata . strip ( ) . split ( ' \ n ' ) : <nl> - if token not in line : <nl> - f . write ( line + ' \ n ' ) <nl> - <nl> - <nl> def write_to_bazelrc ( line ) : <nl> with open ( _TF_BAZELRC , ' a ' ) as f : <nl> f . write ( line + ' \ n ' ) <nl> def setup_python ( environ_cp ) : <nl> environ_cp [ ' PYTHON_BIN_PATH ' ] = python_bin_path <nl> <nl> # Write tools / python_bin_path . sh <nl> - with open ( ' tools / python_bin_path . sh ' , ' w ' ) as f : <nl> + with open ( os . path . join ( <nl> + _TF_WORKSPACE_ROOT , ' tools ' , ' python_bin_path . sh ' ) , ' w ' ) as f : <nl> f . write ( ' export PYTHON_BIN_PATH = " % s " ' % python_bin_path ) <nl> <nl> <nl> - def reset_tf_configure_bazelrc ( ) : <nl> + def reset_tf_configure_bazelrc ( workspace_path ) : <nl> " " " Reset file that contains customized config settings . " " " <nl> open ( _TF_BAZELRC , ' w ' ) . close ( ) <nl> - <nl> - home = os . path . expanduser ( ' ~ ' ) <nl> - if not os . path . exists ( ' . bazelrc ' ) : <nl> - if os . path . exists ( os . path . join ( home , ' . bazelrc ' ) ) : <nl> - with open ( ' . bazelrc ' , ' a ' ) as f : <nl> - f . write ( ' import % s / . bazelrc \ n ' % home . replace ( ' \ \ ' , ' / ' ) ) <nl> + bazelrc_path = os . path . join ( workspace_path , ' . bazelrc ' ) <nl> + <nl> + data = [ ] <nl> + if os . path . exists ( bazelrc_path ) : <nl> + with open ( bazelrc_path , ' r ' ) as f : <nl> + data = f . read ( ) . splitlines ( ) <nl> + with open ( bazelrc_path , ' w ' ) as f : <nl> + for l in data : <nl> + if _TF_BAZELRC_FILENAME in l : <nl> + continue <nl> + f . write ( ' % s \ n ' % l ) <nl> + if is_windows ( ) : <nl> + tf_bazelrc_path = _TF_BAZELRC . replace ( " \ \ " , " / " ) <nl> else : <nl> - open ( ' . bazelrc ' , ' w ' ) . close ( ) <nl> - <nl> - remove_line_with ( ' . bazelrc ' , ' tf_configure ' ) <nl> - with open ( ' . bazelrc ' , ' a ' ) as f : <nl> - f . write ( ' import % workspace % / . tf_configure . bazelrc \ n ' ) <nl> + tf_bazelrc_path = _TF_BAZELRC <nl> + f . write ( ' import % s \ n ' % tf_bazelrc_path ) <nl> <nl> <nl> def cleanup_makefile ( ) : <nl> def cleanup_makefile ( ) : <nl> <nl> These files could interfere with Bazel parsing . <nl> " " " <nl> - makefile_download_dir = ' tensorflow / contrib / makefile / downloads ' <nl> + makefile_download_dir = os . path . join ( <nl> + _TF_WORKSPACE_ROOT , ' tensorflow ' , ' contrib ' , ' makefile ' , ' downloads ' ) <nl> if os . path . isdir ( makefile_download_dir ) : <nl> for root , _ , filenames in os . walk ( makefile_download_dir ) : <nl> for f in filenames : <nl> def check_bazel_version ( min_version ) : <nl> if which ( ' bazel ' ) is None : <nl> print ( ' Cannot find bazel . Please install bazel . ' ) <nl> sys . exit ( 0 ) <nl> - curr_version = run_shell ( [ ' bazel ' , ' - - batch ' , ' version ' ] ) <nl> + curr_version = run_shell ( [ ' bazel ' , ' - - batch ' , ' - - bazelrc = / dev / null ' , ' version ' ] ) <nl> <nl> for line in curr_version . split ( ' \ n ' ) : <nl> if ' Build label : ' in line : <nl> def set_cc_opt_flags ( environ_cp ) : <nl> for opt in cc_opt_flags . split ( ) : <nl> write_to_bazelrc ( ' build : opt - - copt = % s ' % opt ) <nl> # It should be safe on the same build host . <nl> - write_to_bazelrc ( ' build : opt - - host_copt = - march = native ' ) <nl> + if not is_ppc64le ( ) : <nl> + write_to_bazelrc ( ' build : opt - - host_copt = - march = native ' ) <nl> write_to_bazelrc ( ' build : opt - - define with_default_optimizations = true ' ) <nl> # TODO ( mikecase ) : Remove these default defines once we are able to get <nl> # TF Lite targets building without them . <nl> def set_host_c_compiler ( environ_cp ) : <nl> environ_cp , <nl> var_name = ' HOST_C_COMPILER ' , <nl> var_default = default_c_host_compiler , <nl> - ask_for_var = ( ' Please specify which C compiler should be used as the host ' <nl> + ask_for_var = ( ' Please specify which C compiler should be used as the host ' <nl> ' C compiler . ' ) , <nl> check_success = os . path . exists , <nl> error_msg = ' Invalid C compiler path . % s cannot be found . ' , <nl> def config_info_line ( name , help_text ) : <nl> <nl> <nl> def main ( ) : <nl> + parser = argparse . ArgumentParser ( ) <nl> + parser . add_argument ( " - - workspace " , <nl> + type = str , <nl> + default = _TF_WORKSPACE_ROOT , <nl> + help = " The absolute path to your active Bazel workspace . " ) <nl> + args = parser . parse_args ( ) <nl> + <nl> # Make a copy of os . environ to be clear when functions and getting and setting <nl> # environment variables . <nl> environ_cp = dict ( os . environ ) <nl> <nl> check_bazel_version ( ' 0 . 5 . 4 ' ) <nl> <nl> - reset_tf_configure_bazelrc ( ) <nl> + reset_tf_configure_bazelrc ( args . workspace ) <nl> cleanup_makefile ( ) <nl> setup_python ( environ_cp ) <nl> <nl> mmm a / tensorflow / cc / gradients / nn_grad . cc <nl> ppp b / tensorflow / cc / gradients / nn_grad . cc <nl> Status MaxPoolGradV2Helper ( const Scope & scope , const Operation & op , <nl> } <nl> REGISTER_GRADIENT_OP ( " MaxPoolV2 " , MaxPoolGradV2Helper ) ; <nl> <nl> + Status MaxPool3DGradHelper ( const Scope & scope , const Operation & op , <nl> + const std : : vector < Output > & grad_inputs , <nl> + std : : vector < Output > * grad_outputs ) { <nl> + std : : vector < int32 > ksize ; <nl> + std : : vector < int32 > strides ; <nl> + string padding ; <nl> + string data_format ; <nl> + auto attrs = op . output ( 0 ) . node ( ) - > attrs ( ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " ksize " , & ksize ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " strides " , & strides ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " padding " , & padding ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " data_format " , & data_format ) ) ; <nl> + MaxPool3DGrad : : Attrs grad_attrs ; <nl> + auto dx = MaxPool3DGrad ( scope , op . input ( 0 ) , op . output ( 0 ) , grad_inputs [ 0 ] , <nl> + ksize , strides , padding , <nl> + grad_attrs . DataFormat ( data_format ) ) ; <nl> + grad_outputs - > push_back ( dx ) ; <nl> + return scope . status ( ) ; <nl> + } <nl> + REGISTER_GRADIENT_OP ( " MaxPool3D " , MaxPool3DGradHelper ) ; <nl> + <nl> + Status AvgPoolGradHelper ( const Scope & scope , const Operation & op , <nl> + const std : : vector < Output > & grad_inputs , <nl> + std : : vector < Output > * grad_outputs ) { <nl> + std : : vector < int32 > ksize ; <nl> + std : : vector < int32 > strides ; <nl> + string padding ; <nl> + string data_format ; <nl> + auto attrs = op . output ( 0 ) . node ( ) - > attrs ( ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " ksize " , & ksize ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " strides " , & strides ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " padding " , & padding ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " data_format " , & data_format ) ) ; <nl> + internal : : AvgPoolGrad : : Attrs grad_attrs ; <nl> + auto dx = <nl> + internal : : AvgPoolGrad ( scope , Shape ( scope , op . input ( 0 ) ) , grad_inputs [ 0 ] , <nl> + ksize , strides , padding , <nl> + grad_attrs . DataFormat ( data_format ) ) ; <nl> + grad_outputs - > push_back ( dx ) ; <nl> + return scope . status ( ) ; <nl> + } <nl> + REGISTER_GRADIENT_OP ( " AvgPool " , AvgPoolGradHelper ) ; <nl> + <nl> + Status AvgPool3DGradHelper ( const Scope & scope , const Operation & op , <nl> + const std : : vector < Output > & grad_inputs , <nl> + std : : vector < Output > * grad_outputs ) { <nl> + std : : vector < int32 > ksize ; <nl> + std : : vector < int32 > strides ; <nl> + string padding ; <nl> + string data_format ; <nl> + auto attrs = op . output ( 0 ) . node ( ) - > attrs ( ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " ksize " , & ksize ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " strides " , & strides ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " padding " , & padding ) ) ; <nl> + TF_RETURN_IF_ERROR ( GetNodeAttr ( attrs , " data_format " , & data_format ) ) ; <nl> + AvgPool3DGrad : : Attrs grad_attrs ; <nl> + auto dx = AvgPool3DGrad ( scope , Shape ( scope , op . input ( 0 ) ) , grad_inputs [ 0 ] , <nl> + ksize , strides , padding , <nl> + grad_attrs . DataFormat ( data_format ) ) ; <nl> + grad_outputs - > push_back ( dx ) ; <nl> + return scope . status ( ) ; <nl> + } <nl> + REGISTER_GRADIENT_OP ( " AvgPool3D " , AvgPool3DGradHelper ) ; <nl> + <nl> Status LRNGradHelper ( const Scope & scope , const Operation & op , <nl> const std : : vector < Output > & grad_inputs , <nl> std : : vector < Output > * grad_outputs ) { <nl> mmm a / tensorflow / cc / gradients / nn_grad_test . cc <nl> ppp b / tensorflow / cc / gradients / nn_grad_test . cc <nl> using ops : : Elu ; <nl> using ops : : L2Loss ; <nl> using ops : : LogSoftmax ; <nl> using ops : : LRN ; <nl> + using ops : : AvgPool ; <nl> + using ops : : AvgPool3D ; <nl> using ops : : MaxPool ; <nl> using ops : : MaxPoolV2 ; <nl> + using ops : : MaxPool3D ; <nl> using ops : : Placeholder ; <nl> using ops : : Relu ; <nl> using ops : : Relu6 ; <nl> class NNGradTest : public : : testing : : Test { <nl> <nl> / / Sets tensor with random values , ensuring that the max value is largest by <nl> / / a reasonable amount . <nl> - / / This is an issue for MaxPool and MaxPoolV2 , in which perturbations by the <nl> - / / numeric gradient computation in the gradient checker can change the max <nl> - / / value if values are too close together . <nl> + / / This is an issue for MaxPool , MaxPoolV2 and MaxPool3D , in which <nl> + / / perturbations by the numeric gradient computation in the gradient checker <nl> + / / can change the max value if values are too close together . <nl> template < typename T > <nl> void SetRandomValuesWithBumpedMax ( Tensor * tensor ) { <nl> auto tensor_flat = tensor - > flat < T > ( ) ; <nl> TEST_F ( NNGradTest , MaxPoolGradV2Helper ) { <nl> RunTest ( x , x_init_value , y , y_shape ) ; <nl> } <nl> <nl> + TEST_F ( NNGradTest , MaxPool3DGradHelper ) { <nl> + TensorShape x_shape ( { 1 , 3 , 3 , 3 , 1 } ) ; <nl> + TensorShape y_shape ( { 1 , 1 , 1 , 1 , 1 } ) ; <nl> + auto x = Placeholder ( scope_ , DT_FLOAT , Placeholder : : Shape ( x_shape ) ) ; <nl> + / / Setup window and strides so that we only do one MaxPool3D . <nl> + const std : : vector < int > ksize { 1 , 3 , 3 , 3 , 1 } ; <nl> + const std : : vector < int > strides { 1 , 3 , 3 , 3 , 1 } ; <nl> + auto y = MaxPool3D ( scope_ , x , ksize , strides , " VALID " ) ; <nl> + Tensor x_init_value = Tensor ( DT_FLOAT , x_shape ) ; <nl> + SetRandomValuesWithBumpedMax < float > ( & x_init_value ) ; <nl> + RunTest ( x , x_init_value , y , y_shape ) ; <nl> + } <nl> + <nl> + TEST_F ( NNGradTest , AvgPoolGradHelper ) { <nl> + TensorShape x_shape ( { 1 , 2 , 2 , 1 } ) ; <nl> + TensorShape y_shape ( { 1 , 1 , 1 , 1 } ) ; <nl> + auto x = Placeholder ( scope_ , DT_FLOAT , Placeholder : : Shape ( x_shape ) ) ; <nl> + / / Setup window and strides so that we only do one AvgPool . <nl> + const std : : vector < int > ksize { 1 , 2 , 2 , 1 } ; <nl> + const std : : vector < int > strides { 1 , 2 , 2 , 1 } ; <nl> + auto y = AvgPool ( scope_ , x , ksize , strides , " SAME " ) ; <nl> + RunTest ( x , x_shape , y , y_shape ) ; <nl> + } <nl> + <nl> + TEST_F ( NNGradTest , AvgPool3DGradHelper ) { <nl> + TensorShape x_shape ( { 1 , 3 , 3 , 3 , 1 } ) ; <nl> + TensorShape y_shape ( { 1 , 1 , 1 , 1 , 1 } ) ; <nl> + auto x = Placeholder ( scope_ , DT_FLOAT , Placeholder : : Shape ( x_shape ) ) ; <nl> + / / Setup window and strides so that we only do one AvgPool3D . <nl> + const std : : vector < int > ksize { 1 , 3 , 3 , 3 , 1 } ; <nl> + const std : : vector < int > strides { 1 , 3 , 3 , 3 , 1 } ; <nl> + auto y = AvgPool3D ( scope_ , x , ksize , strides , " SAME " ) ; <nl> + RunTest ( x , x_shape , y , y_shape ) ; <nl> + } <nl> + <nl> TEST_F ( NNGradTest , LRN ) { <nl> TensorShape x_shape ( { 1 , 1 , 2 , 1 } ) ; <nl> auto x = Placeholder ( scope_ , DT_FLOAT , Placeholder : : Shape ( x_shape ) ) ; <nl> mmm a / tensorflow / cc / profiler / profiler . h <nl> ppp b / tensorflow / cc / profiler / profiler . h <nl> class Profiler { <nl> / / / Adds tracing information ` run_meta ` to profiler . A ` run_meta ` is <nl> / / / generated by a TensorFlow session run call . ` step ` is the key <nl> / / / to the ` run_meta ` . When calling ProfileXXX methods , caller can specify <nl> - / / / ` step ` in ` options ` to seletively profile the corresponding ` run_meta ` . <nl> + / / / ` step ` in ` options ` to selectively profile the corresponding ` run_meta ` . <nl> / / / Multiple different ` run_meta ` can be keyed by the same ` step ` in order <nl> / / / to group them together . <nl> void AddStep ( int64 step , const RunMetadata & run_meta ) ; <nl> <nl> / / / Profiles the model by organizing nodes in graph structure . <nl> - / / / Each node is an op and the nodes are contected by the op inputs / outputs . <nl> + / / / Each node is an op and the nodes are connected by the op inputs / outputs . <nl> GraphNodeProto ProfileGraph ( const Options & options ) ; <nl> <nl> / / / Profiles the model by organizing nodes in name scope structure . <nl> / / / Each node is an op , and nodes are organized by the ops ' name <nl> - / / / scope , similar to a filesystem tree . <nl> + / / / scope , similar to a file system tree . <nl> / / / E . g . / foo is the root of operation / foo / matmul_1 and foo / conv_2 . <nl> GraphNodeProto ProfileNameScope ( const Options & options ) ; <nl> <nl> mmm a / tensorflow / contrib / cmake / tests / cuda / compatibility_test . cc <nl> ppp b / tensorflow / contrib / cmake / tests / cuda / compatibility_test . cc <nl> limitations under the License . <nl> # define __CUDACC__ <nl> # include " crt / host_config . h " <nl> <nl> - int main ( void ) { return 0 ; } <nl> + int main ( void ) { <nl> + return 0 ; <nl> + } <nl> new file mode 100644 <nl> index 0000000000000 . . 4ed7268e7a921 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / feature_column / python / feature_column / sequential_feature_column . py <nl> <nl> + # Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Experimental methods for tf . feature_column sequence input . " " " <nl> + <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + <nl> + import abc <nl> + import collections <nl> + <nl> + <nl> + from tensorflow . python . feature_column import feature_column as fc <nl> + from tensorflow . python . framework import dtypes <nl> + from tensorflow . python . framework import ops <nl> + from tensorflow . python . framework import tensor_shape <nl> + from tensorflow . python . ops import array_ops <nl> + from tensorflow . python . ops import check_ops <nl> + from tensorflow . python . ops import math_ops <nl> + from tensorflow . python . ops import parsing_ops <nl> + from tensorflow . python . ops import sparse_ops <nl> + from tensorflow . python . ops import variable_scope <nl> + <nl> + # TODO ( b / 73160931 ) : Fix pydoc . <nl> + # pylint : disable = g - doc - args , missing - docstring , protected - access <nl> + # TODO ( b / 73827486 ) : Support SequenceExample . <nl> + <nl> + <nl> + def sequence_input_layer ( <nl> + features , <nl> + feature_columns , <nl> + weight_collections = None , <nl> + trainable = True , <nl> + scope = None ) : <nl> + " " " " Builds input layer for sequence input . <nl> + <nl> + All ` feature_columns ` must be sequence dense columns with the same <nl> + ` sequence_length ` . The output of this method can be fed into sequence <nl> + networks , such as RNN . <nl> + <nl> + The output of this method is a 3D ` Tensor ` of shape ` [ batch_size , T , D ] ` . <nl> + ` T ` is the maximum sequence length for this batch , which could differ from <nl> + batch to batch . <nl> + <nl> + If multiple ` feature_columns ` are given with ` Di ` ` num_elements ` each , their <nl> + outputs are concatenated . So , the final ` Tensor ` has shape <nl> + ` [ batch_size , T , D0 + D1 + . . . + Dn ] ` . <nl> + <nl> + Example : <nl> + <nl> + ` ` ` python <nl> + rating = sequence_numeric_column ( ' rating ' ) <nl> + watches = sequence_categorical_column_with_identity ( <nl> + ' watches ' , num_buckets = 1000 ) <nl> + watches_embedding = embedding_column ( watches , dimension = 10 ) <nl> + columns = [ rating , watches ] <nl> + <nl> + features = tf . parse_example ( . . . , features = make_parse_example_spec ( columns ) ) <nl> + input_layer , sequence_length = sequence_input_layer ( features , columns ) <nl> + <nl> + rnn_cell = tf . nn . rnn_cell . BasicRNNCell ( hidden_size ) <nl> + outputs , state = tf . nn . dynamic_rnn ( <nl> + rnn_cell , inputs = input_layer , sequence_length = sequence_length ) <nl> + ` ` ` <nl> + <nl> + Returns : <nl> + An ` ( input_layer , sequence_length ) ` tuple where : <nl> + - input_layer : A float ` Tensor ` of shape ` [ batch_size , T , D ] ` . <nl> + ` T ` is the maximum sequence length for this batch , which could differ <nl> + from batch to batch . ` D ` is the sum of ` num_elements ` for all <nl> + ` feature_columns ` . <nl> + - sequence_length : An int ` Tensor ` of shape ` [ batch_size ] ` . The sequence <nl> + length for each example . <nl> + Raises : <nl> + ValueError : If any of the ` feature_columns ` is the wrong type . <nl> + " " " <nl> + feature_columns = fc . _clean_feature_columns ( feature_columns ) <nl> + for c in feature_columns : <nl> + if not isinstance ( c , _SequenceDenseColumn ) : <nl> + raise ValueError ( <nl> + ' All feature_columns must be of type _SequenceDenseColumn . ' <nl> + ' Given ( type { } ) : { } ' . format ( type ( c ) , c ) ) <nl> + <nl> + with variable_scope . variable_scope ( <nl> + scope , default_name = ' sequence_input_layer ' , values = features . values ( ) ) : <nl> + builder = fc . _LazyBuilder ( features ) <nl> + output_tensors = [ ] <nl> + sequence_lengths = [ ] <nl> + ordered_columns = [ ] <nl> + for column in sorted ( feature_columns , key = lambda x : x . name ) : <nl> + ordered_columns . append ( column ) <nl> + with variable_scope . variable_scope ( <nl> + None , default_name = column . _var_scope_name ) : <nl> + dense_tensor , sequence_length = column . _get_sequence_dense_tensor ( <nl> + builder , <nl> + weight_collections = weight_collections , <nl> + trainable = trainable ) <nl> + # Flattens the final dimension to produce a 3D Tensor . <nl> + num_elements = column . _variable_shape . num_elements ( ) <nl> + shape = array_ops . shape ( dense_tensor ) <nl> + output_tensors . append ( <nl> + array_ops . reshape ( <nl> + dense_tensor , <nl> + shape = array_ops . concat ( [ shape [ : 2 ] , [ num_elements ] ] , axis = 0 ) ) ) <nl> + sequence_lengths . append ( sequence_length ) <nl> + fc . _verify_static_batch_size_equality ( output_tensors , ordered_columns ) <nl> + # TODO ( b / 73160931 ) : Verify sequence_length equality . <nl> + return array_ops . concat ( output_tensors , - 1 ) , sequence_lengths [ 0 ] <nl> + <nl> + <nl> + # TODO ( b / 73160931 ) : Add remaining categorical columns . <nl> + def sequence_categorical_column_with_identity ( <nl> + key , num_buckets , default_value = None ) : <nl> + return _SequenceCategoricalColumn ( <nl> + fc . categorical_column_with_identity ( <nl> + key = key , <nl> + num_buckets = num_buckets , <nl> + default_value = default_value ) ) <nl> + <nl> + <nl> + # TODO ( b / 73160931 ) : Merge with embedding_column <nl> + def _sequence_embedding_column ( <nl> + categorical_column , dimension , initializer = None , ckpt_to_load_from = None , <nl> + tensor_name_in_ckpt = None , max_norm = None , trainable = True ) : <nl> + if not isinstance ( categorical_column , _SequenceCategoricalColumn ) : <nl> + raise ValueError ( <nl> + ' categorical_column must be of type _SequenceCategoricalColumn . ' <nl> + ' Given ( type { } ) : { } ' . format ( <nl> + type ( categorical_column ) , categorical_column ) ) <nl> + return _SequenceEmbeddingColumn ( <nl> + fc . embedding_column ( <nl> + categorical_column , <nl> + dimension = dimension , <nl> + initializer = initializer , <nl> + ckpt_to_load_from = ckpt_to_load_from , <nl> + tensor_name_in_ckpt = tensor_name_in_ckpt , <nl> + max_norm = max_norm , <nl> + trainable = trainable ) ) <nl> + <nl> + <nl> + def sequence_numeric_column ( <nl> + key , <nl> + shape = ( 1 , ) , <nl> + default_value = 0 . , <nl> + dtype = dtypes . float32 ) : <nl> + # TODO ( b / 73160931 ) : Add validations . <nl> + return _SequenceNumericColumn ( <nl> + key , <nl> + shape = shape , <nl> + default_value = default_value , <nl> + dtype = dtype ) <nl> + <nl> + <nl> + class _SequenceDenseColumn ( fc . _FeatureColumn ) : <nl> + " " " Represents dense sequence data . " " " <nl> + <nl> + __metaclass__ = abc . ABCMeta <nl> + <nl> + TensorSequenceLengthPair = collections . namedtuple ( # pylint : disable = invalid - name <nl> + ' TensorSequenceLengthPair ' , [ ' dense_tensor ' , ' sequence_length ' ] ) <nl> + <nl> + @ abc . abstractproperty <nl> + def _variable_shape ( self ) : <nl> + " " " ` TensorShape ` without batch and sequence dimensions . " " " <nl> + pass <nl> + <nl> + @ abc . abstractmethod <nl> + def _get_sequence_dense_tensor ( <nl> + self , inputs , weight_collections = None , trainable = None ) : <nl> + " " " Returns a ` TensorSequenceLengthPair ` . " " " <nl> + pass <nl> + <nl> + <nl> + def _sequence_length_from_sparse_tensor ( sp_tensor , num_elements = 1 ) : <nl> + with ops . name_scope ( None , ' sequence_length ' ) as name_scope : <nl> + row_ids = sp_tensor . indices [ : , 0 ] <nl> + column_ids = sp_tensor . indices [ : , 1 ] <nl> + column_ids + = array_ops . ones_like ( column_ids ) <nl> + seq_length = ( <nl> + math_ops . segment_max ( column_ids , segment_ids = row_ids ) / num_elements ) <nl> + # If the last n rows do not have ids , seq_length will have shape <nl> + # [ batch_size - n ] . Pad the remaining values with zeros . <nl> + n_pad = array_ops . shape ( sp_tensor ) [ : 1 ] - array_ops . shape ( seq_length ) [ : 1 ] <nl> + padding = array_ops . zeros ( n_pad , dtype = seq_length . dtype ) <nl> + return array_ops . concat ( [ seq_length , padding ] , axis = 0 , name = name_scope ) <nl> + <nl> + <nl> + class _SequenceCategoricalColumn ( <nl> + fc . _CategoricalColumn , <nl> + collections . namedtuple ( <nl> + ' _SequenceCategoricalColumn ' , [ ' categorical_column ' ] ) ) : <nl> + <nl> + @ property <nl> + def name ( self ) : <nl> + return self . categorical_column . name <nl> + <nl> + @ property <nl> + def _parse_example_spec ( self ) : <nl> + return self . categorical_column . _parse_example_spec <nl> + <nl> + def _transform_feature ( self , inputs ) : <nl> + return self . categorical_column . _transform_feature ( inputs ) <nl> + <nl> + @ property <nl> + def _num_buckets ( self ) : <nl> + return self . categorical_column . _num_buckets <nl> + <nl> + def _get_sparse_tensors ( self , inputs , weight_collections = None , <nl> + trainable = None ) : <nl> + sparse_tensors = self . categorical_column . _get_sparse_tensors ( inputs ) <nl> + id_tensor = sparse_tensors . id_tensor <nl> + weight_tensor = sparse_tensors . weight_tensor <nl> + # Expands final dimension , so that embeddings are not combined during <nl> + # embedding lookup . <nl> + check_id_rank = check_ops . assert_equal ( <nl> + array_ops . rank ( id_tensor ) , 2 , <nl> + data = [ <nl> + ' Column { } expected ID tensor of rank 2 . ' . format ( self . name ) , <nl> + ' id_tensor shape : ' , array_ops . shape ( id_tensor ) ] ) <nl> + with ops . control_dependencies ( [ check_id_rank ] ) : <nl> + id_tensor = sparse_ops . sparse_reshape ( <nl> + id_tensor , <nl> + shape = array_ops . concat ( [ id_tensor . dense_shape , [ 1 ] ] , axis = 0 ) ) <nl> + if weight_tensor is not None : <nl> + check_weight_rank = check_ops . assert_equal ( <nl> + array_ops . rank ( weight_tensor ) , 2 , <nl> + data = [ <nl> + ' Column { } expected weight tensor of rank 2 . ' . format ( self . name ) , <nl> + ' weight_tensor shape : ' , array_ops . shape ( weight_tensor ) ] ) <nl> + with ops . control_dependencies ( [ check_weight_rank ] ) : <nl> + weight_tensor = sparse_ops . sparse_reshape ( <nl> + weight_tensor , <nl> + shape = array_ops . concat ( [ weight_tensor . dense_shape , [ 1 ] ] , axis = 0 ) ) <nl> + return fc . _CategoricalColumn . IdWeightPair ( id_tensor , weight_tensor ) <nl> + <nl> + def _sequence_length ( self , inputs ) : <nl> + sparse_tensors = self . categorical_column . _get_sparse_tensors ( inputs ) <nl> + return _sequence_length_from_sparse_tensor ( sparse_tensors . id_tensor ) <nl> + <nl> + <nl> + class _SequenceEmbeddingColumn ( <nl> + _SequenceDenseColumn , <nl> + collections . namedtuple ( ' _SequenceEmbeddingColumn ' , [ ' embedding_column ' ] ) ) : <nl> + <nl> + @ property <nl> + def name ( self ) : <nl> + return self . embedding_column . name <nl> + <nl> + @ property <nl> + def _parse_example_spec ( self ) : <nl> + return self . embedding_column . _parse_example_spec <nl> + <nl> + def _transform_feature ( self , inputs ) : <nl> + return self . embedding_column . _transform_feature ( inputs ) <nl> + <nl> + @ property <nl> + def _variable_shape ( self ) : <nl> + return self . embedding_column . _variable_shape <nl> + <nl> + def _get_sequence_dense_tensor ( <nl> + self , inputs , weight_collections = None , trainable = None ) : <nl> + dense_tensor = self . embedding_column . _get_dense_tensor ( <nl> + inputs = inputs , <nl> + weight_collections = weight_collections , <nl> + trainable = trainable ) <nl> + sequence_length = self . embedding_column . categorical_column . _sequence_length ( <nl> + inputs ) <nl> + return _SequenceDenseColumn . TensorSequenceLengthPair ( <nl> + dense_tensor = dense_tensor , sequence_length = sequence_length ) <nl> + <nl> + <nl> + class _SequenceNumericColumn ( <nl> + _SequenceDenseColumn , <nl> + collections . namedtuple ( <nl> + ' _SequenceNumericColumn ' , <nl> + [ ' key ' , ' shape ' , ' default_value ' , ' dtype ' ] ) ) : <nl> + <nl> + @ property <nl> + def name ( self ) : <nl> + return self . key <nl> + <nl> + @ property <nl> + def _parse_example_spec ( self ) : <nl> + return { self . key : parsing_ops . VarLenFeature ( self . dtype ) } <nl> + <nl> + def _transform_feature ( self , inputs ) : <nl> + return inputs . get ( self . key ) <nl> + <nl> + @ property <nl> + def _variable_shape ( self ) : <nl> + return tensor_shape . TensorShape ( self . shape ) <nl> + <nl> + def _get_sequence_dense_tensor ( <nl> + self , inputs , weight_collections = None , trainable = None ) : <nl> + # Do nothing with weight_collections and trainable since no variables are <nl> + # created in this function . <nl> + del weight_collections <nl> + del trainable <nl> + sp_tensor = inputs . get ( self ) <nl> + dense_tensor = sparse_ops . sparse_tensor_to_dense ( <nl> + sp_tensor , default_value = self . default_value ) <nl> + # Reshape into [ batch_size , T , variable_shape ] . <nl> + dense_shape = array_ops . concat ( <nl> + [ array_ops . shape ( dense_tensor ) [ : 1 ] , [ - 1 ] , self . _variable_shape ] , <nl> + axis = 0 ) <nl> + dense_tensor = array_ops . reshape ( dense_tensor , shape = dense_shape ) <nl> + sequence_length = _sequence_length_from_sparse_tensor ( <nl> + sp_tensor , num_elements = self . _variable_shape . num_elements ( ) ) <nl> + return _SequenceDenseColumn . TensorSequenceLengthPair ( <nl> + dense_tensor = dense_tensor , sequence_length = sequence_length ) <nl> + <nl> + # pylint : enable = g - doc - args , missing - docstring , protected - access <nl> new file mode 100644 <nl> index 0000000000000 . . 59674869a27c3 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / feature_column / python / feature_column / sequential_feature_column_test . py <nl> <nl> + # Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Tests for sequential_feature_column . " " " <nl> + <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + import numpy as np <nl> + <nl> + from tensorflow . contrib . feature_column . python . feature_column import sequential_feature_column as sfc <nl> + from tensorflow . python . feature_column . feature_column import _LazyBuilder <nl> + from tensorflow . python . framework import dtypes <nl> + from tensorflow . python . framework import errors <nl> + from tensorflow . python . framework import ops <nl> + from tensorflow . python . framework import sparse_tensor <nl> + from tensorflow . python . platform import test <nl> + from tensorflow . python . training import monitored_session <nl> + <nl> + <nl> + class SequenceInputLayerTest ( test . TestCase ) : <nl> + <nl> + def test_embedding_column ( self ) : <nl> + vocabulary_size = 3 <nl> + sparse_input_a = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , ids [ 2 ] <nl> + # example 1 , ids [ 0 , 1 ] <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) ) , <nl> + values = ( 2 , 0 , 1 ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + sparse_input_b = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , ids [ 1 ] <nl> + # example 1 , ids [ 2 , 0 ] <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) ) , <nl> + values = ( 1 , 2 , 0 ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + <nl> + embedding_dimension_a = 2 <nl> + embedding_values_a = ( <nl> + ( 1 . , 2 . ) , # id 0 <nl> + ( 3 . , 4 . ) , # id 1 <nl> + ( 5 . , 6 . ) # id 2 <nl> + ) <nl> + embedding_dimension_b = 3 <nl> + embedding_values_b = ( <nl> + ( 11 . , 12 . , 13 . ) , # id 0 <nl> + ( 14 . , 15 . , 16 . ) , # id 1 <nl> + ( 17 . , 18 . , 19 . ) # id 2 <nl> + ) <nl> + def _get_initializer ( embedding_dimension , embedding_values ) : <nl> + def _initializer ( shape , dtype , partition_info ) : <nl> + self . assertAllEqual ( ( vocabulary_size , embedding_dimension ) , shape ) <nl> + self . assertEqual ( dtypes . float32 , dtype ) <nl> + self . assertIsNone ( partition_info ) <nl> + return embedding_values <nl> + return _initializer <nl> + <nl> + expected_input_layer = [ <nl> + # example 0 , ids_a [ 2 ] , ids_b [ 1 ] <nl> + [ [ 5 . , 6 . , 14 . , 15 . , 16 . ] , [ 0 . , 0 . , 0 . , 0 . , 0 . ] ] , <nl> + # example 1 , ids_a [ 0 , 1 ] , ids_b [ 2 , 0 ] <nl> + [ [ 1 . , 2 . , 17 . , 18 . , 19 . ] , [ 3 . , 4 . , 11 . , 12 . , 13 . ] ] , <nl> + ] <nl> + expected_sequence_length = [ 1 , 2 ] <nl> + <nl> + categorical_column_a = sfc . sequence_categorical_column_with_identity ( <nl> + key = ' aaa ' , num_buckets = vocabulary_size ) <nl> + embedding_column_a = sfc . _sequence_embedding_column ( <nl> + categorical_column_a , dimension = embedding_dimension_a , <nl> + initializer = _get_initializer ( embedding_dimension_a , embedding_values_a ) ) <nl> + categorical_column_b = sfc . sequence_categorical_column_with_identity ( <nl> + key = ' bbb ' , num_buckets = vocabulary_size ) <nl> + embedding_column_b = sfc . _sequence_embedding_column ( <nl> + categorical_column_b , dimension = embedding_dimension_b , <nl> + initializer = _get_initializer ( embedding_dimension_b , embedding_values_b ) ) <nl> + <nl> + input_layer , sequence_length = sfc . sequence_input_layer ( <nl> + features = { <nl> + ' aaa ' : sparse_input_a , <nl> + ' bbb ' : sparse_input_b , <nl> + } , <nl> + # Test that columns are reordered alphabetically . <nl> + feature_columns = [ embedding_column_b , embedding_column_a ] ) <nl> + <nl> + global_vars = ops . get_collection ( ops . GraphKeys . GLOBAL_VARIABLES ) <nl> + self . assertItemsEqual ( <nl> + ( ' sequence_input_layer / aaa_embedding / embedding_weights : 0 ' , <nl> + ' sequence_input_layer / bbb_embedding / embedding_weights : 0 ' ) , <nl> + tuple ( [ v . name for v in global_vars ] ) ) <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( embedding_values_a , global_vars [ 0 ] . eval ( session = sess ) ) <nl> + self . assertAllEqual ( embedding_values_b , global_vars [ 1 ] . eval ( session = sess ) ) <nl> + self . assertAllEqual ( expected_input_layer , input_layer . eval ( session = sess ) ) <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_numeric_column ( self ) : <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ 0 . ] , [ 1 ] ] <nl> + # example 1 , [ [ 10 . ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 1 , 0 ) ) , <nl> + values = ( 0 . , 1 . , 10 . ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_input_layer = [ <nl> + [ [ 0 . ] , [ 1 . ] ] , <nl> + [ [ 10 . ] , [ 0 . ] ] , <nl> + ] <nl> + expected_sequence_length = [ 2 , 1 ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' ) <nl> + <nl> + input_layer , sequence_length = sfc . sequence_input_layer ( <nl> + features = { ' aaa ' : sparse_input } , <nl> + feature_columns = [ numeric_column ] ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( expected_input_layer , input_layer . eval ( session = sess ) ) <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_numeric_column_multi_dim ( self ) : <nl> + " " " Tests sequence_input_layer for multi - dimensional numeric_column . " " " <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ [ 0 . , 1 . ] , [ 2 . , 3 . ] ] , [ [ 4 . , 5 . ] , [ 6 . , 7 . ] ] ] <nl> + # example 1 , [ [ [ 10 . , 11 . ] , [ 12 . , 13 . ] ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 0 , 3 ) , ( 0 , 4 ) , ( 0 , 5 ) , ( 0 , 6 ) , ( 0 , 7 ) , <nl> + ( 1 , 0 ) , ( 1 , 1 ) , ( 1 , 2 ) , ( 1 , 3 ) ) , <nl> + values = ( 0 . , 1 . , 2 . , 3 . , 4 . , 5 . , 6 . , 7 . , 10 . , 11 . , 12 . , 13 . ) , <nl> + dense_shape = ( 2 , 8 ) ) <nl> + # The output of numeric_column . _get_dense_tensor should be flattened . <nl> + expected_input_layer = [ <nl> + [ [ 0 . , 1 . , 2 . , 3 . ] , [ 4 . , 5 . , 6 . , 7 . ] ] , <nl> + [ [ 10 . , 11 . , 12 . , 13 . ] , [ 0 . , 0 . , 0 . , 0 . ] ] , <nl> + ] <nl> + expected_sequence_length = [ 2 , 1 ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' , shape = ( 2 , 2 ) ) <nl> + <nl> + input_layer , sequence_length = sfc . sequence_input_layer ( <nl> + features = { ' aaa ' : sparse_input } , <nl> + feature_columns = [ numeric_column ] ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( expected_input_layer , input_layer . eval ( session = sess ) ) <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + <nl> + def _assert_sparse_tensor_value ( test_case , expected , actual ) : <nl> + test_case . assertEqual ( np . int64 , np . array ( actual . indices ) . dtype ) <nl> + test_case . assertAllEqual ( expected . indices , actual . indices ) <nl> + <nl> + test_case . assertEqual ( <nl> + np . array ( expected . values ) . dtype , np . array ( actual . values ) . dtype ) <nl> + test_case . assertAllEqual ( expected . values , actual . values ) <nl> + <nl> + test_case . assertEqual ( np . int64 , np . array ( actual . dense_shape ) . dtype ) <nl> + test_case . assertAllEqual ( expected . dense_shape , actual . dense_shape ) <nl> + <nl> + <nl> + class SequenceCategoricalColumnWithIdentityTest ( test . TestCase ) : <nl> + <nl> + def test_get_sparse_tensors ( self ) : <nl> + column = sfc . sequence_categorical_column_with_identity ( <nl> + ' aaa ' , num_buckets = 3 ) <nl> + inputs = sparse_tensor . SparseTensorValue ( <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) ) , <nl> + values = ( 1 , 2 , 0 ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_sparse_ids = sparse_tensor . SparseTensorValue ( <nl> + indices = ( ( 0 , 0 , 0 ) , ( 1 , 0 , 0 ) , ( 1 , 1 , 0 ) ) , <nl> + values = np . array ( ( 1 , 2 , 0 ) , dtype = np . int64 ) , <nl> + dense_shape = ( 2 , 2 , 1 ) ) <nl> + <nl> + id_weight_pair = column . _get_sparse_tensors ( _LazyBuilder ( { ' aaa ' : inputs } ) ) <nl> + <nl> + self . assertIsNone ( id_weight_pair . weight_tensor ) <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + _assert_sparse_tensor_value ( <nl> + self , <nl> + expected_sparse_ids , <nl> + id_weight_pair . id_tensor . eval ( session = sess ) ) <nl> + <nl> + def test_get_sparse_tensors_inputs3d ( self ) : <nl> + " " " Tests _get_sparse_tensors when the input is already 3D Tensor . " " " <nl> + column = sfc . sequence_categorical_column_with_identity ( <nl> + ' aaa ' , num_buckets = 3 ) <nl> + inputs = sparse_tensor . SparseTensorValue ( <nl> + indices = ( ( 0 , 0 , 0 ) , ( 1 , 0 , 0 ) , ( 1 , 1 , 0 ) ) , <nl> + values = ( 1 , 2 , 0 ) , <nl> + dense_shape = ( 2 , 2 , 1 ) ) <nl> + <nl> + with self . assertRaisesRegexp ( <nl> + errors . InvalidArgumentError , <nl> + r ' Column aaa expected ID tensor of rank 2 \ . \ s * ' <nl> + r ' id_tensor shape : \ s * \ [ 2 2 1 \ ] ' ) : <nl> + id_weight_pair = column . _get_sparse_tensors ( <nl> + _LazyBuilder ( { ' aaa ' : inputs } ) ) <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + id_weight_pair . id_tensor . eval ( session = sess ) <nl> + <nl> + def test_sequence_length ( self ) : <nl> + column = sfc . sequence_categorical_column_with_identity ( <nl> + ' aaa ' , num_buckets = 3 ) <nl> + inputs = sparse_tensor . SparseTensorValue ( <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) ) , <nl> + values = ( 1 , 2 , 0 ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_sequence_length = [ 1 , 2 ] <nl> + <nl> + sequence_length = column . _sequence_length ( _LazyBuilder ( { ' aaa ' : inputs } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length_with_zeros ( self ) : <nl> + column = sfc . sequence_categorical_column_with_identity ( <nl> + ' aaa ' , num_buckets = 3 ) <nl> + inputs = sparse_tensor . SparseTensorValue ( <nl> + indices = ( ( 1 , 0 ) , ( 3 , 0 ) , ( 3 , 1 ) ) , <nl> + values = ( 1 , 2 , 0 ) , <nl> + dense_shape = ( 5 , 2 ) ) <nl> + expected_sequence_length = [ 0 , 1 , 0 , 2 , 0 ] <nl> + <nl> + sequence_length = column . _sequence_length ( _LazyBuilder ( { ' aaa ' : inputs } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + <nl> + class SequenceEmbeddingColumnTest ( test . TestCase ) : <nl> + <nl> + def test_get_sequence_dense_tensor ( self ) : <nl> + vocabulary_size = 3 <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , ids [ 2 ] <nl> + # example 1 , ids [ 0 , 1 ] <nl> + # example 2 , ids [ ] <nl> + # example 3 , ids [ 1 ] <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) , ( 3 , 0 ) ) , <nl> + values = ( 2 , 0 , 1 , 1 ) , <nl> + dense_shape = ( 4 , 2 ) ) <nl> + <nl> + embedding_dimension = 2 <nl> + embedding_values = ( <nl> + ( 1 . , 2 . ) , # id 0 <nl> + ( 3 . , 5 . ) , # id 1 <nl> + ( 7 . , 11 . ) # id 2 <nl> + ) <nl> + def _initializer ( shape , dtype , partition_info ) : <nl> + self . assertAllEqual ( ( vocabulary_size , embedding_dimension ) , shape ) <nl> + self . assertEqual ( dtypes . float32 , dtype ) <nl> + self . assertIsNone ( partition_info ) <nl> + return embedding_values <nl> + <nl> + expected_lookups = [ <nl> + # example 0 , ids [ 2 ] <nl> + [ [ 7 . , 11 . ] , [ 0 . , 0 . ] ] , <nl> + # example 1 , ids [ 0 , 1 ] <nl> + [ [ 1 . , 2 . ] , [ 3 . , 5 . ] ] , <nl> + # example 2 , ids [ ] <nl> + [ [ 0 . , 0 . ] , [ 0 . , 0 . ] ] , <nl> + # example 3 , ids [ 1 ] <nl> + [ [ 3 . , 5 . ] , [ 0 . , 0 . ] ] , <nl> + ] <nl> + <nl> + categorical_column = sfc . sequence_categorical_column_with_identity ( <nl> + key = ' aaa ' , num_buckets = vocabulary_size ) <nl> + embedding_column = sfc . _sequence_embedding_column ( <nl> + categorical_column , dimension = embedding_dimension , <nl> + initializer = _initializer ) <nl> + <nl> + embedding_lookup , _ = embedding_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + global_vars = ops . get_collection ( ops . GraphKeys . GLOBAL_VARIABLES ) <nl> + self . assertItemsEqual ( <nl> + ( ' embedding_weights : 0 ' , ) , tuple ( [ v . name for v in global_vars ] ) ) <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( embedding_values , global_vars [ 0 ] . eval ( session = sess ) ) <nl> + self . assertAllEqual ( expected_lookups , embedding_lookup . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length ( self ) : <nl> + vocabulary_size = 3 <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , ids [ 2 ] <nl> + # example 1 , ids [ 0 , 1 ] <nl> + indices = ( ( 0 , 0 ) , ( 1 , 0 ) , ( 1 , 1 ) ) , <nl> + values = ( 2 , 0 , 1 ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_sequence_length = [ 1 , 2 ] <nl> + <nl> + categorical_column = sfc . sequence_categorical_column_with_identity ( <nl> + key = ' aaa ' , num_buckets = vocabulary_size ) <nl> + embedding_column = sfc . _sequence_embedding_column ( <nl> + categorical_column , dimension = 2 ) <nl> + <nl> + _ , sequence_length = embedding_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length_with_empty_rows ( self ) : <nl> + " " " Tests _sequence_length when some examples do not have ids . " " " <nl> + vocabulary_size = 3 <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , ids [ ] <nl> + # example 1 , ids [ 2 ] <nl> + # example 2 , ids [ 0 , 1 ] <nl> + # example 3 , ids [ ] <nl> + # example 4 , ids [ 1 ] <nl> + # example 5 , ids [ ] <nl> + indices = ( ( 1 , 0 ) , ( 2 , 0 ) , ( 2 , 1 ) , ( 4 , 0 ) ) , <nl> + values = ( 2 , 0 , 1 , 1 ) , <nl> + dense_shape = ( 6 , 2 ) ) <nl> + expected_sequence_length = [ 0 , 1 , 2 , 0 , 1 , 0 ] <nl> + <nl> + categorical_column = sfc . sequence_categorical_column_with_identity ( <nl> + key = ' aaa ' , num_buckets = vocabulary_size ) <nl> + embedding_column = sfc . _sequence_embedding_column ( <nl> + categorical_column , dimension = 2 ) <nl> + <nl> + _ , sequence_length = embedding_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + <nl> + class SequenceNumericColumnTest ( test . TestCase ) : <nl> + <nl> + def test_get_sequence_dense_tensor ( self ) : <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ 0 . ] , [ 1 ] ] <nl> + # example 1 , [ [ 10 . ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 1 , 0 ) ) , <nl> + values = ( 0 . , 1 . , 10 . ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_dense_tensor = [ <nl> + [ [ 0 . ] , [ 1 . ] ] , <nl> + [ [ 10 . ] , [ 0 . ] ] , <nl> + ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' ) <nl> + <nl> + dense_tensor , _ = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_dense_tensor , dense_tensor . eval ( session = sess ) ) <nl> + <nl> + def test_get_sequence_dense_tensor_with_shape ( self ) : <nl> + " " " Tests get_sequence_dense_tensor with shape ! = ( 1 , ) . " " " <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ 0 . , 1 . , 2 . ] , [ 3 . , 4 . , 5 . ] ] <nl> + # example 1 , [ [ 10 . , 11 . , 12 . ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 0 , 3 ) , ( 0 , 4 ) , ( 0 , 5 ) , <nl> + ( 1 , 0 ) , ( 1 , 1 ) , ( 1 , 2 ) ) , <nl> + values = ( 0 . , 1 . , 2 . , 3 . , 4 . , 5 . , 10 . , 11 . , 12 . ) , <nl> + dense_shape = ( 2 , 6 ) ) <nl> + expected_dense_tensor = [ <nl> + [ [ 0 . , 1 . , 2 . ] , [ 3 . , 4 . , 5 . ] ] , <nl> + [ [ 10 . , 11 . , 12 . ] , [ 0 . , 0 . , 0 . ] ] , <nl> + ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' , shape = ( 3 , ) ) <nl> + <nl> + dense_tensor , _ = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_dense_tensor , dense_tensor . eval ( session = sess ) ) <nl> + <nl> + def test_get_dense_tensor_multi_dim ( self ) : <nl> + " " " Tests get_sequence_dense_tensor for multi - dim numeric_column . " " " <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ [ 0 . , 1 . ] , [ 2 . , 3 . ] ] , [ [ 4 . , 5 . ] , [ 6 . , 7 . ] ] ] <nl> + # example 1 , [ [ [ 10 . , 11 . ] , [ 12 . , 13 . ] ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 0 , 3 ) , ( 0 , 4 ) , ( 0 , 5 ) , ( 0 , 6 ) , ( 0 , 7 ) , <nl> + ( 1 , 0 ) , ( 1 , 1 ) , ( 1 , 2 ) , ( 1 , 3 ) ) , <nl> + values = ( 0 . , 1 . , 2 . , 3 . , 4 . , 5 . , 6 . , 7 . , 10 . , 11 . , 12 . , 13 . ) , <nl> + dense_shape = ( 2 , 8 ) ) <nl> + expected_dense_tensor = [ <nl> + [ [ [ 0 . , 1 . ] , [ 2 . , 3 . ] ] , [ [ 4 . , 5 . ] , [ 6 . , 7 . ] ] ] , <nl> + [ [ [ 10 . , 11 . ] , [ 12 . , 13 . ] ] , [ [ 0 . , 0 . ] , [ 0 . , 0 . ] ] ] , <nl> + ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' , shape = ( 2 , 2 ) ) <nl> + <nl> + dense_tensor , _ = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_dense_tensor , dense_tensor . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length ( self ) : <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ 0 . , 1 . , 2 . ] , [ 3 . , 4 . , 5 . ] ] <nl> + # example 1 , [ [ 10 . , 11 . , 12 . ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 0 , 3 ) , ( 0 , 4 ) , ( 0 , 5 ) , <nl> + ( 1 , 0 ) , ( 1 , 1 ) , ( 1 , 2 ) ) , <nl> + values = ( 0 . , 1 . , 2 . , 3 . , 4 . , 5 . , 10 . , 11 . , 12 . ) , <nl> + dense_shape = ( 2 , 6 ) ) <nl> + expected_sequence_length = [ 2 , 1 ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' , shape = ( 3 , ) ) <nl> + <nl> + _ , sequence_length = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length_with_shape ( self ) : <nl> + " " " Tests _sequence_length with shape ! = ( 1 , ) . " " " <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ [ 0 . ] , [ 1 ] ] <nl> + # example 1 , [ [ 10 . ] ] <nl> + indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 1 , 0 ) ) , <nl> + values = ( 0 . , 1 . , 10 . ) , <nl> + dense_shape = ( 2 , 2 ) ) <nl> + expected_sequence_length = [ 2 , 1 ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' ) <nl> + <nl> + _ , sequence_length = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + def test_sequence_length_with_empty_rows ( self ) : <nl> + " " " Tests _sequence_length when some examples do not have ids . " " " <nl> + sparse_input = sparse_tensor . SparseTensorValue ( <nl> + # example 0 , values [ ] <nl> + # example 1 , values [ [ 0 . ] , [ 1 . ] ] <nl> + # example 2 , [ [ 2 . ] ] <nl> + # example 3 , values [ ] <nl> + # example 4 , [ [ 3 . ] ] <nl> + # example 5 , values [ ] <nl> + indices = ( ( 1 , 0 ) , ( 1 , 1 ) , ( 2 , 0 ) , ( 4 , 0 ) ) , <nl> + values = ( 0 . , 1 . , 2 . , 3 . ) , <nl> + dense_shape = ( 6 , 2 ) ) <nl> + expected_sequence_length = [ 0 , 2 , 1 , 0 , 1 , 0 ] <nl> + numeric_column = sfc . sequence_numeric_column ( ' aaa ' ) <nl> + <nl> + _ , sequence_length = numeric_column . _get_sequence_dense_tensor ( <nl> + _LazyBuilder ( { ' aaa ' : sparse_input } ) ) <nl> + <nl> + with monitored_session . MonitoredSession ( ) as sess : <nl> + self . assertAllEqual ( <nl> + expected_sequence_length , sequence_length . eval ( session = sess ) ) <nl> + <nl> + <nl> + if __name__ = = ' __main__ ' : <nl> + test . main ( ) <nl> mmm a / tensorflow / contrib / gan / python / eval / python / summaries_test . py <nl> ppp b / tensorflow / contrib / gan / python / eval / python / summaries_test . py <nl> def get_cyclegan_model ( ) : <nl> <nl> class SummariesTest ( test . TestCase ) : <nl> <nl> - def _test_add_gan_model_image_summaries_impl ( <nl> - self , get_model_fn , expected_num_summary_ops , model_summaries ) : <nl> - summaries . add_gan_model_image_summaries ( <nl> - get_model_fn ( ) , grid_size = 2 , model_summaries = model_summaries ) <nl> + def _test_add_gan_model_image_summaries_impl ( self , get_model_fn , <nl> + expected_num_summary_ops , <nl> + model_summaries ) : <nl> + summaries . add_gan_model_image_summaries ( get_model_fn ( ) , grid_size = 2 , <nl> + model_summaries = model_summaries ) <nl> <nl> self . assertEquals ( expected_num_summary_ops , <nl> len ( ops . get_collection ( ops . GraphKeys . SUMMARIES ) ) ) <nl> mmm a / tensorflow / contrib / layers / python / layers / layers . py <nl> ppp b / tensorflow / contrib / layers / python / layers / layers . py <nl> <nl> ' avg_pool2d ' , ' avg_pool3d ' , ' batch_norm ' , ' bias_add ' , ' conv2d ' , ' conv3d ' , <nl> ' conv2d_in_plane ' , ' conv2d_transpose ' , ' conv3d_transpose ' , ' convolution ' , <nl> ' convolution2d ' , ' convolution2d_in_plane ' , ' convolution2d_transpose ' , <nl> - ' convolution3d ' , ' convolution3d_transpose ' , ' dense_to_sparse ' , ' dropout ' , <nl> - ' elu ' , ' flatten ' , ' fully_connected ' , ' GDN ' , ' gdn ' , ' images_to_sequence ' , <nl> - ' layer_norm ' , ' linear ' , ' pool ' , ' max_pool2d ' , ' max_pool3d ' , <nl> - ' one_hot_encoding ' , ' relu ' , ' relu6 ' , ' repeat ' , ' scale_gradient ' , <nl> - ' separable_conv2d ' , ' separable_convolution2d ' , ' sequence_to_images ' , <nl> - ' softmax ' , ' spatial_softmax ' , ' stack ' , ' unit_norm ' , <nl> + ' convolution3d ' , ' convolution3d_transpose ' , ' dense_to_sparse ' , <nl> + ' dropout ' , ' elu ' , ' flatten ' , ' fully_connected ' , ' GDN ' , ' gdn ' , <nl> + ' images_to_sequence ' , ' layer_norm ' , ' linear ' , ' pool ' , ' max_pool2d ' , <nl> + ' max_pool3d ' , ' one_hot_encoding ' , ' relu ' , ' relu6 ' , ' repeat ' , <nl> + ' scale_gradient ' , ' separable_conv2d ' , ' separable_convolution2d ' , <nl> + ' sequence_to_images ' , ' softmax ' , ' spatial_softmax ' , ' stack ' , ' unit_norm ' , <nl> ' legacy_fully_connected ' , ' legacy_linear ' , ' legacy_relu ' , ' maxout ' <nl> ] <nl> <nl> def sequence_to_images ( inputs , <nl> num_batches = - 1 <nl> else : <nl> num_batches = num_batches / / height <nl> - reshaped = array_ops . reshape ( inputs , [ width , num_batches , height , depth ] ) <nl> + reshaped = array_ops . reshape ( inputs , <nl> + [ width , num_batches , height , depth ] ) <nl> if output_data_format = = ' channels_first ' : <nl> outputs = array_ops . transpose ( reshaped , [ 1 , 3 , 2 , 0 ] ) <nl> else : <nl> mmm a / tensorflow / contrib / layers / python / layers / layers_test . py <nl> ppp b / tensorflow / contrib / layers / python / layers / layers_test . py <nl> def testImagesToSequenceDims ( self ) : <nl> num_time_steps = 11 <nl> num_channels = 5 <nl> desired_height = 7 <nl> - sequence = np . random . uniform ( <nl> - size = ( num_time_steps , num_batches , num_channels ) ) . astype ( np . float32 ) <nl> + sequence = np . random . uniform ( size = ( num_time_steps , <nl> + num_batches , <nl> + num_channels ) ) . astype ( np . float32 ) <nl> output = _layers . sequence_to_images ( sequence , desired_height ) <nl> self . assertListEqual ( output . get_shape ( ) . as_list ( ) , [ 2 , 7 , 11 , 5 ] ) <nl> <nl> def testImagesToSequenceNCHW ( self ) : <nl> num_time_steps = 11 <nl> num_channels = 5 <nl> desired_height = 7 <nl> - sequence = np . random . uniform ( <nl> - size = ( num_time_steps , num_batches , num_channels ) ) . astype ( np . float32 ) <nl> - output = _layers . sequence_to_images ( <nl> - sequence , desired_height , output_data_format = ' channels_first ' ) <nl> + sequence = np . random . uniform ( size = ( num_time_steps , <nl> + num_batches , <nl> + num_channels ) ) . astype ( np . float32 ) <nl> + output = _layers . sequence_to_images ( sequence , <nl> + desired_height , <nl> + output_data_format = ' channels_first ' ) <nl> self . assertListEqual ( output . get_shape ( ) . as_list ( ) , [ 2 , 5 , 7 , 11 ] ) <nl> <nl> <nl> mmm a / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifier . java <nl> ppp b / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifier . java <nl> <nl> import android . graphics . Bitmap ; <nl> import android . os . SystemClock ; <nl> import android . util . Log ; <nl> + <nl> + import org . tensorflow . lite . Interpreter ; <nl> + <nl> import java . io . BufferedReader ; <nl> import java . io . FileInputStream ; <nl> import java . io . IOException ; <nl> <nl> import java . util . List ; <nl> import java . util . Map ; <nl> import java . util . PriorityQueue ; <nl> - import org . tensorflow . lite . Interpreter ; <nl> <nl> - / * * Classifies images with Tensorflow Lite . * / <nl> + / * * <nl> + * Classifies images with Tensorflow Lite . <nl> + * / <nl> public abstract class ImageClassifier { <nl> <nl> / * * Tag for the { @ link Log } . * / <nl> mmm a / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifierFloatInception . java <nl> ppp b / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifierFloatInception . java <nl> <nl> package com . example . android . tflitecamerademo ; <nl> <nl> import android . app . Activity ; <nl> + <nl> import java . io . IOException ; <nl> <nl> / * * <nl> - * This classifier works with the Inception - v3 slim model . It applies floating point inference <nl> - * rather than using a quantized model . <nl> + * This classifier works with the Inception - v3 slim model . <nl> + * It applies floating point inference rather than using a quantized model . <nl> * / <nl> public class ImageClassifierFloatInception extends ImageClassifier { <nl> <nl> - / * * The inception net requires additional normalization of the used input . * / <nl> + / * * <nl> + * The inception net requires additional normalization of the used input . <nl> + * / <nl> private static final int IMAGE_MEAN = 128 ; <nl> - <nl> private static final float IMAGE_STD = 128 . 0f ; <nl> <nl> / * * <nl> - * An array to hold inference results , to be feed into Tensorflow Lite as outputs . This isn ' t part <nl> - * of the super class , because we need a primitive array here . <nl> + * An array to hold inference results , to be feed into Tensorflow Lite as outputs . <nl> + * This isn ' t part of the super class , because we need a primitive array here . <nl> * / <nl> private float [ ] [ ] labelProbArray = null ; <nl> <nl> mmm a / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifierQuantizedMobileNet . java <nl> ppp b / tensorflow / contrib / lite / java / demo / app / src / main / java / com / example / android / tflitecamerademo / ImageClassifierQuantizedMobileNet . java <nl> <nl> package com . example . android . tflitecamerademo ; <nl> <nl> import android . app . Activity ; <nl> + <nl> import java . io . IOException ; <nl> <nl> - / * * This classifier works with the quantized MobileNet model . * / <nl> + / * * <nl> + * This classifier works with the quantized MobileNet model . <nl> + * / <nl> public class ImageClassifierQuantizedMobileNet extends ImageClassifier { <nl> <nl> / * * <nl> - * An array to hold inference results , to be feed into Tensorflow Lite as outputs . This isn ' t part <nl> - * of the super class , because we need a primitive array here . <nl> + * An array to hold inference results , to be feed into Tensorflow Lite as outputs . <nl> + * This isn ' t part of the super class , because we need a primitive array here . <nl> * / <nl> private byte [ ] [ ] labelProbArray = null ; <nl> <nl> mmm a / tensorflow / contrib / lite / kernels / internal / optimized / neon_tensor_utils . cc <nl> ppp b / tensorflow / contrib / lite / kernels / internal / optimized / neon_tensor_utils . cc <nl> limitations under the License . <nl> # include < string . h > <nl> <nl> # include " tensorflow / contrib / lite / builtin_op_data . h " <nl> + # include " tensorflow / contrib / lite / kernels / internal / common . h " <nl> # include " tensorflow / contrib / lite / kernels / activation_functor . h " <nl> # include " tensorflow / contrib / lite / kernels / internal / common . h " <nl> # include " tensorflow / contrib / lite / kernels / internal / optimized / tensor_utils_impl . h " <nl> mmm a / tensorflow / contrib / lite / testing / generate_examples . py <nl> ppp b / tensorflow / contrib / lite / testing / generate_examples . py <nl> <nl> import zipfile <nl> import numpy as np <nl> from six import StringIO <nl> + from six . moves import xrange <nl> <nl> # TODO ( aselle ) : Disable GPU for now <nl> os . environ [ " CUDA_VISIBLE_DEVICES " ] = " - 1 " <nl> mmm a / tensorflow / contrib / rnn / python / kernel_tests / rnn_cell_test . py <nl> ppp b / tensorflow / contrib / rnn / python / kernel_tests / rnn_cell_test . py <nl> def _cell_output ( self , cell ) : <nl> <nl> with self . test_session ( ) as sess : <nl> init = init_ops . constant_initializer ( 0 . 5 ) <nl> - with variable_scope . variable_scope ( " root " , initializer = init ) : <nl> + with variable_scope . variable_scope ( " root " , <nl> + initializer = init ) : <nl> x = array_ops . zeros ( [ 1 , 2 ] ) <nl> c0 = array_ops . zeros ( [ 1 , 2 ] ) <nl> h0 = array_ops . zeros ( [ 1 , 2 ] ) <nl> def _cell_output ( self , cell ) : <nl> xout , sout = cell ( ) ( x , state0 ) <nl> <nl> sess . run ( [ variables . global_variables_initializer ( ) ] ) <nl> - res = sess . run ( <nl> - [ xout , sout ] , { <nl> - x . name : np . array ( [ [ 1 . , 1 . ] ] ) , <nl> - c0 . name : 0 . 1 * np . asarray ( [ [ 0 , 1 ] ] ) , <nl> - h0 . name : 0 . 1 * np . asarray ( [ [ 2 , 3 ] ] ) , <nl> - } ) <nl> + res = sess . run ( [ xout , sout ] , { <nl> + x . name : np . array ( [ [ 1 . , 1 . ] ] ) , <nl> + c0 . name : 0 . 1 * np . asarray ( [ [ 0 , 1 ] ] ) , <nl> + h0 . name : 0 . 1 * np . asarray ( [ [ 2 , 3 ] ] ) , <nl> + } ) <nl> <nl> actual_state_c = res [ 1 ] . c <nl> actual_state_h = res [ 1 ] . h <nl> def testBasicCell ( self ) : <nl> " " " Tests cell w / o peepholes and w / o normalisation . " " " <nl> <nl> def cell ( ) : <nl> - return contrib_rnn_cell . WeightNormLSTMCell ( <nl> - 2 , norm = False , use_peepholes = False ) <nl> + return contrib_rnn_cell . WeightNormLSTMCell ( 2 , <nl> + norm = False , <nl> + use_peepholes = False ) <nl> <nl> actual_c , actual_h = self . _cell_output ( cell ) <nl> <nl> def testNonbasicCell ( self ) : <nl> " " " Tests cell with peepholes and w / o normalisation . " " " <nl> <nl> def cell ( ) : <nl> - return contrib_rnn_cell . WeightNormLSTMCell ( <nl> - 2 , norm = False , use_peepholes = True ) <nl> + return contrib_rnn_cell . WeightNormLSTMCell ( 2 , <nl> + norm = False , <nl> + use_peepholes = True ) <nl> <nl> actual_c , actual_h = self . _cell_output ( cell ) <nl> <nl> def testBasicCellWithNorm ( self ) : <nl> " " " Tests cell w / o peepholes and with normalisation . " " " <nl> <nl> def cell ( ) : <nl> - return contrib_rnn_cell . WeightNormLSTMCell ( <nl> - 2 , norm = True , use_peepholes = False ) <nl> + return contrib_rnn_cell . WeightNormLSTMCell ( 2 , <nl> + norm = True , <nl> + use_peepholes = False ) <nl> <nl> actual_c , actual_h = self . _cell_output ( cell ) <nl> <nl> def testNonBasicCellWithNorm ( self ) : <nl> " " " Tests cell with peepholes and with normalisation . " " " <nl> <nl> def cell ( ) : <nl> - return contrib_rnn_cell . WeightNormLSTMCell ( <nl> - 2 , norm = True , use_peepholes = True ) <nl> + return contrib_rnn_cell . WeightNormLSTMCell ( 2 , <nl> + norm = True , <nl> + use_peepholes = True ) <nl> <nl> actual_c , actual_h = self . _cell_output ( cell ) <nl> <nl> mmm a / tensorflow / contrib / seq2seq / python / ops / beam_search_decoder . py <nl> ppp b / tensorflow / contrib / seq2seq / python / ops / beam_search_decoder . py <nl> def _mask_probs ( probs , eos_token , finished ) : <nl> eos_token , <nl> vocab_size , <nl> dtype = probs . dtype , <nl> - on_value = 0 . , <nl> + on_value = ops . convert_to_tensor ( 0 . , dtype = probs . dtype ) , <nl> off_value = probs . dtype . min ) <nl> finished_probs = array_ops . tile ( <nl> array_ops . reshape ( finished_row , [ 1 , 1 , - 1 ] ) , <nl> mmm a / tensorflow / contrib / slim / python / slim / data / parallel_reader . py <nl> ppp b / tensorflow / contrib / slim / python / slim / data / parallel_reader . py <nl> def parallel_read ( data_sources , <nl> the data will be cycled through indefinitely . <nl> num_readers : a integer , number of Readers to create . <nl> reader_kwargs : an optional dict , of kwargs for the reader . <nl> - shuffle : boolean , wether should shuffle the files and the records by using <nl> + shuffle : boolean , whether should shuffle the files and the records by using <nl> RandomShuffleQueue as common_queue . <nl> dtypes : A list of types . The length of dtypes must equal the number <nl> of elements in each record . If it is None it will default to <nl> mmm a / tensorflow / contrib / tensor_forest / kernels / v4 / grow_stats . h <nl> ppp b / tensorflow / contrib / tensor_forest / kernels / v4 / grow_stats . h <nl> class FixedSizeSparseClassificationGrowStats : public ClassificationStats { <nl> void PackToProto ( FertileSlot * slot ) const override ; <nl> <nl> void InitLeafClassStats ( int best_split_index , LeafStat * left_stats , <nl> - LeafStat * right_stats ) const ; <nl> + LeafStat * right_stats ) const override ; <nl> <nl> protected : <nl> void ClassificationAddSplitStats ( ) override { <nl> mmm a / tensorflow / contrib / tensorrt / BUILD <nl> ppp b / tensorflow / contrib / tensorrt / BUILD <nl> tf_cuda_cc_test ( <nl> <nl> tf_custom_op_library ( <nl> name = " python / ops / _trt_engine_op . so " , <nl> - srcs = [ " ops / trt_engine_op . cc " ] , <nl> + srcs = [ <nl> + " ops / trt_calib_op . cc " , <nl> + " ops / trt_engine_op . cc " , <nl> + ] , <nl> deps = [ <nl> " : trt_engine_op_kernel " , <nl> " : trt_shape_function " , <nl> tf_cuda_library ( <nl> <nl> cc_library ( <nl> name = " trt_engine_op_kernel " , <nl> - srcs = [ " kernels / trt_engine_op . cc " ] , <nl> - hdrs = [ " kernels / trt_engine_op . h " ] , <nl> + srcs = [ <nl> + " kernels / trt_calib_op . cc " , <nl> + " kernels / trt_engine_op . cc " , <nl> + ] , <nl> + hdrs = [ <nl> + " kernels / trt_calib_op . h " , <nl> + " kernels / trt_engine_op . h " , <nl> + ] , <nl> copts = tf_copts ( ) , <nl> deps = [ <nl> " : trt_logging " , <nl> + " : trt_resources " , <nl> " / / tensorflow / core : gpu_headers_lib " , <nl> " / / tensorflow / core : lib_proto_parsing " , <nl> " / / tensorflow / core : stream_executor_headers_lib " , <nl> cc_library ( <nl> ) <nl> <nl> tf_gen_op_libs ( <nl> - op_lib_names = [ " trt_engine_op " ] , <nl> + op_lib_names = [ <nl> + " trt_engine_op " , <nl> + " trt_calib_op " , <nl> + ] , <nl> deps = if_tensorrt ( [ <nl> " @ local_config_tensorrt / / : nv_infer " , <nl> ] ) , <nl> tf_gen_op_wrapper_py ( <nl> name = " trt_engine_op " , <nl> gen_locally = True , <nl> deps = [ <nl> + " : trt_calib_op_op_lib " , <nl> " : trt_engine_op_op_lib " , <nl> " : trt_logging " , <nl> " : trt_shape_function " , <nl> tf_py_wrap_cc ( <nl> ] , <nl> ) <nl> <nl> + tf_cuda_library ( <nl> + name = " trt_resources " , <nl> + srcs = [ <nl> + " resources / trt_int8_calibrator . cc " , <nl> + " resources / trt_resource_manager . cc " , <nl> + ] , <nl> + hdrs = [ <nl> + " resources / trt_int8_calibrator . h " , <nl> + " resources / trt_resource_manager . h " , <nl> + " resources / trt_resources . h " , <nl> + ] , <nl> + deps = [ <nl> + " : trt_logging " , <nl> + " / / tensorflow / core : framework_headers_lib " , <nl> + " / / tensorflow / core : framework_lite " , <nl> + " / / tensorflow / core : lib_proto_parsing " , <nl> + ] + if_tensorrt ( [ <nl> + " @ local_config_tensorrt / / : nv_infer " , <nl> + ] ) , <nl> + ) <nl> + <nl> # Library for the node - level conversion portion of TensorRT operation creation <nl> tf_cuda_library ( <nl> name = " trt_conversion " , <nl> tf_cuda_library ( <nl> deps = [ <nl> " : segment " , <nl> " : trt_logging " , <nl> + " : trt_resources " , <nl> " / / tensorflow / core / grappler : grappler_item " , <nl> " / / tensorflow / core / grappler : utils " , <nl> " / / tensorflow / core : framework " , <nl> mmm a / tensorflow / contrib / tensorrt / convert / convert_nodes . cc <nl> ppp b / tensorflow / contrib / tensorrt / convert / convert_nodes . cc <nl> tensorflow : : Status BinaryTensorOpTensor ( <nl> CHECK_EQ_TYPE ( tensor_r - > getType ( ) , dtype ) ; <nl> auto op_pair = ops . find ( node_def . op ( ) ) ; <nl> if ( op_pair = = ops . end ( ) ) <nl> - return tensorflow : : errors : : Unimplemented ( <nl> - " binary op : " + node_def . op ( ) + <nl> - " not supported at : " + node_def . name ( ) ) ; <nl> + return tensorflow : : errors : : Unimplemented ( " binary op : " + node_def . op ( ) + <nl> + " not supported at : " + <nl> + node_def . name ( ) ) ; <nl> <nl> nvinfer1 : : IElementWiseLayer * layer = ctx . network ( ) - > addElementWise ( <nl> * const_cast < nvinfer1 : : ITensor * > ( tensor_l ) , <nl> tensorflow : : Status ConvertSubGraphToTensorRTNodeDef ( <nl> < < std : : to_string ( op_info_vec . size ( ) ) ; <nl> <nl> / / TODO ( ben , jie ) : update TRT input format / dimension <nl> - nvinfer1 : : DimsCHW input_dim_pseudo_chw ; <nl> - for ( int i = 0 ; i < 3 ; i + + ) input_dim_pseudo_chw . d [ i ] = 1 ; <nl> + nvinfer1 : : DimsCHW input_dim_psuedo_chw ; <nl> + for ( int i = 0 ; i < 3 ; i + + ) input_dim_psuedo_chw . d [ i ] = 1 ; <nl> <nl> for ( int i = 1 ; i < op_info . shape ( ) . dim_size ( ) ; i + + ) { <nl> VLOG ( 2 ) < < " dimension : " < < i <nl> < < " , size : " < < op_info . shape ( ) . dim ( i ) . size ( ) ; <nl> - input_dim_pseudo_chw . d [ i - 1 ] = op_info . shape ( ) . dim ( i ) . size ( ) ; <nl> + input_dim_psuedo_chw . d [ i - 1 ] = op_info . shape ( ) . dim ( i ) . size ( ) ; <nl> } <nl> <nl> / / TODO ( ben , jie ) : proper way to restore input tensor name ? <nl> tensorflow : : Status ConvertSubGraphToTensorRTNodeDef ( <nl> input_tensor_name = node_name + " : " + std : : to_string ( output_idx ) ; <nl> <nl> nvinfer1 : : ITensor * input_tensor = converter . network ( ) - > addInput ( <nl> - input_tensor_name . c_str ( ) , dtype , input_dim_pseudo_chw ) ; <nl> + input_tensor_name . c_str ( ) , dtype , input_dim_psuedo_chw ) ; <nl> <nl> if ( ! input_tensor ) <nl> return tensorflow : : errors : : InvalidArgument ( <nl> new file mode 100644 <nl> index 0000000000000 . . 1dcb87e7683ad <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / kernels / trt_calib_op . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # include " tensorflow / contrib / tensorrt / kernels / trt_calib_op . h " <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_int8_calibrator . h " <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_resource_manager . h " <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_resources . h " <nl> + # include " tensorflow / core / framework / tensor . h " <nl> + # include " tensorflow / core / framework / tensor_shape . h " <nl> + # include " tensorflow / core / framework / tensor_types . h " <nl> + # include " tensorflow / core / framework / types . h " <nl> + <nl> + # if GOOGLE_CUDA <nl> + # if GOOGLE_TENSORRT <nl> + # include " cuda_runtime_api . h " <nl> + # include " tensorrt / include / NvInfer . h " <nl> + <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + <nl> + TRTCalibOp : : TRTCalibOp ( OpKernelConstruction * context ) : OpKernel ( context ) { <nl> + OP_REQUIRES_OK ( context , context - > GetAttr ( " segment_nodes " , & segment_nodes_ ) ) ; <nl> + OP_REQUIRES_OK ( context , context - > GetAttr ( " input_names " , & input_names_ ) ) ; <nl> + OP_REQUIRES_OK ( context , context - > GetAttr ( " resource_name " , & resource_name_ ) ) ; <nl> + } ; <nl> + <nl> + # define TYPECASE ( dt , X , Y ) \ <nl> + case dt : { \ <nl> + return ( void * ) X - > flat < tensorflow : : EnumToDataType < dt > : : Type > ( ) . data ( ) ; \ <nl> + } <nl> + <nl> + void * GetTensorAddress ( const Tensor * tensor_ptr ) { <nl> + auto tensor_type = tensor_ptr - > dtype ( ) ; <nl> + switch ( tensor_type ) { <nl> + TYPECASE ( tensorflow : : DT_FLOAT , tensor_ptr , dest_ptr ) ; <nl> + TYPECASE ( tensorflow : : DT_HALF , tensor_ptr , dest_ptr ) ; <nl> + TYPECASE ( tensorflow : : DT_INT8 , tensor_ptr , dest_ptr ) ; <nl> + default : { <nl> + LOG ( FATAL ) < < " Unsupported Data type " <nl> + < < tensorflow : : DataTypeString ( tensor_type ) ; <nl> + return nullptr ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void TRTCalibOp : : Compute ( tensorflow : : OpKernelContext * ctx ) { <nl> + / / TODO ( aaroey ) : make sure ctx - > resource_mgr ( ) is used in future PR . <nl> + auto trt_rm = tensorflow : : tensorrt : : TRTResourceManager : : instance ( ) ; <nl> + auto res_mgr = trt_rm - > getManager ( " TRTCalibOps " ) ; <nl> + tensorflow : : tensorrt : : TRTCalibrationResource * calib_res = nullptr ; <nl> + auto status = res_mgr - > Lookup ( resource_name_ , resource_name_ , & calib_res ) ; <nl> + <nl> + if ( ! status . ok ( ) ) { <nl> + ctx - > SetStatus ( status ) ; <nl> + return ; <nl> + } <nl> + int num_inputs = ctx - > num_inputs ( ) ; <nl> + / / first run instantiate calibrator <nl> + if ( calib_res - > calibrator_ = = nullptr ) { <nl> + dev_tensors_ . resize ( num_inputs ) ; <nl> + int batch_size = ctx - > input ( 0 ) . dim_size ( 0 ) ; <nl> + VLOG ( 1 ) < < " Constructing calibrator " ; <nl> + for ( int i = 0 ; i < num_inputs ; i + + ) { <nl> + / / allocate workspace on device for inputs <nl> + const tensorflow : : Tensor & t = ctx - > input ( i ) ; <nl> + OP_REQUIRES_OK ( ctx , <nl> + ctx - > allocate_persistent ( t . dtype ( ) , t . shape ( ) , <nl> + & dev_tensors_ . at ( i ) , nullptr ) ) ; <nl> + const auto device_tensor = dev_tensors_ . at ( i ) . AccessTensor ( ctx ) ; <nl> + CHECK_EQ ( t . TotalBytes ( ) , device_tensor - > TotalBytes ( ) ) ; <nl> + void * device_address = GetTensorAddress ( device_tensor ) ; <nl> + device_buffers_ . emplace ( input_names_ . at ( i ) , <nl> + std : : pair < void * , size_t > ( <nl> + device_address , device_tensor - > TotalBytes ( ) ) ) ; <nl> + } <nl> + <nl> + calib_res - > calibrator_ = <nl> + new TRTInt8Calibrator ( device_buffers_ , batch_size , resource_name_ ) ; <nl> + string label ( resource_name_ ) ; <nl> + calib_res - > thr_ = new std : : thread ( [ calib_res , label ] ( ) { <nl> + VLOG ( 1 ) < < " Starting calibration thread , Calibration Resource @ " <nl> + < < calib_res ; <nl> + calib_res - > builder_ - > setInt8Calibrator ( calib_res - > calibrator_ ) ; <nl> + calib_res - > builder_ - > setInt8Mode ( true ) ; <nl> + calib_res - > engine_ = calib_res - > builder_ - > buildCudaEngine ( <nl> + * calib_res - > network_ ) ; / / will loop until we terminate calibrator <nl> + VLOG ( 1 ) < < " Calibration loop terminated " < < label ; <nl> + } ) ; <nl> + VLOG ( 1 ) < < " initialized calibrator resource " ; <nl> + } / / calibrator initialized <nl> + <nl> + / / Pass input data to calibrator <nl> + std : : unordered_map < string , void * > input_data ; <nl> + for ( int i = 0 ; i < num_inputs ; i + + ) { <nl> + const Tensor & t = ctx - > input ( i ) ; <nl> + void * data_address = GetTensorAddress ( & t ) ; <nl> + const auto device_tensor = dev_tensors_ . at ( i ) . AccessTensor ( ctx ) ; <nl> + CHECK_EQ ( t . TotalBytes ( ) , <nl> + device_tensor - > TotalBytes ( ) ) ; / / use the tensor so FW keeps it <nl> + input_data . emplace ( input_names_ . at ( i ) , data_address ) ; <nl> + ctx - > set_output ( i , t ) ; <nl> + } <nl> + VLOG ( 2 ) < < " Filled map for sending " ; <nl> + calib_res - > calibrator_ - > setBatch ( input_data ) ; <nl> + VLOG ( 2 ) < < " Passed calibration data " ; <nl> + / / TODO ( aaroey ) : make sure we wait for the completion of calibration on the <nl> + / / last batch in future PR . <nl> + } ; <nl> + <nl> + # undef TYPECASE <nl> + <nl> + REGISTER_KERNEL_BUILDER ( Name ( " TRTCalibOp " ) . Device ( DEVICE_GPU ) , TRTCalibOp ) ; <nl> + <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + # endif <nl> + # endif <nl> new file mode 100644 <nl> index 0000000000000 . . 23df9db32f077 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / kernels / trt_calib_op . h <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # ifndef TENSORFLOW_CONTRIB_TENSORRT_KERNELS_TRT_CALIB_OP_H <nl> + # define TENSORFLOW_CONTRIB_TENSORRT_KERNELS_TRT_CALIB_OP_H <nl> + <nl> + # include < memory > <nl> + # include < string > <nl> + # include < unordered_map > <nl> + # include < utility > <nl> + # include < vector > <nl> + # include " tensorflow / core / framework / op . h " <nl> + # include " tensorflow / core / framework / op_kernel . h " <nl> + # include " tensorflow / core / framework / tensor_shape . h " <nl> + # include " tensorflow / core / platform / types . h " <nl> + <nl> + # if GOOGLE_CUDA <nl> + # if GOOGLE_TENSORRT <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + / / TODO ( sami ) : Convert this to async kernel ! <nl> + class TRTCalibOp : public OpKernel { <nl> + public : <nl> + explicit TRTCalibOp ( OpKernelConstruction * context ) ; <nl> + <nl> + void Compute ( OpKernelContext * context ) override ; <nl> + <nl> + private : <nl> + string resource_name_ ; <nl> + std : : vector < string > segment_nodes_ ; <nl> + std : : vector < string > input_names_ ; <nl> + std : : vector < tensorflow : : TensorShape > shapes_ ; <nl> + std : : unordered_map < string , std : : pair < void * , size_t > > device_buffers_ ; <nl> + std : : vector < tensorflow : : PersistentTensor > dev_tensors_ ; <nl> + } ; <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + # endif <nl> + # endif <nl> + # endif / / TENSORFLOW_CONTRIB_TENSORRT_KERNELS_TRT_CALIB_OP_H <nl> new file mode 100644 <nl> index 0000000000000 . . 4835e5065068e <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / ops / trt_calib_op . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # include " tensorflow / core / framework / op . h " <nl> + # include " tensorflow / core / framework / shape_inference . h " <nl> + namespace tensorflow { <nl> + <nl> + REGISTER_OP ( " TRTCalibOp " ) <nl> + . Attr ( " segment_nodes : list ( string ) " ) / / names of the ops in segment <nl> + . Attr ( " segment_output_names : list ( string ) " ) / / names of the output ops in <nl> + / / segment <nl> + . Attr ( " input_names : list ( string ) " ) / / names of the inputs for <nl> + / / passing into tensorrt <nl> + . Attr ( " resource_name : string " ) <nl> + . Attr ( " InT : list ( { int8 , float16 , float32 } ) " ) <nl> + . Input ( " in_tensor : InT " ) <nl> + . Output ( " out_tensor : InT " ) <nl> + . SetShapeFn ( [ ] ( tensorflow : : shape_inference : : InferenceContext * c ) { <nl> + for ( int i = 0 ; i < c - > num_inputs ( ) ; i + + ) { <nl> + c - > set_output ( i , c - > input ( i ) ) ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } ) ; <nl> + <nl> + } / / namespace tensorflow <nl> new file mode 100644 <nl> index 0000000000000 . . 3d5cc76c4256b <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / resources / trt_int8_calibrator . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_int8_calibrator . h " <nl> + <nl> + # include < atomic > <nl> + # include < chrono > <nl> + # include < unordered_map > <nl> + <nl> + # include " tensorflow / core / platform / logging . h " <nl> + <nl> + # if GOOGLE_CUDA <nl> + # if GOOGLE_TENSORRT <nl> + # include " cuda_runtime_api . h " <nl> + <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + <nl> + / / set the batch size before constructing the thread to execute engine <nl> + int TRTInt8Calibrator : : getBatchSize ( ) const { return batch_size_ ; } <nl> + <nl> + TRTInt8Calibrator : : TRTInt8Calibrator ( <nl> + const std : : unordered_map < string , std : : pair < void * , size_t > > & dev_buffers , <nl> + int batch_size , string engine_name ) <nl> + : batch_size_ ( batch_size ) , <nl> + done_ ( false ) , <nl> + dev_buffers_ ( dev_buffers ) , <nl> + calib_running_ ( false ) , <nl> + engine_name_ ( engine_name ) { } <nl> + <nl> + bool TRTInt8Calibrator : : setBatch ( <nl> + const std : : unordered_map < string , void * > & data ) { <nl> + / / TODO ( aaroey ) : make sure that in future PR : <nl> + / / 1 . the mutex_lock is outside of the loop <nl> + / / 2 . wait ( ) is used instead of wait_for ( ) <nl> + / / 3 . done_ is to be protected by the mutex <nl> + / / 4 . the first batch is not missed <nl> + if ( done_ ) return false ; <nl> + while ( calib_running_ . load ( <nl> + std : : memory_order_acquire ) ) { / / wait while calibration is running <nl> + tensorflow : : mutex_lock l ( cond_mtx_ ) ; <nl> + cond_ . wait_for ( l , std : : chrono : : milliseconds ( 50 ) ) ; <nl> + if ( done_ ) return false ; <nl> + } <nl> + VLOG ( 1 ) < < " Set Batch Waiting finished " ; <nl> + for ( const auto it : data ) { <nl> + auto devptr = dev_buffers_ . find ( it . first ) ; <nl> + if ( devptr = = dev_buffers_ . end ( ) ) { <nl> + LOG ( FATAL ) < < " FATAL " < < engine_name_ < < " input name ' " < < it . first <nl> + < < " ' does not match with the buffer names " ; <nl> + } <nl> + const auto & d = devptr - > second ; <nl> + <nl> + / / TODO ( aaroey ) : we should not use sync copy on default stream . Make sure <nl> + / / stream - > ThenMemcpy ( ) is used in future PRs . <nl> + auto status = <nl> + cudaMemcpy ( d . first , it . second , d . second , cudaMemcpyDeviceToDevice ) ; <nl> + if ( status ! = cudaSuccess ) { <nl> + LOG ( FATAL ) < < " cudaMemcpy " < < engine_name_ < < " for ' " < < it . first <nl> + < < " ' failed with " < < status ; <nl> + } <nl> + } <nl> + calib_running_ . store ( true , std : : memory_order_release ) ; / / release builder <nl> + cond_ . notify_all ( ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool TRTInt8Calibrator : : getBatch ( void * * bindings , const char * * names , <nl> + int num_bindings ) { <nl> + calib_running_ . store ( false , std : : memory_order_release ) ; / / wait for new batch <nl> + cond_ . notify_all ( ) ; <nl> + while ( ! calib_running_ . load ( <nl> + std : : memory_order_acquire ) ) { / / wait until new batch arrives <nl> + tensorflow : : mutex_lock l ( cond_mtx_ ) ; <nl> + cond_ . wait_for ( l , std : : chrono : : milliseconds ( 50 ) ) ; <nl> + if ( done_ ) return false ; <nl> + } <nl> + if ( done_ ) { <nl> + return false ; <nl> + } <nl> + <nl> + for ( int i = 0 ; i < num_bindings ; i + + ) { <nl> + auto it = dev_buffers_ . find ( names [ i ] ) ; <nl> + if ( it = = dev_buffers_ . end ( ) ) { <nl> + LOG ( FATAL ) < < " Calibration engine asked for unknown tensor name ' " <nl> + < < names [ i ] < < " ' at position " < < i ; <nl> + } <nl> + <nl> + bindings [ i ] = it - > second . first ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + const void * TRTInt8Calibrator : : readCalibrationCache ( std : : size_t & length ) { <nl> + return nullptr ; <nl> + } <nl> + <nl> + void TRTInt8Calibrator : : writeCalibrationCache ( const void * ptr , <nl> + std : : size_t length ) { } <nl> + TRTInt8Calibrator : : ~ TRTInt8Calibrator ( ) { <nl> + VLOG ( 1 ) < < " Destroying calibrator for " < < engine_name_ ; <nl> + } <nl> + <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + # endif <nl> + # endif <nl> new file mode 100644 <nl> index 0000000000000 . . 8830f7efe75b4 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / resources / trt_int8_calibrator . h <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # ifndef TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_INT8_CALIBRATOR_H_ <nl> + # define TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_INT8_CALIBRATOR_H_ <nl> + <nl> + # include < atomic > <nl> + # include < string > <nl> + # include < unordered_map > <nl> + # include < utility > <nl> + # include " tensorflow / core / platform / mutex . h " <nl> + <nl> + # if GOOGLE_CUDA <nl> + # if GOOGLE_TENSORRT <nl> + # include " tensorrt / include / NvInfer . h " <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + / / This class provides a 1 element queue to match TFs push model to <nl> + / / TRTs pull model for calibration . When TRT implements a means for <nl> + / / a push calibration This class should be updated accordingly <nl> + <nl> + struct TRTInt8Calibrator : public nvinfer1 : : IInt8EntropyCalibrator { <nl> + public : <nl> + TRTInt8Calibrator ( <nl> + const std : : unordered_map < string , std : : pair < void * , size_t > > & dev_buffers , <nl> + int batch_size , string engine_name ) ; <nl> + int getBatchSize ( ) const override ; <nl> + bool getBatch ( void * bindings [ ] , const char * names [ ] , <nl> + int num_bindings ) override ; <nl> + bool setBatch ( const std : : unordered_map < string , void * > & data ) ; <nl> + void setDone ( ) { done_ = true ; } <nl> + const void * readCalibrationCache ( std : : size_t & length ) override ; <nl> + void writeCalibrationCache ( const void * ptr , std : : size_t length ) override ; <nl> + ~ TRTInt8Calibrator ( ) ; <nl> + <nl> + private : <nl> + const int batch_size_ ; <nl> + tensorflow : : mutex cond_mtx_ ; / / mutex for condition_variable <nl> + tensorflow : : condition_variable cond_ ; / / condition variable to implement <nl> + / / producer - consumer queue for <nl> + / / calibration <nl> + bool done_ ; <nl> + const std : : unordered_map < string , std : : pair < void * , size_t > > <nl> + dev_buffers_ ; / / map to keep tensorrt input buffers and sizes keyed with <nl> + / / buffer names <nl> + std : : atomic_bool calib_running_ ; <nl> + string engine_name_ ; <nl> + } ; <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + # endif / / TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_INT8_CALIBRATOR_H_ <nl> + # endif <nl> + # endif <nl> new file mode 100644 <nl> index 0000000000000 . . e663eed4dd670 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / resources / trt_resource_manager . cc <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_resource_manager . h " <nl> + # include " tensorflow / core / platform / logging . h " <nl> + <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + <nl> + std : : shared_ptr < tensorflow : : ResourceMgr > <nl> + tensorflow : : tensorrt : : TRTResourceManager : : getManager ( const string & op_name ) { <nl> + / / mutex is held for lookup only . Most instantiations where mutex will be held <nl> + / / longer will be during op creation and should be ok . <nl> + tensorflow : : mutex_lock lock ( map_mutex_ ) ; <nl> + auto s = managers_ . find ( op_name ) ; <nl> + if ( s = = managers_ . end ( ) ) { <nl> + auto it = managers_ . emplace ( <nl> + op_name , std : : make_shared < tensorflow : : ResourceMgr > ( op_name ) ) ; <nl> + VLOG ( 1 ) < < " Returning a new manager " < < op_name ; <nl> + return it . first - > second ; <nl> + } <nl> + VLOG ( 1 ) < < " Returning old manager " < < op_name ; <nl> + return s - > second ; <nl> + } <nl> + <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> new file mode 100644 <nl> index 0000000000000 . . 5f8ad491d3c13 <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / resources / trt_resource_manager . h <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # ifndef TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_RESOURCE_MANAGER_H_ <nl> + # define TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRT_RESOURCE_MANAGER_H_ <nl> + # include < memory > <nl> + <nl> + # include < string > <nl> + # include < unordered_map > <nl> + # include " tensorflow / core / framework / resource_mgr . h " <nl> + # include " tensorflow / core / platform / mutex . h " <nl> + <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + <nl> + class TRTResourceManager { <nl> + TRTResourceManager ( ) = default ; <nl> + <nl> + public : <nl> + static std : : shared_ptr < TRTResourceManager > instance ( ) { <nl> + static std : : shared_ptr < TRTResourceManager > instance_ ( <nl> + new TRTResourceManager ) ; <nl> + return instance_ ; <nl> + } <nl> + / / returns a manager for given op , if it doesn ' t exists it creates one <nl> + std : : shared_ptr < tensorflow : : ResourceMgr > getManager ( const string & op_name ) ; <nl> + <nl> + private : <nl> + std : : unordered_map < string , std : : shared_ptr < tensorflow : : ResourceMgr > > <nl> + managers_ ; <nl> + tensorflow : : mutex map_mutex_ ; <nl> + } ; <nl> + <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + <nl> + # endif / / TENSORFLOW_CONTRIB_TENSORRT_RESOURCE_TRT_RESOURCE_MANAGER_H_ <nl> new file mode 100644 <nl> index 0000000000000 . . 3c85968ae7acf <nl> mmm / dev / null <nl> ppp b / tensorflow / contrib / tensorrt / resources / trt_resources . h <nl> <nl> + / * Copyright 2018 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # ifndef TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRTRESOURCES_H_ <nl> + # define TENSORFLOW_CONTRIB_TENSORRT_RESOURCES_TRTRESOURCES_H_ <nl> + <nl> + # include < list > <nl> + # include < sstream > <nl> + # include < string > <nl> + # include < thread > <nl> + # include < vector > <nl> + # include " tensorflow / contrib / tensorrt / log / trt_logger . h " <nl> + # include " tensorflow / core / framework / resource_mgr . h " <nl> + <nl> + # if GOOGLE_CUDA <nl> + # if GOOGLE_TENSORRT <nl> + # include " tensorflow / contrib / tensorrt / resources / trt_int8_calibrator . h " <nl> + # include " tensorrt / include / NvInfer . h " <nl> + <nl> + namespace tensorflow { <nl> + namespace tensorrt { <nl> + class TRTCalibrationResource : public tensorflow : : ResourceBase { <nl> + public : <nl> + TRTCalibrationResource ( ) <nl> + : calibrator_ ( nullptr ) , <nl> + builder_ ( nullptr ) , <nl> + network_ ( nullptr ) , <nl> + engine_ ( nullptr ) , <nl> + logger_ ( nullptr ) , <nl> + thr_ ( nullptr ) { } <nl> + string DebugString ( ) override { <nl> + std : : stringstream oss ; <nl> + oss < < " Calibrator = " < < std : : hex < < calibrator_ < < std : : dec < < std : : endl <nl> + < < " Builder = " < < std : : hex < < builder_ < < std : : dec < < std : : endl <nl> + < < " Network = " < < std : : hex < < network_ < < std : : dec < < std : : endl <nl> + < < " Engine = " < < std : : hex < < engine_ < < std : : dec < < std : : endl <nl> + < < " Logger = " < < std : : hex < < logger_ < < std : : dec < < std : : endl <nl> + < < " Thread = " < < std : : hex < < thr_ < < std : : dec < < std : : endl ; <nl> + return oss . str ( ) ; <nl> + } <nl> + ~ TRTCalibrationResource ( ) { <nl> + VLOG ( 0 ) < < " Destroying Calibration Resource " < < std : : endl < < DebugString ( ) ; <nl> + } <nl> + TRTInt8Calibrator * calibrator_ ; <nl> + nvinfer1 : : IBuilder * builder_ ; <nl> + nvinfer1 : : INetworkDefinition * network_ ; <nl> + nvinfer1 : : ICudaEngine * engine_ ; <nl> + tensorflow : : tensorrt : : Logger * logger_ ; <nl> + / / TODO ( sami ) : Use threadpool threads ! <nl> + std : : thread * thr_ ; <nl> + } ; <nl> + <nl> + class TRTWeightStore : public tensorflow : : ResourceBase { <nl> + public : <nl> + TRTWeightStore ( ) { } <nl> + std : : list < std : : vector < uint8_t > > store_ ; <nl> + string DebugString ( ) override { <nl> + std : : stringstream oss ; <nl> + size_t lenBytes = 0 ; <nl> + for ( const auto & v : store_ ) { <nl> + lenBytes + = v . size ( ) * sizeof ( uint8_t ) ; <nl> + } <nl> + oss < < " Number of entries = " < < store_ . size ( ) < < std : : endl <nl> + < < " Total number of bytes = " <nl> + < < store_ . size ( ) * sizeof ( std : : vector < uint8_t > ) + lenBytes < < std : : endl ; <nl> + return oss . str ( ) ; <nl> + } <nl> + virtual ~ TRTWeightStore ( ) { VLOG ( 1 ) < < " Destroying store " < < DebugString ( ) ; } <nl> + } ; <nl> + <nl> + class TRTEngineResource : public tensorflow : : ResourceBase { <nl> + public : <nl> + TRTEngineResource ( ) : runtime_ ( nullptr ) , ctx_ ( nullptr ) { } ; <nl> + string DebugString ( ) override { return string ( " " ) ; } <nl> + nvinfer1 : : IRuntime * runtime_ ; <nl> + nvinfer1 : : IExecutionContext * ctx_ ; <nl> + } ; <nl> + <nl> + } / / namespace tensorrt <nl> + } / / namespace tensorflow <nl> + # endif / / TENSORFLOW_CONTRIB_TENSORRT_RESOURCEMGR_TRTRESOURCES_H_ <nl> + # endif <nl> + # endif <nl> mmm a / tensorflow / contrib / timeseries / python / timeseries / BUILD <nl> ppp b / tensorflow / contrib / timeseries / python / timeseries / BUILD <nl> py_library ( <nl> " / / tensorflow / python : framework_ops " , <nl> " / / tensorflow / python : math_ops " , <nl> " / / tensorflow / python : state_ops " , <nl> + " / / tensorflow / python : summary " , <nl> " / / tensorflow / python : util " , <nl> " / / tensorflow / python : variable_scope " , <nl> " / / tensorflow / python / estimator : estimator_py " , <nl> " / / tensorflow / python / estimator : export " , <nl> " / / tensorflow / python / estimator : head " , <nl> + " / / tensorflow / python / estimator : metric_keys " , <nl> ] , <nl> ) <nl> <nl> mmm a / tensorflow / contrib / timeseries / python / timeseries / head . py <nl> ppp b / tensorflow / contrib / timeseries / python / timeseries / head . py <nl> <nl> <nl> from tensorflow . python . estimator import estimator_lib <nl> from tensorflow . python . estimator . canned import head as head_lib <nl> + from tensorflow . python . estimator . canned import metric_keys <nl> from tensorflow . python . estimator . export import export_lib <nl> from tensorflow . python . framework import dtypes <nl> from tensorflow . python . framework import ops <nl> <nl> from tensorflow . python . ops import state_ops <nl> from tensorflow . python . ops import variable_scope <nl> from tensorflow . python . util import nest <nl> + from tensorflow . python . summary import summary <nl> <nl> <nl> def time_series_regression_head ( model , <nl> def __init__ ( self , <nl> self . input_statistics_generator = input_statistics_generator <nl> self . _name = name <nl> <nl> + @ property <nl> + def name ( self ) : <nl> + return self . _name <nl> + <nl> + # TODO ( terrytangyuan ) : consolidate ` model_outputs ` and ` _Head . LossSpec ` <nl> + # once ` _Head . create_loss ` becomes extendable <nl> + def create_loss ( self , features , mode , logits = None , labels = None ) : <nl> + " " " See ` _Head ` . " " " <nl> + model_outputs = self . state_manager . define_loss ( <nl> + self . model , features , mode ) <nl> + summary . scalar ( <nl> + head_lib . _summary_key ( self . _name , metric_keys . MetricKeys . LOSS ) , <nl> + model_outputs . loss ) <nl> + return model_outputs <nl> + <nl> + @ property <nl> + def logits_dimension ( self ) : <nl> + " " " See ` _Head ` . " " " <nl> + return 1 <nl> + <nl> def _train_ops ( self , features ) : <nl> " " " Add training ops to the graph . " " " <nl> + mode = estimator_lib . ModeKeys . TRAIN <nl> with variable_scope . variable_scope ( <nl> " model " , <nl> # Use ResourceVariables to avoid race conditions . <nl> use_resource = True ) : <nl> - model_outputs = self . state_manager . define_loss ( <nl> - self . model , features , estimator_lib . ModeKeys . TRAIN ) <nl> + model_outputs = self . create_loss ( features , mode ) <nl> <nl> train_op = optimizers . optimize_loss ( <nl> model_outputs . loss , <nl> def _train_ops ( self , features ) : <nl> learning_rate = None ) <nl> return estimator_lib . EstimatorSpec ( <nl> loss = model_outputs . loss , <nl> - mode = estimator_lib . ModeKeys . TRAIN , <nl> + mode = mode , <nl> train_op = train_op ) <nl> <nl> - # TODO ( terrytangyuan ) : suffix summary and metrics keys by ` " / " + name ` <nl> - @ property <nl> - def name ( self ) : <nl> - return self . _name <nl> - <nl> - # TODO ( terrytangyuan ) : unused for now . Need to decouple <nl> - # ` state_manager . define_loss ` to satisfy the extendable return signature of <nl> - # ` _Head . create_loss ` . <nl> - def create_loss ( self , features , mode , logits , labels ) : <nl> - " " " See ` _Head ` . " " " <nl> - return None <nl> - <nl> - # TODO ( terrytangyuan ) : check label dimension <nl> - @ property <nl> - def logits_dimension ( self ) : <nl> - return None <nl> - <nl> def _evaluate_ops ( self , features ) : <nl> " " " Add ops for evaluation ( aka filtering ) to the graph . " " " <nl> + mode = estimator_lib . ModeKeys . EVAL <nl> with variable_scope . variable_scope ( " model " , use_resource = True ) : <nl> - model_outputs = self . state_manager . define_loss ( <nl> - self . model , features , estimator_lib . ModeKeys . EVAL ) <nl> + model_outputs = self . create_loss ( features , mode ) <nl> metrics = { } <nl> # Just output in - sample predictions for the last chunk seen <nl> for prediction_key , prediction_value in model_outputs . predictions . items ( ) : <nl> def _evaluate_ops ( self , features ) : <nl> model_outputs . end_state ) ) <nl> return estimator_lib . EstimatorSpec ( <nl> loss = model_outputs . loss , <nl> - mode = estimator_lib . ModeKeys . EVAL , <nl> + mode = mode , <nl> eval_metric_ops = metrics , <nl> predictions = { } ) <nl> <nl> def _serving_ops ( self , features ) : <nl> with variable_scope . variable_scope ( " model " , use_resource = True ) : <nl> prediction_outputs = self . model . predict ( features = features ) <nl> with variable_scope . variable_scope ( " model " , reuse = True ) : <nl> - filtering_outputs = self . state_manager . define_loss ( <nl> - self . model , features , estimator_lib . ModeKeys . EVAL ) <nl> - <nl> + filtering_outputs = self . create_loss ( <nl> + features , estimator_lib . ModeKeys . EVAL ) <nl> return estimator_lib . EstimatorSpec ( <nl> mode = estimator_lib . ModeKeys . PREDICT , <nl> export_outputs = { <nl> def _gather_state ( self , features ) : <nl> <nl> def create_estimator_spec ( self , features , mode , labels = None ) : <nl> " " " Performs basic error checking and returns an EstimatorSpec . " " " <nl> - with ops . name_scope ( " head " ) : <nl> + with ops . name_scope ( self . _name , " head " ) : <nl> if labels : <nl> raise ValueError ( <nl> " The model received a ` labels ` dictionary , which is " <nl> mmm a / tensorflow / contrib / verbs / README . md <nl> ppp b / tensorflow / contrib / verbs / README . md <nl> When the receiver receives the RDMA write , it will locate the relevant * * RdmaTen <nl> <nl> 1 . When the sender receives a tensor request , the source tensor may or may not be ready yet . The situation is handled through a process of tag matching : <nl> * If the request arrives before the tensor is ready , then a callback is put in a local table , and will be invoked once the tensor arrives . <nl> - * If the tensor is ready before the request arives , than the tensor is put in a local table . When the request arrives , it will invoke the callback immediately . <nl> + * If the tensor is ready before the request arrives , than the tensor is put in a local table . When the request arrives , it will invoke the callback immediately . <nl> In code it is done by calling * * RecvLocalAsync ( ) * * , which receives the tensor ' s key , step - id , and the callback . <nl> 2 . When the callback is invoked , the relevant tensor is removed from the tag matching table . In the case where we need to send the tensor ' s meta - data , the * * RdmaTensorResponse * * will store a copy of the tensor until the re - request arrives . <nl> 3 . The sending of protocol messages ( * * RDMA_MESSAGE_TENSOR_REQUEST * * , * * RDMA_MESSAGE_META_DATA_RESPONSE * * and * * RDMA_MESSAGE_TENSOR_RE_REQUEST * * ) is done by the class * * RdmaMessageBuffer * * . All messages are sent using RDMA writes from / to fixed messages buffers . This implies that we cannot send on a specific channel more than one message at a time . In order to synchronize the messages , the * * RdmaMessageBuffer * * holds the a local and remote buffer statuses which can be either busy or idle . When a write is issued , both statuses will be changed to busy . When the write - complete event is received , the local status is changed to idle . When the write is received on the remote side , the remote side will parse the message , and return an ACK back to the sending side on which the sending side will update the remote status to idle . When both the local and remote statuses are idle , the next message can be sent . <nl> mmm a / tensorflow / contrib / verbs / patch_notes_verbs_with_0_copies . md <nl> ppp b / tensorflow / contrib / verbs / patch_notes_verbs_with_0_copies . md <nl> The protocol messages themselves will remain mostly unchanged at the first stage <nl> * type - The message type . <nl> * request_index - Request index . <nl> * is_dead / data_type / tensor_shape / tensor_bytes - The up - to - date meta - data . <nl> - * * * RDMA_MESSAGE_BUFFER_RESPONSE * * - ( receiver = = > sender ) Tensor re - requset after meta - data update and reallocation of result / proxy tensors . <nl> + * * * RDMA_MESSAGE_BUFFER_RESPONSE * * - ( receiver = = > sender ) Tensor re - request after meta - data update and reallocation of result / proxy tensors . <nl> * type - The message type . <nl> * name ( name_size ) - Name of the requested tensor . <nl> * step_id - Step ID . <nl> mmm a / tensorflow / contrib / verbs / rdma . cc <nl> ppp b / tensorflow / contrib / verbs / rdma . cc <nl> limitations under the License . <nl> # include " tensorflow / core / distributed_runtime / rendezvous_mgr_interface . h " <nl> # include " tensorflow / core / distributed_runtime / rpc / grpc_util . h " <nl> # include " tensorflow / core / distributed_runtime / session_mgr . h " <nl> + # include " tensorflow / core / distributed_runtime / rpc / grpc_util . h " <nl> # include " tensorflow / core / framework / rendezvous . h " <nl> # include " tensorflow / core / framework / tensor . h " <nl> # include " tensorflow / core / lib / core / status . h " <nl> new file mode 100644 <nl> index 0000000000000 . . e21f56ba5b926 <nl> mmm / dev / null <nl> ppp b / tensorflow / core / api_def / base_api / api_def_UniqueWithCountsV2 . pbtxt <nl> <nl> + op { <nl> + graph_op_name : " UniqueWithCountsV2 " <nl> + in_arg { <nl> + name : " x " <nl> + description : < < END <nl> + A ` Tensor ` . <nl> + END <nl> + } <nl> + in_arg { <nl> + name : " axis " <nl> + description : < < END <nl> + A ` Tensor ` of type ` int32 ` ( default : None ) . The axis of the Tensor to <nl> + find the unique elements . <nl> + END <nl> + } <nl> + out_arg { <nl> + name : " y " <nl> + description : < < END <nl> + A ` Tensor ` . Unique elements along the ` axis ` of ` Tensor ` x . <nl> + END <nl> + } <nl> + out_arg { <nl> + name : " idx " <nl> + description : < < END <nl> + A 1 - D Tensor . Has the same type as x that contains the index of each <nl> + value of x in the output y . <nl> + END <nl> + } <nl> + out_arg { <nl> + name : " count " <nl> + description : < < END <nl> + A 1 - D Tensor . The count of each value of x in the output y . <nl> + END <nl> + } <nl> + summary : " Finds unique elements along an axis of a tensor . " <nl> + description : < < END <nl> + This operation either returns a tensor ` y ` containing unique elements <nl> + along the ` axis ` of a tensor . The returned unique elements is sorted <nl> + in the same order as they occur along ` axis ` in ` x ` . <nl> + This operation also returns a tensor ` idx ` and a tensor ` count ` <nl> + that are the same size as the number of the elements in ` x ` along the <nl> + ` axis ` dimension . The ` idx ` contains the index in the unique output ` y ` <nl> + and the ` count ` contains the count in the unique output ` y ` . <nl> + In other words , for an ` 1 - D ` tensor ` x ` with ` axis = None : <nl> + <nl> + ` y [ idx [ i ] ] = x [ i ] for i in [ 0 , 1 , . . . , rank ( x ) - 1 ] ` <nl> + <nl> + For example : <nl> + <nl> + ` ` ` <nl> + # tensor ' x ' is [ 1 , 1 , 2 , 4 , 4 , 4 , 7 , 8 , 8 ] <nl> + y , idx , count = unique_with_counts ( x ) <nl> + y = = > [ 1 , 2 , 4 , 7 , 8 ] <nl> + idx = = > [ 0 , 0 , 1 , 2 , 2 , 2 , 3 , 4 , 4 ] <nl> + count = = > [ 2 , 1 , 3 , 1 , 2 ] <nl> + ` ` ` <nl> + <nl> + For an ` 2 - D ` tensor ` x ` with ` axis = 0 ` : <nl> + <nl> + ` ` ` <nl> + # tensor ' x ' is [ [ 1 , 0 , 0 ] , <nl> + # [ 1 , 0 , 0 ] , <nl> + # [ 2 , 0 , 0 ] ] <nl> + y , idx , count = unique_with_counts ( x , axis = 0 ) <nl> + y = = > [ [ 1 , 0 , 0 ] , <nl> + [ 2 , 0 , 0 ] ] <nl> + idx = = > [ 0 , 0 , 1 ] <nl> + count = = > [ 2 , 1 ] <nl> + ` ` ` <nl> + <nl> + For an ` 2 - D ` tensor ` x ` with ` axis = 1 ` : <nl> + <nl> + ` ` ` <nl> + # tensor ' x ' is [ [ 1 , 0 , 0 ] , <nl> + # [ 1 , 0 , 0 ] , <nl> + # [ 2 , 0 , 0 ] ] <nl> + y , idx , count = unique_with_counts ( x , axis = 1 ) <nl> + y = = > [ [ 1 , 0 ] , <nl> + [ 1 , 0 ] , <nl> + [ 2 , 0 ] ] <nl> + idx = = > [ 0 , 1 , 1 ] <nl> + count = = > [ 1 , 2 ] <nl> + ` ` ` <nl> + END <nl> + } <nl> mmm a / tensorflow / core / api_def / base_api / api_def_UnsortedSegmentMax . pbtxt <nl> ppp b / tensorflow / core / api_def / base_api / api_def_UnsortedSegmentMax . pbtxt <nl> Has same shape as data , except for dimension 0 which <nl> has size ` num_segments ` . <nl> END <nl> } <nl> - summary : " Computes the Max along segments of a tensor . " <nl> + summary : " Computes the maximum along segments of a tensor . " <nl> description : < < END <nl> Read @ { $ math_ops # Segmentation $ the section on segmentation } for an explanation of <nl> segments . <nl> <nl> - This operator is similar to the [ unsorted segment sum operator ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> - Instead of computing the sum over segments , it computes the maximum <nl> - such that : <nl> + This operator is similar to the unsorted segment sum operator found <nl> + [ ( here ) ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> + Instead of computing the sum over segments , it computes the maximum such that : <nl> <nl> \ \ ( output_i = \ max_j data_j \ \ ) where max is over ` j ` such <nl> that ` segment_ids [ j ] = = i ` . <nl> <nl> - If the maximum is empty for a given segment ID ` i ` , it outputs the smallest possible value for specific numeric type , <nl> - ` output [ i ] = numeric_limits < T > : : min ( ) ` . <nl> + If the maximum is empty for a given segment ID ` i ` , it outputs the smallest <nl> + possible value for the specific numeric type , <nl> + ` output [ i ] = numeric_limits < T > : : lowest ( ) ` . <nl> <nl> < div style = " width : 70 % ; margin : auto ; margin - bottom : 10px ; margin - top : 20px ; " > <nl> < img style = " width : 100 % " src = " https : / / www . tensorflow . org / images / UnsortedSegmentMax . png " alt > <nl> new file mode 100644 <nl> index 0000000000000 . . 55ea69b5dd5f7 <nl> mmm / dev / null <nl> ppp b / tensorflow / core / api_def / base_api / api_def_UnsortedSegmentMin . pbtxt <nl> <nl> + op { <nl> + graph_op_name : " UnsortedSegmentMin " <nl> + in_arg { <nl> + name : " segment_ids " <nl> + description : < < END <nl> + A 1 - D tensor whose rank is equal to the rank of ` data ` ' s <nl> + first dimension . <nl> + END <nl> + } <nl> + out_arg { <nl> + name : " output " <nl> + description : < < END <nl> + Has same shape as data , except for dimension 0 which <nl> + has size ` num_segments ` . <nl> + END <nl> + } <nl> + summary : " Computes the minimum along segments of a tensor . " <nl> + description : < < END <nl> + Read @ { $ math_ops # segmentation $ the section on segmentation } for an explanation of <nl> + segments . <nl> + <nl> + This operator is similar to the unsorted segment sum operator found <nl> + [ ( here ) ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> + Instead of computing the sum over segments , it computes the minimum such that : <nl> + <nl> + \ \ ( output_i = \ min_j data_j \ \ ) where min is over ` j ` such <nl> + that ` segment_ids [ j ] = = i ` . <nl> + <nl> + If the minimum is empty for a given segment ID ` i ` , it outputs the largest <nl> + possible value for the specific numeric type , <nl> + ` output [ i ] = numeric_limits < T > : : max ( ) ` . <nl> + END <nl> + } <nl> new file mode 100644 <nl> index 0000000000000 . . 577ff53d60c5a <nl> mmm / dev / null <nl> ppp b / tensorflow / core / api_def / base_api / api_def_UnsortedSegmentProd . pbtxt <nl> <nl> + op { <nl> + graph_op_name : " UnsortedSegmentProd " <nl> + in_arg { <nl> + name : " segment_ids " <nl> + description : < < END <nl> + A 1 - D tensor whose rank is equal to the rank of ` data ` ' s <nl> + first dimension . <nl> + END <nl> + } <nl> + out_arg { <nl> + name : " output " <nl> + description : < < END <nl> + Has same shape as data , except for dimension 0 which <nl> + has size ` num_segments ` . <nl> + END <nl> + } <nl> + summary : " Computes the product along segments of a tensor . " <nl> + description : < < END <nl> + Read @ { $ math_ops # segmentation $ the section on segmentation } for an explanation of <nl> + segments . <nl> + <nl> + This operator is similar to the unsorted segment sum operator found <nl> + [ ( here ) ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> + Instead of computing the sum over segments , it computes the product of all <nl> + entries belonging to a segment such that : <nl> + <nl> + \ \ ( output_i = \ prod_j data_j \ \ ) where the product is over ` j ` such <nl> + that ` segment_ids [ j ] = = i ` . <nl> + <nl> + If there is no entry for a given segment ID ` i ` , it outputs 1 . <nl> + END <nl> + } <nl> new file mode 100644 <nl> index 0000000000000 . . 71b35eaab5f4a <nl> mmm / dev / null <nl> ppp b / tensorflow / core / api_def / python_api / api_def_UniqueWithCounts . pbtxt <nl> <nl> + op { <nl> + graph_op_name : " UniqueWithCounts " <nl> + visibility : HIDDEN <nl> + } <nl> new file mode 100644 <nl> index 0000000000000 . . 7876e55cf3e2c <nl> mmm / dev / null <nl> ppp b / tensorflow / core / api_def / python_api / api_def_UniqueWithCountsV2 . pbtxt <nl> <nl> + op { <nl> + graph_op_name : " UniqueWithCountsV2 " <nl> + visibility : HIDDEN <nl> + } <nl> mmm a / tensorflow / core / common_runtime / gpu / gpu_device . h <nl> ppp b / tensorflow / core / common_runtime / gpu / gpu_device . h <nl> class BaseGPUDevice : public LocalDevice { <nl> const TensorReferenceVector & tensor_refs ) override ; <nl> <nl> Status FillContextMap ( const Graph * graph , <nl> - DeviceContextMap * device_context_map ) ; <nl> + DeviceContextMap * device_context_map ) override ; <nl> <nl> void Compute ( OpKernel * op_kernel , OpKernelContext * context ) override ; <nl> <nl> mmm a / tensorflow / core / distributed_runtime / session_mgr . cc <nl> ppp b / tensorflow / core / distributed_runtime / session_mgr . cc <nl> SessionMgr : : SessionMgr ( <nl> worker_cache_factory_ ( std : : move ( worker_cache_factory ) ) { } <nl> <nl> string SessionMgr : : WorkerNameFromServerDef ( const ServerDef & server_def ) { <nl> - return strings : : StrCat ( " / job : " , server_def . job_name ( ) , <nl> - " / replica : 0 / task : " , server_def . task_index ( ) ) ; <nl> + return strings : : StrCat ( " / job : " , server_def . job_name ( ) , " / replica : 0 / task : " , <nl> + server_def . task_index ( ) ) ; <nl> } <nl> <nl> Status SessionMgr : : CreateSession ( const string & session , <nl> mmm a / tensorflow / core / framework / numeric_types . h <nl> ppp b / tensorflow / core / framework / numeric_types . h <nl> limitations under the License . <nl> # define TENSORFLOW_FRAMEWORK_NUMERIC_TYPES_H_ <nl> <nl> # include < complex > <nl> - <nl> # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> / / Disable clang - format to prevent ' FixedPoint ' header from being included <nl> / / before ' Tensor ' header on which it depends . <nl> typedef Eigen : : QUInt16 quint16 ; <nl> <nl> } / / namespace tensorflow <nl> <nl> + <nl> + <nl> + <nl> + static inline tensorflow : : bfloat16 FloatToBFloat16 ( float float_val ) { <nl> + # if __BYTE_ORDER__ = = __ORDER_BIG_ENDIAN__ <nl> + return * reinterpret_cast < tensorflow : : bfloat16 * > ( <nl> + reinterpret_cast < uint16_t * > ( & float_val ) ) ; <nl> + # else <nl> + return * reinterpret_cast < tensorflow : : bfloat16 * > ( <nl> + & ( reinterpret_cast < uint16_t * > ( & float_val ) [ 1 ] ) ) ; <nl> + # endif <nl> + } <nl> + <nl> namespace Eigen { <nl> - / / TOOD ( xpan ) : We probably need to overwrite more methods to have correct eigen <nl> - / / behavior . E . g . loest ( ) , is_integer , etc . See NumTraits . h in eigen . <nl> + / / TODO ( xpan ) : We probably need to overwrite more methods to have correct eigen <nl> + / / behavior . E . g . epsilon ( ) , dummy_precision , etc . See NumTraits . h in eigen . <nl> template < > <nl> struct NumTraits < tensorflow : : bfloat16 > <nl> - : GenericNumTraits < tensorflow : : bfloat16 > { } ; <nl> + : GenericNumTraits < tensorflow : : bfloat16 > { <nl> + enum { <nl> + IsInteger = 0 , <nl> + IsSigned = 1 , <nl> + RequireInitialization = 0 <nl> + } ; <nl> + static EIGEN_STRONG_INLINE tensorflow : : bfloat16 highest ( ) { <nl> + return FloatToBFloat16 ( NumTraits < float > : : highest ( ) ) ; <nl> + } <nl> + <nl> + static EIGEN_STRONG_INLINE tensorflow : : bfloat16 lowest ( ) { <nl> + return FloatToBFloat16 ( NumTraits < float > : : lowest ( ) ) ; <nl> + } <nl> + <nl> + static EIGEN_STRONG_INLINE tensorflow : : bfloat16 infinity ( ) { <nl> + return FloatToBFloat16 ( NumTraits < float > : : infinity ( ) ) ; <nl> + } <nl> + <nl> + static EIGEN_STRONG_INLINE tensorflow : : bfloat16 quiet_NaN ( ) { <nl> + return FloatToBFloat16 ( NumTraits < float > : : quiet_NaN ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> <nl> using : : tensorflow : : operator = = ; <nl> using : : tensorflow : : operator ! = ; <nl> mmm a / tensorflow / core / framework / variant_op_registry . h <nl> ppp b / tensorflow / core / framework / variant_op_registry . h <nl> Status BinaryOpVariants ( OpKernelContext * ctx , VariantBinaryOp op , <nl> return errors : : Internal ( <nl> " No unary variant binary_op function found for binary variant op " <nl> " enum : " , <nl> - op , " Variant type_name : ' " , a . TypeName ( ) , <nl> - " ' for device type : " , device ) ; <nl> + op , " Variant type_name : ' " , a . TypeName ( ) , " ' for device type : " , <nl> + device ) ; <nl> } <nl> return ( * binary_op_fn ) ( ctx , a , b , out ) ; <nl> } <nl> mmm a / tensorflow / core / grappler / optimizers / BUILD <nl> ppp b / tensorflow / core / grappler / optimizers / BUILD <nl> cc_library ( <nl> " / / tensorflow / core / grappler : op_types " , <nl> " / / tensorflow / core / grappler : utils " , <nl> " / / tensorflow / core / grappler / costs : graph_properties " , <nl> + " / / tensorflow / core / grappler / utils : frame " , <nl> ] , <nl> ) <nl> <nl> tf_cc_test ( <nl> name = " loop_optimizer_test " , <nl> size = " small " , <nl> srcs = [ " loop_optimizer_test . cc " ] , <nl> + tags = [ <nl> + " manual " , <nl> + " no_oss " , # b / 74111495 <nl> + " notap " , <nl> + ] , <nl> deps = [ <nl> " : loop_optimizer " , <nl> " / / tensorflow / cc : cc_ops " , <nl> mmm a / tensorflow / core / grappler / optimizers / loop_optimizer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / loop_optimizer . cc <nl> limitations under the License . <nl> <nl> # include " tensorflow / core / grappler / optimizers / loop_optimizer . h " <nl> <nl> + # include < algorithm > <nl> + # include < limits > <nl> # include < unordered_map > <nl> # include < unordered_set > <nl> + # include < vector > <nl> + # include < deque > <nl> <nl> # include " tensorflow / core / framework / attr_value . pb . h " <nl> + # include " tensorflow / core / framework / node_def . pb . h " <nl> # include " tensorflow / core / framework / op . h " <nl> + # include " tensorflow / core / framework / types . h " <nl> # include " tensorflow / core / grappler / costs / graph_properties . h " <nl> # include " tensorflow / core / grappler / grappler_item . h " <nl> # include " tensorflow / core / grappler / op_types . h " <nl> # include " tensorflow / core / grappler / optimizers / constant_folding . h " <nl> # include " tensorflow / core / grappler / utils . h " <nl> + # include " tensorflow / core / grappler / utils / frame . h " <nl> # include " tensorflow / core / lib / core / errors . h " <nl> # include " tensorflow / core / lib / core / stringpiece . h " <nl> # include " tensorflow / core / lib / strings / strcat . h " <nl> + # include " tensorflow / core / platform / tensor_coding . h " <nl> + # include " tensorflow / core / util / device_name_utils . h " <nl> + # include " tensorflow / core / util / saved_tensor_slice_util . h " <nl> + <nl> + using tensorflow : : strings : : StrCat ; <nl> <nl> namespace tensorflow { <nl> namespace grappler { <nl> Status RemoveStackOps ( const GraphDef & graph , GraphDef * optimized_graph ) { <nl> <nl> } / / namespace <nl> <nl> + Status LoopOptimizer : : LINMHandleInvariantEnter ( NodeDef * node , <nl> + const int num_outputs ) { <nl> + auto consumers = node_map_ - > GetOutputs ( node - > name ( ) ) ; <nl> + std : : vector < string > enter_control_inputs ; <nl> + string enter_input ; <nl> + for ( auto & input : node - > input ( ) ) { <nl> + if ( IsControlInput ( input ) ) { <nl> + enter_control_inputs . push_back ( input ) ; <nl> + } else { <nl> + enter_input = input ; <nl> + } <nl> + } <nl> + for ( auto * consumer : consumers ) { <nl> + if ( invariant_nodes_ . count ( consumer ) ) { <nl> + for ( int i = 0 ; i < consumer - > input_size ( ) ; + + i ) { <nl> + if ( NodeName ( consumer - > input ( i ) ) = = node - > name ( ) ) { <nl> + consumer - > set_input ( i , enter_input ) ; <nl> + node_map_ - > AddOutput ( NodeName ( enter_input ) , consumer - > name ( ) ) ; <nl> + node_map_ - > RemoveOutput ( node - > name ( ) , consumer - > name ( ) ) ; <nl> + } <nl> + } <nl> + for ( auto & control_input : enter_control_inputs ) { <nl> + consumer - > add_input ( control_input ) ; <nl> + node_map_ - > AddOutput ( NodeName ( control_input ) , consumer - > name ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : LINMHandleConst ( NodeDef * node , <nl> + const int num_outputs , const int frame_id ) { <nl> + NodeDef * const_node ; <nl> + if ( num_outputs = = 0 ) { <nl> + / / all successor nodes are invariant <nl> + / / Remove the control inputs from this frame to the const node , <nl> + / / when moving it out of the frame ( in parent frame ) <nl> + const_node = node ; <nl> + node_map_ - > RemoveInputs ( node - > name ( ) ) ; <nl> + node - > clear_input ( ) ; <nl> + } else { <nl> + / / some successor nodes are variant <nl> + / / Have to keep the const node in the frame , <nl> + / / so create a new one outside the frame ( in parent frame ) <nl> + const_node = optimized_graph_ - > add_node ( ) ; <nl> + const_node - > set_name ( AddPrefixToNodeName ( node - > name ( ) , kLoopOptimizer ) ) ; <nl> + const_node - > set_op ( " Const " ) ; <nl> + const_node - > set_device ( node - > device ( ) ) ; <nl> + * const_node - > mutable_attr ( ) = node - > attr ( ) ; <nl> + node_map_ - > AddNode ( const_node - > name ( ) , const_node ) ; <nl> + auto consumers = node_map_ - > GetOutputs ( node - > name ( ) ) ; <nl> + for ( auto * consumer : consumers ) { <nl> + if ( invariant_nodes_ . count ( consumer ) ) { <nl> + for ( int i = 0 ; i < consumer - > input_size ( ) ; + + i ) { <nl> + if ( NodeName ( consumer - > input ( i ) ) = = node - > name ( ) ) { <nl> + if ( IsControlInput ( consumer - > input ( i ) ) ) { <nl> + * consumer - > mutable_input ( i ) = AsControlDependency ( * const_node ) ; <nl> + } else { <nl> + * consumer - > mutable_input ( i ) = const_node - > name ( ) ; <nl> + } <nl> + node_map_ - > AddOutput ( const_node - > name ( ) , consumer - > name ( ) ) ; <nl> + node_map_ - > RemoveOutput ( node - > name ( ) , consumer - > name ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + / / add a control input from the parent frame <nl> + auto parent_it = frame_parent_ . find ( frame_id ) ; <nl> + if ( parent_it ! = frame_parent_ . end ( ) ) { <nl> + int parent_id = parent_it - > second ; <nl> + auto loop_cond_it = loop_cond_ . find ( parent_id ) ; <nl> + if ( loop_cond_it = = loop_cond_ . end ( ) ) { <nl> + return errors : : InvalidArgument ( <nl> + " Frame " , frame_id , " doesn ' t have a LoopCond node " ) ; <nl> + } <nl> + auto & loop_cond_name = loop_cond_it - > second - > name ( ) ; <nl> + NodeDef * switch_node = nullptr ; <nl> + for ( auto * node : node_map_ - > GetOutputs ( loop_cond_name ) ) { <nl> + if ( node - > op ( ) = = " Switch " ) { <nl> + switch_node = node ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( ! switch_node ) { <nl> + return errors : : InvalidArgument ( <nl> + " LoopCond node of Frame " , frame_id , <nl> + " doesn ' t connect to any Switch node " ) ; <nl> + } <nl> + string switch_output = StrCat ( switch_node - > name ( ) , " : 1 " ) ; <nl> + const string ctrl_dep = ConstantFolding : : AddControlDependency ( <nl> + switch_output , optimized_graph_ , node_map_ . get ( ) ) ; <nl> + const_node - > add_input ( ctrl_dep ) ; <nl> + node_map_ - > AddOutput ( NodeName ( ctrl_dep ) , const_node - > name ( ) ) ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : LINMHandleInvariantNode ( NodeDef * node , <nl> + const int num_outputs , const int frame_id ) { <nl> + / / have to remove control inputs to the invariant node from the same frame <nl> + / / when moving this node out of this frame <nl> + for ( int i = 0 ; i < node - > input_size ( ) ; + + i ) { <nl> + if ( IsControlInput ( node - > input ( i ) ) ) { <nl> + node - > mutable_input ( ) - > SwapElements ( i , node - > input_size ( ) - 1 ) ; <nl> + node - > mutable_input ( ) - > RemoveLast ( ) ; <nl> + } <nl> + } <nl> + if ( num_outputs = = 0 ) { <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + DataTypeVector input_types ; <nl> + DataTypeVector output_types ; <nl> + OpRegistryInterface * op_registry = OpRegistry : : Global ( ) ; <nl> + const OpRegistrationData * op_reg_data = nullptr ; <nl> + TF_RETURN_IF_ERROR ( <nl> + op_registry - > LookUp ( node - > op ( ) , & op_reg_data ) ) ; <nl> + TF_RETURN_IF_ERROR ( <nl> + InOutTypesForNode ( * node , op_reg_data - > op_def , <nl> + & input_types , & output_types ) ) ; <nl> + <nl> + auto consumers = node_map_ - > GetOutputs ( node - > name ( ) ) ; <nl> + string fname = invariant_enters_ [ frame_id ] [ 0 ] - > attr ( ) . at ( " frame_name " ) . s ( ) ; <nl> + int piterations = invariant_enters_ [ frame_id ] [ 0 ] <nl> + - > attr ( ) . at ( " parallel_iterations " ) . i ( ) ; <nl> + for ( auto * consumer : consumers ) { <nl> + if ( ! invariant_nodes_ . count ( consumer ) ) { <nl> + for ( int i = 0 ; i < consumer - > input_size ( ) ; + + i ) { <nl> + int port ; <nl> + string node_name = ParseNodeName ( consumer - > input ( i ) , & port ) ; <nl> + if ( node_name ! = node - > name ( ) ) { <nl> + continue ; <nl> + } <nl> + if ( port < 0 ) { <nl> + return errors : : InvalidArgument ( <nl> + " Invariant node should not have control outputs " <nl> + " to variant node " ) ; <nl> + } <nl> + DataType output_type = output_types [ port ] ; <nl> + NodeDef * new_enter = optimized_graph_ - > add_node ( ) ; <nl> + new_enter - > set_op ( " Enter " ) ; <nl> + new_enter - > set_device ( node - > device ( ) ) ; <nl> + new_enter - > set_name ( AddPrefixToNodeName ( <nl> + StrCat ( fname , " _enter_ " , new_enter_id_ + + ) , kLoopOptimizer ) ) ; <nl> + AttrValue data_type ; <nl> + data_type . set_type ( output_type ) ; <nl> + new_enter - > mutable_attr ( ) - > insert ( { " T " , data_type } ) ; <nl> + AttrValue frame_name ; <nl> + frame_name . set_s ( fname ) ; <nl> + new_enter - > mutable_attr ( ) - > insert ( { " frame_name " , frame_name } ) ; <nl> + AttrValue is_const ; <nl> + is_const . set_b ( true ) ; <nl> + new_enter - > mutable_attr ( ) - > insert ( { " is_constant " , is_const } ) ; <nl> + AttrValue parallel_iterations ; <nl> + parallel_iterations . set_i ( piterations ) ; <nl> + new_enter - > mutable_attr ( ) - > insert ( <nl> + { " parallel_iterations " , parallel_iterations } ) ; <nl> + new_enter - > add_input ( consumer - > input ( i ) ) ; <nl> + * consumer - > mutable_input ( i ) = new_enter - > name ( ) ; <nl> + node_map_ - > AddNode ( new_enter - > name ( ) , new_enter ) ; <nl> + node_map_ - > AddOutput ( node - > name ( ) , new_enter - > name ( ) ) ; <nl> + node_map_ - > AddOutput ( new_enter - > name ( ) , consumer - > name ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : MoveInvariantNodes ( const int frame_id ) { <nl> + for ( auto iter = invariant_nodes_ . begin ( ) ; <nl> + iter ! = invariant_nodes_ . end ( ) ; + + iter ) { <nl> + auto * invariant_node = iter - > first ; <nl> + const int num_outputs = iter - > second ; <nl> + if ( IsEnter ( * invariant_node ) ) { <nl> + TF_RETURN_IF_ERROR ( <nl> + LINMHandleInvariantEnter ( invariant_node , num_outputs ) ) ; <nl> + } else if ( IsConstant ( * invariant_node ) ) { <nl> + TF_RETURN_IF_ERROR ( <nl> + LINMHandleConst ( invariant_node , num_outputs , frame_id ) ) ; <nl> + } else { <nl> + TF_RETURN_IF_ERROR ( <nl> + LINMHandleInvariantNode ( invariant_node , num_outputs , frame_id ) ) ; <nl> + } <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : RevertInvariantNodes ( ) { <nl> + std : : deque < const NodeDef * > reverted_nodes ; <nl> + for ( auto iter = invariant_nodes_ . begin ( ) ; iter ! = invariant_nodes_ . end ( ) ; ) { <nl> + bool erased = false ; <nl> + const auto * node = iter - > first ; <nl> + if ( ! IsConstant ( * node ) & & ! IsEnter ( * node ) & & iter - > second > 0 ) { <nl> + auto & consumers = node_map_ - > GetOutputs ( node - > name ( ) ) ; <nl> + for ( auto * consumer : consumers ) { <nl> + if ( ! invariant_nodes_ . count ( consumer ) ) { <nl> + for ( const auto & input : consumer - > input ( ) ) { <nl> + if ( IsControlInput ( input ) & & NodeName ( input ) = = node - > name ( ) ) { <nl> + reverted_nodes . push_back ( node ) ; <nl> + invariant_nodes_ . erase ( iter + + ) ; <nl> + erased = true ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( erased ) break ; <nl> + } <nl> + } <nl> + } <nl> + if ( ! erased ) + + iter ; <nl> + } <nl> + while ( ! reverted_nodes . empty ( ) ) { <nl> + const auto * node = reverted_nodes . front ( ) ; <nl> + reverted_nodes . pop_front ( ) ; <nl> + std : : set < NodeDef * > producers ; <nl> + for ( const auto & input : node - > input ( ) ) { <nl> + auto * producer = node_map_ - > GetNode ( input ) ; <nl> + auto iter = invariant_nodes_ . find ( producer ) ; <nl> + if ( iter ! = invariant_nodes_ . end ( ) ) { <nl> + if ( IsControlInput ( input ) & & <nl> + ! IsConstant ( * producer ) & & ! IsEnter ( * producer ) ) { <nl> + reverted_nodes . push_back ( producer ) ; <nl> + invariant_nodes_ . erase ( iter ) ; <nl> + } else { <nl> + producers . insert ( producer ) ; <nl> + } <nl> + } <nl> + } <nl> + for ( auto * producer : producers ) { <nl> + auto iter = invariant_nodes_ . find ( producer ) ; <nl> + if ( iter ! = invariant_nodes_ . end ( ) ) { <nl> + + + iter - > second ; <nl> + } <nl> + } <nl> + for ( auto * consumer : node_map_ - > GetOutputs ( node - > name ( ) ) ) { <nl> + auto iter = invariant_nodes_ . find ( consumer ) ; <nl> + if ( iter ! = invariant_nodes_ . end ( ) ) { <nl> + reverted_nodes . push_back ( consumer ) ; <nl> + invariant_nodes_ . erase ( iter ) ; <nl> + } <nl> + } <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : FindInvariantNodes ( NodeDef * node ) { <nl> + auto consumers = node_map_ - > GetOutputs ( node - > name ( ) ) ; <nl> + invariant_nodes_ . insert ( std : : make_pair ( node , consumers . size ( ) ) ) ; <nl> + for ( auto * consumer : consumers ) { <nl> + if ( invariant_nodes_ . count ( consumer ) | | <nl> + ModifiesFrameInfo ( * consumer ) ) { <nl> + continue ; <nl> + } <nl> + bool is_invariant = true ; <nl> + for ( const auto & input : consumer - > input ( ) ) { <nl> + if ( ! IsControlInput ( input ) ) { <nl> + const auto & name = NodeName ( input ) ; <nl> + auto * producer = node_map_ - > GetNode ( name ) ; <nl> + if ( ! invariant_nodes_ . count ( producer ) ) { <nl> + if ( IsConstant ( * producer ) ) { <nl> + invariant_nodes_ . insert ( <nl> + std : : make_pair ( producer , node_map_ - > GetOutputs ( name ) . size ( ) ) ) ; <nl> + } else { <nl> + is_invariant = false ; <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + if ( is_invariant ) { <nl> + std : : set < NodeDef * > producers ; <nl> + for ( const auto & input : consumer - > input ( ) ) { <nl> + auto * producer = node_map_ - > GetNode ( input ) ; <nl> + producers . insert ( producer ) ; <nl> + } <nl> + for ( auto * producer : producers ) { <nl> + auto iter = invariant_nodes_ . find ( producer ) ; <nl> + if ( iter ! = invariant_nodes_ . end ( ) ) { <nl> + - - iter - > second ; <nl> + } <nl> + } <nl> + TF_RETURN_IF_ERROR ( FindInvariantNodes ( consumer ) ) ; <nl> + } <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + Status LoopOptimizer : : LoopInvariantNodeMotion ( ) { <nl> + std : : deque < int > worklist ; <nl> + for ( auto iter = frame_map_ . begin ( ) ; iter ! = frame_map_ . end ( ) ; + + iter ) { <nl> + auto * node = iter - > first ; <nl> + auto & frame_ids = iter - > second ; <nl> + if ( frame_ids . size ( ) > = 3 ) { <nl> + for ( unsigned int i = 1 ; i < frame_ids . size ( ) - 1 ; + + i ) { <nl> + frame_parent_ [ frame_ids [ i ] ] = frame_ids [ i - 1 ] ; <nl> + frame_children_ [ frame_ids [ i ] ] . insert ( frame_ids [ i + 1 ] ) ; <nl> + } <nl> + } <nl> + if ( frame_ids . size ( ) > = 2 ) { <nl> + frame_children_ [ frame_ids [ 0 ] ] . insert ( frame_ids [ 1 ] ) ; <nl> + frame_parent_ [ frame_ids . back ( ) ] = frame_ids [ frame_ids . size ( ) - 2 ] ; <nl> + } <nl> + if ( ! frame_ids . empty ( ) ) { <nl> + frame_children_ . insert ( std : : make_pair ( frame_ids . back ( ) , empty_set_ ) ) ; <nl> + if ( node - > op ( ) = = " LoopCond " ) { <nl> + if ( loop_cond_ . count ( frame_ids . back ( ) ) ) { <nl> + return errors : : InvalidArgument ( <nl> + " Loop " , frame_ids . back ( ) , <nl> + " has more than one LoopCond node : " , node - > name ( ) , " and " , <nl> + loop_cond_ [ frame_ids . back ( ) ] - > name ( ) ) ; <nl> + } <nl> + loop_cond_ [ frame_ids . back ( ) ] = node ; <nl> + } <nl> + if ( IsEnter ( * node ) & & node - > attr ( ) . at ( " is_constant " ) . b ( ) ) { <nl> + invariant_enters_ [ frame_ids . back ( ) ] . push_back ( <nl> + const_cast < NodeDef * > ( node ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + for ( auto it = frame_children_ . begin ( ) ; it ! = frame_children_ . end ( ) ; + + it ) { <nl> + if ( it - > second . empty ( ) ) { <nl> + worklist . push_back ( it - > first ) ; <nl> + } <nl> + } <nl> + <nl> + while ( ! worklist . empty ( ) ) { <nl> + int frame_id = worklist . front ( ) ; <nl> + new_enter_id_ = 0 ; <nl> + worklist . pop_front ( ) ; <nl> + auto parent_it = frame_parent_ . find ( frame_id ) ; <nl> + if ( parent_it ! = frame_parent_ . end ( ) ) { <nl> + int parent_id = parent_it - > second ; <nl> + frame_children_ [ parent_id ] . erase ( frame_id ) ; <nl> + if ( frame_children_ [ parent_id ] . empty ( ) ) { <nl> + worklist . push_back ( parent_id ) ; <nl> + } <nl> + } <nl> + <nl> + if ( invariant_enters_ [ frame_id ] . empty ( ) ) { <nl> + continue ; <nl> + } <nl> + invariant_nodes_ . clear ( ) ; <nl> + for ( auto * enter : invariant_enters_ [ frame_id ] ) { <nl> + TF_RETURN_IF_ERROR ( FindInvariantNodes ( enter ) ) ; <nl> + } <nl> + <nl> + / / revert invariant nodes that have control outputs to variant nodes <nl> + TF_RETURN_IF_ERROR ( RevertInvariantNodes ( ) ) ; <nl> + <nl> + TF_RETURN_IF_ERROR ( MoveInvariantNodes ( frame_id ) ) ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> Status LoopOptimizer : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> GraphDef * optimized_graph ) { <nl> - Status status = RemoveStackOps ( item . graph , optimized_graph ) ; <nl> - return status ; <nl> + TF_RETURN_IF_ERROR ( RemoveStackOps ( item . graph , optimized_graph ) ) ; <nl> + <nl> + optimized_graph_ = optimized_graph ; <nl> + <nl> + / / Set up helper data structures . <nl> + node_map_ . reset ( new NodeMap ( optimized_graph_ ) ) ; <nl> + int num_frames ; <nl> + TF_RETURN_IF_ERROR ( IdentifyFramesWithNodeMap ( * optimized_graph_ , * node_map_ , <nl> + & frame_map_ , & num_frames ) ) ; <nl> + <nl> + TF_RETURN_IF_ERROR ( LoopInvariantNodeMotion ( ) ) ; <nl> + return Status : : OK ( ) ; <nl> } <nl> <nl> void LoopOptimizer : : Feedback ( Cluster * / * cluster * / , const GrapplerItem & / * item * / , <nl> mmm a / tensorflow / core / grappler / optimizers / loop_optimizer . h <nl> ppp b / tensorflow / core / grappler / optimizers / loop_optimizer . h <nl> limitations under the License . <nl> # define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_LOOP_OPTIMIZER_H_ <nl> <nl> # include < unordered_set > <nl> + # include " tensorflow / core / grappler / costs / graph_properties . h " <nl> # include " tensorflow / core / grappler / optimizers / graph_optimizer . h " <nl> # include " tensorflow / core / grappler / utils . h " <nl> + # include " tensorflow / core / grappler / utils / frame . h " <nl> # include " tensorflow / core / protobuf / rewriter_config . pb . h " <nl> <nl> namespace tensorflow { <nl> namespace grappler { <nl> <nl> + constexpr char kLoopOptimizer [ ] = " LoopOptimizer " ; <nl> + <nl> class LoopOptimizer : public GraphOptimizer { <nl> public : <nl> LoopOptimizer ( ) : opt_level_ ( RewriterConfig : : ON ) { } <nl> class LoopOptimizer : public GraphOptimizer { <nl> const GraphDef & optimized_graph , double result ) override ; <nl> <nl> private : <nl> + Status LoopInvariantNodeMotion ( ) ; <nl> + Status FindInvariantNodes ( NodeDef * node ) ; <nl> + Status RevertInvariantNodes ( ) ; <nl> + Status MoveInvariantNodes ( const int frame_id ) ; <nl> + Status LINMHandleInvariantNode ( NodeDef * node , const int num_outputs , <nl> + const int frame_id ) ; <nl> + Status LINMHandleConst ( NodeDef * node , const int num_outputs , <nl> + const int frame_id ) ; <nl> + Status LINMHandleInvariantEnter ( NodeDef * node , const int num_outputs ) ; <nl> + <nl> + std : : map < NodeDef * , int > invariant_nodes_ ; <nl> + std : : set < int > empty_set_ ; <nl> + std : : map < int , std : : set < int > > frame_children_ ; <nl> + std : : map < int , int > frame_parent_ ; <nl> + std : : map < int , const NodeDef * > loop_cond_ ; <nl> + std : : map < int , std : : vector < NodeDef * > > invariant_enters_ ; <nl> + int new_enter_id_ ; <nl> RewriterConfig : : Toggle opt_level_ ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map_ ; <nl> + FrameMap frame_map_ ; <nl> + std : : unique_ptr < GraphProperties > graph_properties_ ; <nl> + GraphDef * optimized_graph_ ; / / Not owned . <nl> } ; <nl> <nl> } / / end namespace grappler <nl> mmm a / tensorflow / core / grappler / optimizers / loop_optimizer_test . cc <nl> ppp b / tensorflow / core / grappler / optimizers / loop_optimizer_test . cc <nl> namespace tensorflow { <nl> namespace grappler { <nl> namespace { <nl> <nl> - class LoopOptimizerTest : public : : testing : : Test { } ; <nl> + class LoopOptimizerTest : public : : testing : : Test { <nl> + protected : <nl> + static NodeDef CreateNode ( const string & name , <nl> + const std : : vector < string > & inputs ) { <nl> + return CreateNode ( name , " Identity " , " " , false , 0 , inputs ) ; <nl> + } <nl> + static NodeDef CreateNode ( const string & name , const string & op , <nl> + const std : : vector < string > & inputs ) { <nl> + return CreateNode ( name , op , " " , false , 0 , inputs ) ; <nl> + } <nl> + static NodeDef CreateNode ( const string & name , const string & op , <nl> + const string & frame , <nl> + const bool is_constant , <nl> + const int piterations , <nl> + const std : : vector < string > & inputs ) { <nl> + NodeDef node ; <nl> + node . set_name ( name ) ; <nl> + if ( ! op . empty ( ) ) { <nl> + node . set_op ( op ) ; <nl> + } <nl> + if ( ! frame . empty ( ) ) { <nl> + AttrValue frame_name ; <nl> + frame_name . set_s ( frame ) ; <nl> + node . mutable_attr ( ) - > insert ( { " frame_name " , frame_name } ) ; <nl> + } <nl> + if ( op = = " Enter " ) { <nl> + AttrValue is_const ; <nl> + is_const . set_b ( is_constant ) ; <nl> + node . mutable_attr ( ) - > insert ( { " is_constant " , is_const } ) ; <nl> + AttrValue parallel_iterations ; <nl> + parallel_iterations . set_i ( piterations ) ; <nl> + node . mutable_attr ( ) - > insert ( <nl> + { " parallel_iterations " , parallel_iterations } ) ; <nl> + } <nl> + AttrValue type ; <nl> + type . set_type ( DT_FLOAT ) ; <nl> + node . mutable_attr ( ) - > insert ( { " T " , type } ) ; <nl> + for ( const string & input : inputs ) { <nl> + node . add_input ( input ) ; <nl> + } <nl> + return node ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_F ( LoopOptimizerTest , Basic ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " VariantAdd " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " VariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . back ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd " ) ) . back ( ) , 0 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd " ) ) . back ( ) , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , Const ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Const " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " Const " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " VariantAdd " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " VariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . back ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const " ) ) . back ( ) , 0 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const " ) ) . size ( ) , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , ControlOutput ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Less " , " Less " , { " VariantAdd " , " less / y " , " ^ InvariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " VariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . back ( ) , 0 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . back ( ) , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , NestedLoop1 ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " Exit2 " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " Exit2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter2 " , " Enter " , " while / while / while_context " , true , 1 , <nl> + { " VariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd2 " , " Add " , { " InvariantEnter2 " , " InvariantEnter2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd2 " , " Add " , { " InvariantAdd2 " , " Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter2 " , " Enter " , " while / while / while_context " , false , 1 , <nl> + { " VariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge2 " , " Merge " , { " VariantEnter2 " , " NextIteration2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 / y " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 " , " Less " , { " VariantAdd2 " , " less2 / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond2 " , " LoopCond " , { " Less2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch2 " , " Switch " , { " Merge2 " , " LoopCond2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity2 " , { " Switch2 : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration2 " , " NextIteration " , { " VariantAdd2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit2 " , " Exit " , { " Switch2 " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . back ( ) , 0 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd " ) ) . size ( ) , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , NestedLoop2 ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " Exit2 " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " Exit2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter2 " , " Enter " , " while / while / while_context " , true , 1 , <nl> + { " InvariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd2 " , " Add " , { " InvariantEnter2 " , " InvariantEnter2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd2 " , " Add " , { " InvariantAdd2 " , " Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter2 " , " Enter " , " while / while / while_context " , false , 1 , <nl> + { " VariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge2 " , " Merge " , { " VariantEnter2 " , " NextIteration2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 / y " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 " , " Less " , { " VariantAdd2 " , " less2 / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond2 " , " LoopCond " , { " Less2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch2 " , " Switch " , { " Merge2 " , " LoopCond2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity2 " , { " Switch2 : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration2 " , " NextIteration " , { " VariantAdd2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit2 " , " Exit " , { " Switch2 " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " VariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , NestedLoopConst1 ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " Exit2 " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " Exit2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter2 " , " Enter " , " while / while / while_context " , true , 1 , <nl> + { " VariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Const2 " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd2 " , " Add " , { " InvariantEnter2 " , " Const2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd2 " , " Add " , { " InvariantAdd2 " , " Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter2 " , " Enter " , " while / while / while_context " , false , 1 , <nl> + { " VariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge2 " , " Merge " , { " VariantEnter2 " , " NextIteration2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 / y " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 " , " Less " , { " VariantAdd2 " , " less2 / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond2 " , " LoopCond " , { " Less2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch2 " , " Switch " , { " Merge2 " , " LoopCond2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity2 " , { " Switch2 : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration2 " , " NextIteration " , { " VariantAdd2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit2 " , " Exit " , { " Switch2 " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . back ( ) , 1 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . size ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . back ( ) , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( LoopOptimizerTest , NestedLoopConst2 ) { <nl> + GraphDef graph ; <nl> + * graph . add_node ( ) = CreateNode ( " 0 " , { } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter " , " Enter " , " while / while_context " , true , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd " , " Add " , { " InvariantEnter " , " InvariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd " , " Add " , { " InvariantAdd " , " Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter " , " Enter " , " while / while_context " , false , 1 , { " 0 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge " , " Merge " , { " VariantEnter " , " NextIteration " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less / y " , " Const " , { " ^ Identity " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less " , " Less " , { " Exit2 " , " less / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond " , " LoopCond " , { " Less " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch " , " Switch " , { " Merge " , " LoopCond " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity " , { " Switch : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration " , " NextIteration " , { " Exit2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit " , " Exit " , { " Switch " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " 1 " , { " Exit " } ) ; <nl> + <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantEnter2 " , " Enter " , " while / while / while_context " , true , 1 , <nl> + { " InvariantAdd " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Const2 " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " InvariantAdd2 " , " Add " , { " InvariantEnter2 " , " Const2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantAdd2 " , " Add " , { " InvariantAdd2 " , " Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " VariantEnter2 " , " Enter " , " while / while / while_context " , false , 1 , <nl> + { " VariantEnter " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " Merge2 " , " Merge " , { " VariantEnter2 " , " NextIteration2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 / y " , " Const " , { " ^ Identity2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Less2 " , " Less " , { " VariantAdd2 " , " less2 / y " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " LoopCond2 " , " LoopCond " , { " Less2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Switch2 " , " Switch " , { " Merge2 " , " LoopCond2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Identity2 " , { " Switch2 : 1 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( <nl> + " NextIteration2 " , " NextIteration " , { " VariantAdd2 " } ) ; <nl> + * graph . add_node ( ) = CreateNode ( " Exit2 " , " Exit " , { " Switch2 " } ) ; <nl> + <nl> + GrapplerItem item ; <nl> + item . graph = graph ; <nl> + <nl> + LoopOptimizer optimizer ; <nl> + GraphDef output ; <nl> + Status status = optimizer . Optimize ( nullptr , item , & output ) ; <nl> + TF_EXPECT_OK ( status ) ; <nl> + <nl> + std : : unique_ptr < NodeMap > node_map ; <nl> + std : : unordered_map < const NodeDef * , std : : vector < int > > frames ; <nl> + int num_frames ; <nl> + <nl> + node_map . reset ( new NodeMap ( & graph ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( graph , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . back ( ) , 1 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . size ( ) , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . back ( ) , 1 ) ; <nl> + <nl> + node_map . reset ( new NodeMap ( & output ) ) ; <nl> + EXPECT_TRUE ( IdentifyFrames ( output , & frames , & num_frames ) . ok ( ) ) ; <nl> + EXPECT_EQ ( num_frames , 2 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " InvariantAdd2 " ) ) . size ( ) , 0 ) ; <nl> + EXPECT_EQ ( frames . at ( node_map - > GetNode ( " Const2 " ) ) . size ( ) , 0 ) ; <nl> + } <nl> <nl> void VerifyGraphsEqual ( const GraphDef & original_graph , <nl> const GraphDef & optimized_graph , const string & func ) { <nl> mmm a / tensorflow / core / kernels / BUILD <nl> ppp b / tensorflow / core / kernels / BUILD <nl> tf_kernel_library ( <nl> srcs = [ <nl> " dequantize_op . cc " , <nl> " meta_support . cc " , <nl> - " quantization_utils . cc " , <nl> " quantize_down_and_shrink_range . cc " , <nl> " quantize_op . cc " , <nl> " quantized_activation_ops . cc " , <nl> tf_kernel_library ( <nl> " : image_resizer_state " , <nl> " : ops_util " , <nl> " : pooling_ops " , <nl> + " : quantization_utils " , <nl> " / / tensorflow / core : array_ops_op_lib " , <nl> " / / tensorflow / core : core_cpu " , <nl> " / / tensorflow / core : framework " , <nl> tf_kernel_library ( <nl> ] , <nl> ) <nl> <nl> + cc_library ( <nl> + name = " quantization_utils " , <nl> + srcs = [ " quantization_utils . cc " ] , <nl> + hdrs = [ " quantization_utils . h " ] , <nl> + deps = [ <nl> + " / / tensorflow / core : framework " , <nl> + " @ gemmlowp " , <nl> + ] , <nl> + ) <nl> + <nl> cc_library ( <nl> name = " remote_fused_graph_execute_utils " , <nl> srcs = [ <nl> cc_library ( <nl> srcs = [ <nl> " cwise_ops_common . cc " , <nl> " meta_support . cc " , <nl> - " quantization_utils . cc " , <nl> ] , <nl> hdrs = [ <nl> " cwise_ops . h " , <nl> cc_library ( <nl> " cwise_ops_gpu_gradients . cu . h " , <nl> " cwise_ops_gradients . h " , <nl> " meta_support . h " , <nl> - " quantization_utils . h " , <nl> ] , <nl> deps = [ <nl> " : bounds_check " , <nl> + " : quantization_utils " , <nl> " / / tensorflow / core : framework " , <nl> " / / tensorflow / core : lib " , <nl> " / / third_party / eigen3 " , <nl> mmm a / tensorflow / core / kernels / cwise_op_maximum . cc <nl> ppp b / tensorflow / core / kernels / cwise_op_maximum . cc <nl> limitations under the License . <nl> # include " tensorflow / core / kernels / cwise_ops_common . h " <nl> <nl> namespace tensorflow { <nl> - REGISTER5 ( BinaryOp , CPU , " Maximum " , functor : : maximum , float , Eigen : : half , <nl> - double , int32 , int64 ) ; <nl> + REGISTER6 ( BinaryOp , CPU , " Maximum " , functor : : maximum , float , Eigen : : half , <nl> + bfloat16 , double , int32 , int64 ) ; <nl> # if GOOGLE_CUDA <nl> REGISTER4 ( BinaryOp , GPU , " Maximum " , functor : : maximum , float , Eigen : : half , <nl> double , int64 ) ; <nl> mmm a / tensorflow / core / kernels / mkl_fused_batch_norm_op . cc <nl> ppp b / tensorflow / core / kernels / mkl_fused_batch_norm_op . cc <nl> class MklFusedBatchNormGradOp : public OpKernel { <nl> return ; <nl> } <nl> <nl> - if ( dnn_shape_src . IsMklTensor ( ) ) <nl> - depth_ = dnn_shape_src . DimSize ( MklDnnDims : : Dim_C ) ; <nl> - else <nl> - ExtractParams ( context ) ; <nl> - <nl> - memory : : format format_m ; <nl> if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> - if ( dnn_shape_src . IsTensorInNCHWFormat ( ) ) <nl> - format_m = memory : : format : : nchw ; <nl> - else <nl> - format_m = memory : : format : : nhwc ; <nl> + depth_ = dnn_shape_src . DimSize ( MklDnnDims : : Dim_C ) ; <nl> + } else if ( dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> + depth_ = dnn_shape_diff_dst . DimSize ( MklDnnDims : : Dim_C ) ; <nl> } else { <nl> - format_m = TFDataFormatToMklDnnDataFormat ( tensor_format_ ) ; <nl> + ExtractParams ( context ) ; <nl> } <nl> <nl> MklDnnData < T > src ( & cpu_engine ) ; <nl> class MklFusedBatchNormGradOp : public OpKernel { <nl> diff_dst_dims = <nl> TFShapeToMklDnnDimsInNCHW ( diff_dst_tensor . shape ( ) , tensor_format_ ) ; <nl> <nl> - / / set src and diff_dst primitives <nl> + / / set src and diff_dst primitives according to input layout <nl> memory : : desc src_md ( { } , memory : : data_undef , memory : : format_undef ) ; <nl> memory : : desc diff_dst_md ( { } , memory : : data_undef , memory : : format_undef ) ; <nl> - if ( dnn_shape_src . IsMklTensor ( ) | | dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> - if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> - src_md = dnn_shape_src . GetMklLayout ( ) ; <nl> - diff_dst_md = src_md ; <nl> - } else { <nl> - diff_dst_md = dnn_shape_diff_dst . GetMklLayout ( ) ; <nl> - src_md = diff_dst_md ; <nl> - } <nl> + if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + src_md = dnn_shape_src . GetMklLayout ( ) ; <nl> } else { <nl> - src_md = memory : : desc ( src_dims , MklDnnType < T > ( ) , format_m ) ; <nl> - diff_dst_md = src_md ; <nl> + src_md = memory : : desc ( src_dims , MklDnnType < T > ( ) , <nl> + TFDataFormatToMklDnnDataFormat ( tensor_format_ ) ) ; <nl> + } <nl> + if ( dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> + diff_dst_md = dnn_shape_diff_dst . GetMklLayout ( ) ; <nl> + } else { <nl> + diff_dst_md = memory : : desc ( diff_dst_dims , MklDnnType < T > ( ) , <nl> + TFDataFormatToMklDnnDataFormat ( tensor_format_ ) ) ; <nl> } <nl> src . SetUsrMem ( src_md , & src_tensor ) ; <nl> diff_dst . SetUsrMem ( diff_dst_md , & diff_dst_tensor ) ; <nl> class MklFusedBatchNormGradOp : public OpKernel { <nl> / / allocate diff_src tensor <nl> MklDnnShape dnn_shape_diff_src ; <nl> TensorShape tf_shape_diff_src ; <nl> - if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + <nl> + / / MKL - DNN ' s BN primitive not provide API to fetch internal format <nl> + / / set common_md as OpMem <nl> + / / src and diff_dst will reorder to common_md <nl> + / / diff_src will set as common_md <nl> + memory : : desc common_md ( { } , memory : : data_undef , memory : : format_undef ) ; <nl> + if ( dnn_shape_src . IsMklTensor ( ) | | dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> + if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + common_md = dnn_shape_src . GetMklLayout ( ) ; <nl> + } else { <nl> + common_md = dnn_shape_diff_dst . GetMklLayout ( ) ; <nl> + } <nl> + } else { <nl> + common_md = memory : : desc ( src_dims , MklDnnType < T > ( ) , <nl> + TFDataFormatToMklDnnDataFormat ( tensor_format_ ) ) ; <nl> + } <nl> + / / if any of src and diff_dst as mkl layout , <nl> + / / then we set diff_src as mkl layout <nl> + if ( dnn_shape_src . IsMklTensor ( ) | | <nl> + dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> dnn_shape_diff_src . SetMklTensor ( true ) ; <nl> - auto diff_src_pd = bnrm_fwd_pd . dst_primitive_desc ( ) ; <nl> + / / set diff_src ' s mkl layout as common_md <nl> + auto diff_src_pd = memory : : primitive_desc ( common_md , cpu_engine ) ; <nl> dnn_shape_diff_src . SetMklLayout ( & diff_src_pd ) ; <nl> dnn_shape_diff_src . SetElemType ( MklDnnType < T > ( ) ) ; <nl> - dnn_shape_diff_src . SetTfLayout ( dnn_shape_src . GetDimension ( ) , src_dims , <nl> - format_m ) ; <nl> - dnn_shape_diff_src . SetTfDimOrder ( dnn_shape_src . GetDimension ( ) , <nl> - tensor_format_ ) ; <nl> + if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + dnn_shape_diff_src . SetTfLayout ( <nl> + dnn_shape_src . GetDimension ( ) , <nl> + src_dims , <nl> + dnn_shape_src . GetTfDataFormat ( ) ) ; <nl> + dnn_shape_diff_src . SetTfDimOrder ( <nl> + dnn_shape_src . GetDimension ( ) , <nl> + tensor_format_ ) ; <nl> + } else { <nl> + dnn_shape_diff_src . SetTfLayout ( <nl> + dnn_shape_diff_dst . GetDimension ( ) , <nl> + src_dims , <nl> + dnn_shape_diff_dst . GetTfDataFormat ( ) ) ; <nl> + dnn_shape_diff_src . SetTfDimOrder ( <nl> + dnn_shape_diff_dst . GetDimension ( ) , <nl> + tensor_format_ ) ; <nl> + } <nl> tf_shape_diff_src . AddDim ( diff_src_pd . get_size ( ) / sizeof ( T ) ) ; <nl> } else { <nl> dnn_shape_diff_src . SetMklTensor ( false ) ; <nl> + / / both src and diff_dst are TensorFlow layout , <nl> + / / so it is OK to get TensorFlow shape . <nl> tf_shape_diff_src = src_tensor . shape ( ) ; <nl> } <nl> AllocateOutputSetMklShape ( context , kDiffSrcIndex , & diff_src_tensor , <nl> tf_shape_diff_src , dnn_shape_diff_src ) ; <nl> <nl> - diff_src . SetUsrMem ( src_md , diff_src_tensor ) ; <nl> + / / set diff_src <nl> + diff_src . SetUsrMem ( common_md , diff_src_tensor ) ; <nl> <nl> prop_kind pk = prop_kind : : backward ; <nl> auto bnrm_bwd_desc = batch_normalization_backward : : desc ( <nl> - pk , diff_src . GetUsrMemDesc ( ) , src . GetUsrMemDesc ( ) , epsilon_ , <nl> + pk , common_md , common_md , epsilon_ , <nl> / * for inference , specify use_global_stats <nl> 1 . on fwd prop , use mean and variance <nl> provided as inputs <nl> class MklFusedBatchNormGradOp : public OpKernel { <nl> auto bnrm_bwd_pd = batch_normalization_backward : : primitive_desc ( <nl> bnrm_bwd_desc , cpu_engine , bnrm_fwd_pd ) ; <nl> <nl> + std : : vector < primitive > net ; <nl> + src . CheckReorderToOpMem ( memory : : primitive_desc ( common_md , <nl> + cpu_engine ) , & net ) ; <nl> + diff_dst . CheckReorderToOpMem ( memory : : primitive_desc ( common_md , <nl> + cpu_engine ) , & net ) ; <nl> + <nl> auto bnrm_bwd_op = batch_normalization_backward ( <nl> bnrm_bwd_pd , src . GetOpMem ( ) , mean . GetOpMem ( ) , variance . GetOpMem ( ) , <nl> diff_dst . GetOpMem ( ) , weights_m , diff_src . GetOpMem ( ) , diff_weights_m ) ; <nl> <nl> - std : : vector < primitive > net ; <nl> net . push_back ( bnrm_bwd_op ) ; <nl> stream ( stream : : kind : : eager ) . submit ( net ) . wait ( ) ; <nl> <nl> mmm a / tensorflow / core / kernels / mkl_relu_op . cc <nl> ppp b / tensorflow / core / kernels / mkl_relu_op . cc <nl> void MklReluGradOp < Device , T > : : Compute ( OpKernelContext * context ) { <nl> mkl_context . MklCleanup ( ) ; <nl> } <nl> <nl> + <nl> + <nl> # else / / INTEL_MKL_ML <nl> <nl> + <nl> template < typename Device , typename T , algorithm alg_kind > <nl> class MklReluOpBase : public OpKernel { <nl> public : <nl> class MklReluGradOpBase : public OpKernel { <nl> / / allocate diff_src tensor <nl> MklDnnShape dnn_shape_diff_src ; <nl> TensorShape tf_shape_diff_src ; <nl> - if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + if ( dnn_shape_src . IsMklTensor ( ) | | <nl> + dnn_shape_diff_dst . IsMklTensor ( ) ) { <nl> dnn_shape_diff_src . SetMklTensor ( true ) ; <nl> auto diff_src_pd = relu_bwd_pd . diff_src_primitive_desc ( ) ; <nl> dnn_shape_diff_src . SetMklLayout ( & diff_src_pd ) ; <nl> dnn_shape_diff_src . SetElemType ( MklDnnType < T > ( ) ) ; <nl> - dnn_shape_diff_src . SetTfLayout ( dnn_shape_src . GetDimension ( ) , <nl> - dnn_shape_src . GetSizesAsMklDnnDims ( ) , <nl> - dnn_shape_src . GetTfDataFormat ( ) ) ; <nl> + if ( dnn_shape_src . IsMklTensor ( ) ) { <nl> + dnn_shape_diff_src . SetTfLayout ( dnn_shape_src . GetDimension ( ) , <nl> + dnn_shape_src . GetSizesAsMklDnnDims ( ) , <nl> + dnn_shape_src . GetTfDataFormat ( ) ) ; <nl> + } else { <nl> + dnn_shape_diff_src . SetTfLayout ( dnn_shape_diff_dst . GetDimension ( ) , <nl> + dnn_shape_diff_dst . GetSizesAsMklDnnDims ( ) , <nl> + dnn_shape_diff_dst . GetTfDataFormat ( ) ) ; <nl> + } <nl> tf_shape_diff_src . AddDim ( diff_src_pd . get_size ( ) / sizeof ( T ) ) ; <nl> } else { <nl> dnn_shape_diff_src . SetMklTensor ( false ) ; <nl> + / / both src and diff_dst are TensorFlow layout , <nl> + / / so it is ok to get TensorFlow shape . <nl> tf_shape_diff_src = src_tensor . shape ( ) ; <nl> } <nl> AllocateOutputSetMklShape ( context , diff_src_index , & diff_src_tensor , <nl> mmm a / tensorflow / core / kernels / reshape_op . cc <nl> ppp b / tensorflow / core / kernels / reshape_op . cc <nl> REGISTER_KERNEL_BUILDER ( Name ( " Reshape " ) <nl> . TypeConstraint < int64 > ( " Tshape " ) , \ <nl> ReshapeOp ) ; <nl> TF_CALL_NUMBER_TYPES_NO_INT32 ( REGISTER_GPU_KERNEL ) ; <nl> - TF_CALL_bfloat16 ( REGISTER_GPU_KERNEL ) ; <nl> TF_CALL_bool ( REGISTER_GPU_KERNEL ) ; <nl> # undef REGISTER_GPU_KERNEL <nl> <nl> mmm a / tensorflow / core / kernels / segment_reduction_ops . cc <nl> ppp b / tensorflow / core / kernels / segment_reduction_ops . cc <nl> limitations under the License . <nl> # define EIGEN_USE_GPU <nl> # endif / / GOOGLE_CUDA <nl> <nl> - # include " tensorflow / core / kernels / segment_reduction_ops . h " <nl> - # include < vector > <nl> # include " third_party / eigen3 / Eigen / Core " <nl> # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> + # include " tensorflow / core / kernels / segment_reduction_ops . h " <nl> + # include < vector > <nl> # include " tensorflow / core / framework / numeric_op . h " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> TF_CALL_GPU_NUMBER_TYPES ( REGISTER_GPU_SORTED_KERNELS_ALL ) ; <nl> # undef REGISTER_GPU_SORTED_KERNELS_ALL <nl> # endif / / GOOGLE_CUDA <nl> <nl> + / / ____________________________________________________________________________ <nl> + / / Unsorted segment reduction ops . <nl> + <nl> namespace functor { <nl> <nl> - / / UnsortedSegmentSumFunctor implementation for CPUDevice . <nl> - / / todo : Remove duplicate code in UnsortedSegmentSumFunctor and <nl> - / / UnsortedSegmentMaxFunctor . <nl> - template < typename T , typename Index > <nl> - struct UnsortedSegmentSumFunctor < CPUDevice , T , Index > <nl> - : UnsortedSegmentBaseFunctor < CPUDevice , T , Index > { <nl> - void operator ( ) ( OpKernelContext * ctx , const CPUDevice & d , <nl> - const Index output_rows , const TensorShape & segment_ids_shape , <nl> + / / The ReductionFunctor implementation for CPU . <nl> + template < typename T , typename Index , typename InitialValueF , <nl> + typename ReductionF > <nl> + struct UnsortedSegmentFunctor < CPUDevice , T , Index , InitialValueF , ReductionF > { <nl> + void operator ( ) ( OpKernelContext * ctx , const Index num_segments , <nl> + const TensorShape & segment_ids_shape , <nl> typename TTypes < Index > : : ConstFlat segment_ids , <nl> const Index data_size , const T * data , <nl> - typename TTypes < T , 2 > : : Tensor output ) override { <nl> - output . setZero ( ) ; <nl> + typename TTypes < T , 2 > : : Tensor output ) { <nl> + output . setConstant ( InitialValueF ( ) ( ) ) ; <nl> if ( data_size = = 0 ) { <nl> return ; <nl> } <nl> const int64 N = segment_ids . dimension ( 0 ) ; <nl> + ReductionF reduction ; <nl> auto data_flat = typename TTypes < T , 2 > : : ConstTensor ( data , N , data_size / N ) ; <nl> for ( int64 i = 0 ; i < N ; + + i ) { <nl> Index j = internal : : SubtleMustCopy ( segment_ids ( i ) ) ; <nl> if ( j < 0 ) { <nl> continue ; <nl> } <nl> - OP_REQUIRES ( ctx , FastBoundsCheck ( j , output_rows ) , <nl> + OP_REQUIRES ( ctx , FastBoundsCheck ( j , num_segments ) , <nl> errors : : InvalidArgument ( <nl> " segment_ids " , SliceDebugString ( segment_ids_shape , i ) , <nl> - " = " , j , " is out of range [ 0 , " , output_rows , " ) " ) ) ; <nl> - output . template chip < 0 > ( j ) + = data_flat . template chip < 0 > ( i ) ; <nl> + " = " , j , " is out of range [ 0 , " , num_segments , " ) " ) ) ; <nl> + reduction ( data_flat . template chip < 0 > ( i ) , output . template chip < 0 > ( j ) ) ; <nl> } <nl> } <nl> } ; <nl> - / / UnsortedSegmentMaxFunctor implementation for CPUDevice . <nl> - template < typename T , typename Index > <nl> - struct UnsortedSegmentMaxFunctor < CPUDevice , T , Index > <nl> - : UnsortedSegmentBaseFunctor < CPUDevice , T , Index > { <nl> - void operator ( ) ( OpKernelContext * ctx , const CPUDevice & d , <nl> - const Index output_rows , const TensorShape & segment_ids_shape , <nl> - typename TTypes < Index > : : ConstFlat segment_ids , <nl> - const Index data_size , const T * data , <nl> - typename TTypes < T , 2 > : : Tensor output ) override { <nl> - output . setConstant ( std : : numeric_limits < T > : : lowest ( ) ) ; <nl> - if ( data_size = = 0 ) { <nl> - return ; <nl> - } <nl> - const int64 N = segment_ids . dimension ( 0 ) ; <nl> - auto data_flat = typename TTypes < T , 2 > : : ConstTensor ( data , N , data_size / N ) ; <nl> - for ( int64 i = 0 ; i < N ; + + i ) { <nl> - Index j = internal : : SubtleMustCopy ( segment_ids ( i ) ) ; <nl> - OP_REQUIRES ( ctx , FastBoundsCheck ( j , output_rows ) , <nl> - errors : : InvalidArgument ( <nl> - " segment_ids " , SliceDebugString ( segment_ids_shape , i ) , <nl> - " = " , j , " is out of range [ 0 , " , output_rows , " ) " ) ) ; <nl> - output . template chip < 0 > ( j ) = <nl> - data_flat . template chip < 0 > ( i ) . cwiseMax ( output . template chip < 0 > ( j ) ) ; <nl> - } <nl> + <nl> + template < typename T > <nl> + using MatrixChip = Eigen : : TensorChippingOp < 0l , typename TTypes < T , 2 > : : Matrix > ; <nl> + <nl> + template < typename T > <nl> + using constMatrixChip = <nl> + Eigen : : TensorChippingOp < 0l , const typename TTypes < T , 2 > : : ConstMatrix > ; <nl> + <nl> + / / reduction functors <nl> + template < typename T > <nl> + struct SumOp { <nl> + void operator ( ) ( const constMatrixChip < T > data , MatrixChip < T > output ) { <nl> + output + = data ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct MaxOp { <nl> + void operator ( ) ( const constMatrixChip < T > data , MatrixChip < T > output ) { <nl> + output = data . cwiseMax ( output ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct MinOp { <nl> + void operator ( ) ( const constMatrixChip < T > data , MatrixChip < T > output ) { <nl> + output = data . cwiseMin ( output ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct ProdOp { <nl> + void operator ( ) ( const constMatrixChip < T > data , MatrixChip < T > output ) { <nl> + output * = data ; <nl> } <nl> } ; <nl> } / / namespace functor <nl> <nl> - / / Base class for SegmentReductionOps that can handle unsorted segment <nl> - / / definitions <nl> - / / and specifying the size of the output in addition to a reduction function <nl> - template < typename Device , class T , class Index > <nl> - class UnsortedSegmentBaseOp : public OpKernel { <nl> + / / Static check routines not in the templated class to reduce code size <nl> + static void UnsortedSegmentReductionValidation ( OpKernel * op_kernel , <nl> + OpKernelContext * context , <nl> + const Tensor & data , <nl> + const Tensor & segment_ids , <nl> + const Tensor & num_segments ) { <nl> + OP_REQUIRES ( <nl> + context , op_kernel - > IsLegacyScalar ( num_segments . shape ( ) ) , <nl> + errors : : InvalidArgument ( " num_segments should be a scalar , not shape " , <nl> + num_segments . shape ( ) . DebugString ( ) ) ) ; <nl> + OP_REQUIRES ( <nl> + context , TensorShapeUtils : : StartsWith ( data . shape ( ) , segment_ids . shape ( ) ) , <nl> + errors : : InvalidArgument ( " data . shape = " , data . shape ( ) . DebugString ( ) , <nl> + " does not start with segment_ids . shape = " , <nl> + segment_ids . shape ( ) . DebugString ( ) ) ) ; <nl> + } <nl> + <nl> + static bool UnsortedSegmentReductionDoValidation ( OpKernel * op_kernel , <nl> + OpKernelContext * context , <nl> + const Tensor & data , <nl> + const Tensor & segment_ids , <nl> + const Tensor & num_segments ) { <nl> + UnsortedSegmentReductionValidation ( op_kernel , context , data , segment_ids , <nl> + num_segments ) ; <nl> + return context - > status ( ) . ok ( ) ; <nl> + } <nl> + <nl> + / / The UnsortedSegmentReduction OpKernel . The DeviceReductionFunctor <nl> + / / is the device specific implementation of the reduction . These device <nl> + / / specific implementations are templated themselves with the corresponding <nl> + / / initial value functors and reduction functors . <nl> + template < typename T , typename Index , typename DeviceReductionFunctor > <nl> + class UnsortedSegmentReductionOp : public OpKernel { <nl> public : <nl> - explicit UnsortedSegmentBaseOp ( <nl> - OpKernelConstruction * context , <nl> - functor : : UnsortedSegmentBaseFunctor < Device , T , Index > & functor ) <nl> - : OpKernel ( context ) , reduction_functor_ ( functor ) { } <nl> + explicit UnsortedSegmentReductionOp ( OpKernelConstruction * context ) <nl> + : OpKernel ( context ) , reduction_functor_ ( DeviceReductionFunctor ( ) ) { } <nl> <nl> void Compute ( OpKernelContext * context ) override { <nl> const Tensor & data = context - > input ( 0 ) ; <nl> const Tensor & segment_ids = context - > input ( 1 ) ; <nl> const Tensor & num_segments = context - > input ( 2 ) ; <nl> - <nl> - OP_REQUIRES ( <nl> - context , IsLegacyScalar ( num_segments . shape ( ) ) , <nl> - errors : : InvalidArgument ( " num_segments should be a scalar , not shape " , <nl> - num_segments . shape ( ) . DebugString ( ) ) ) ; <nl> - OP_REQUIRES ( <nl> - context , <nl> - TensorShapeUtils : : StartsWith ( data . shape ( ) , segment_ids . shape ( ) ) , <nl> - errors : : InvalidArgument ( " data . shape = " , data . shape ( ) . DebugString ( ) , <nl> - " does not start with segment_ids . shape = " , <nl> - segment_ids . shape ( ) . DebugString ( ) ) ) ; <nl> - <nl> + if ( ! UnsortedSegmentReductionDoValidation ( this , context , data , segment_ids , <nl> + num_segments ) ) { <nl> + return ; <nl> + } <nl> const auto segment_flat = segment_ids . flat < Index > ( ) ; <nl> const Index output_rows = <nl> internal : : SubtleMustCopy ( num_segments . scalar < int32 > ( ) ( ) ) ; <nl> OP_REQUIRES ( context , output_rows > = 0 , <nl> errors : : InvalidArgument ( " Input num_segments = = " , output_rows , <nl> " must not be negative . " ) ) ; <nl> - <nl> TensorShape output_shape ; <nl> output_shape . AddDim ( output_rows ) ; <nl> for ( int i = segment_ids . dims ( ) ; i < data . dims ( ) ; i + + ) { <nl> output_shape . AddDim ( data . dim_size ( i ) ) ; <nl> } <nl> - <nl> Tensor * output = nullptr ; <nl> OP_REQUIRES_OK ( context , context - > allocate_output ( 0 , output_shape , & output ) ) ; <nl> auto output_flat = output - > flat_outer_dims < T > ( ) ; <nl> - <nl> auto data_ptr = data . template flat < T > ( ) . data ( ) ; <nl> - reduction_functor_ ( context , context - > template eigen_device < Device > ( ) , <nl> - output_rows , segment_ids . shape ( ) , segment_flat , <nl> + reduction_functor_ ( context , output_rows , segment_ids . shape ( ) , segment_flat , <nl> data . NumElements ( ) , data_ptr , output_flat ) ; <nl> } <nl> <nl> - private : <nl> - functor : : UnsortedSegmentBaseFunctor < Device , T , Index > & reduction_functor_ ; <nl> - } ; <nl> - <nl> - template < typename Device , class T , class Index > <nl> - class UnsortedSegmentSumOp : public UnsortedSegmentBaseOp < Device , T , Index > { <nl> - public : <nl> - explicit UnsortedSegmentSumOp ( OpKernelConstruction * context ) <nl> - : UnsortedSegmentBaseOp < Device , T , Index > ( context , sum_functor_ ) { } <nl> - <nl> - private : <nl> - functor : : UnsortedSegmentSumFunctor < Device , T , Index > sum_functor_ ; <nl> + protected : <nl> + DeviceReductionFunctor reduction_functor_ ; <nl> } ; <nl> <nl> - template < typename Device , class T , class Index > <nl> - class UnsortedSegmentMaxOp : public UnsortedSegmentBaseOp < Device , T , Index > { <nl> - public : <nl> - explicit UnsortedSegmentMaxOp ( OpKernelConstruction * context ) <nl> - : UnsortedSegmentBaseOp < Device , T , Index > ( context , max_functor_ ) { } <nl> - <nl> - private : <nl> - functor : : UnsortedSegmentMaxFunctor < Device , T , Index > max_functor_ ; <nl> - } ; <nl> - <nl> - # define REGISTER_REAL_CPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> - REGISTER_KERNEL_BUILDER ( Name ( " UnsortedSegmentSum " ) \ <nl> - . Device ( DEVICE_CPU ) \ <nl> - . TypeConstraint < type > ( " T " ) \ <nl> - . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> - UnsortedSegmentSumOp < CPUDevice , type , index_type > ) ; \ <nl> - REGISTER_KERNEL_BUILDER ( Name ( " UnsortedSegmentMax " ) \ <nl> - . Device ( DEVICE_CPU ) \ <nl> - . TypeConstraint < type > ( " T " ) \ <nl> - . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> - UnsortedSegmentMaxOp < CPUDevice , type , index_type > ) ; <nl> - <nl> - # define REGISTER_COMPLEX_CPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> - REGISTER_KERNEL_BUILDER ( Name ( " UnsortedSegmentSum " ) \ <nl> - . Device ( DEVICE_CPU ) \ <nl> - . TypeConstraint < type > ( " T " ) \ <nl> - . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> - UnsortedSegmentSumOp < CPUDevice , type , index_type > ) ; <nl> + # define REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( \ <nl> + name , type , index_type , initial_value_functor , reduction_functor ) \ <nl> + REGISTER_KERNEL_BUILDER ( \ <nl> + Name ( name ) \ <nl> + . Device ( DEVICE_CPU ) \ <nl> + . TypeConstraint < type > ( " T " ) \ <nl> + . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> + UnsortedSegmentReductionOp < \ <nl> + type , index_type , \ <nl> + functor : : UnsortedSegmentFunctor < CPUDevice , type , index_type , \ <nl> + initial_value_functor , \ <nl> + reduction_functor > > ) <nl> + <nl> + # define REGISTER_REAL_CPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentSum " , type , index_type , \ <nl> + functor : : Zero < type > , \ <nl> + functor : : SumOp < type > ) ; \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentMax " , type , index_type , \ <nl> + functor : : Lowest < type > , \ <nl> + functor : : MaxOp < type > ) ; \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentMin " , type , index_type , \ <nl> + functor : : Highest < type > , \ <nl> + functor : : MinOp < type > ) ; \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentProd " , type , index_type , \ <nl> + functor : : One < type > , \ <nl> + functor : : ProdOp < type > ) ; <nl> + <nl> + # define REGISTER_COMPLEX_CPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentSum " , type , index_type , \ <nl> + functor : : Zero < type > , \ <nl> + functor : : SumOp < type > ) ; \ <nl> + REGISTER_CPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentProd " , type , index_type , \ <nl> + functor : : One < type > , \ <nl> + functor : : ProdOp < type > ) <nl> <nl> # define REGISTER_REAL_CPU_UNSORTED_KERNELS_ALL ( type ) \ <nl> REGISTER_REAL_CPU_UNSORTED_KERNELS ( type , int32 ) ; \ <nl> class UnsortedSegmentMaxOp : public UnsortedSegmentBaseOp < Device , T , Index > { <nl> TF_CALL_REAL_NUMBER_TYPES ( REGISTER_REAL_CPU_UNSORTED_KERNELS_ALL ) ; <nl> REGISTER_COMPLEX_CPU_UNSORTED_KERNELS_ALL ( complex64 ) ; <nl> REGISTER_COMPLEX_CPU_UNSORTED_KERNELS_ALL ( complex128 ) ; <nl> + <nl> # undef REGISTER_REAL_CPU_UNSORTED_KERNELS <nl> + # undef REGISTER_CPU_KERNEL_UNSORTEDSEGMENT <nl> # undef REGISTER_COMPLEX_CPU_UNSORTED_KERNELS <nl> # undef REGISTER_COMPLEX_CPU_UNSORTED_KERNELS_ALL <nl> # undef REGISTER_REAL_CPU_UNSORTED_KERNELS_ALL <nl> <nl> # if GOOGLE_CUDA <nl> - # define REGISTER_GPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> - REGISTER_KERNEL_BUILDER ( Name ( " UnsortedSegmentSum " ) \ <nl> - . Device ( DEVICE_GPU ) \ <nl> - . HostMemory ( " num_segments " ) \ <nl> - . TypeConstraint < type > ( " T " ) \ <nl> - . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> - UnsortedSegmentSumOp < GPUDevice , type , index_type > ) ; <nl> - <nl> - # define REGISTER_GPU_UNSORTED_KERNELS_ALL ( type ) \ <nl> - REGISTER_GPU_UNSORTED_KERNELS ( type , int32 ) ; \ <nl> - REGISTER_GPU_UNSORTED_KERNELS ( type , int64 ) ; <nl> + # define REGISTER_GPU_KERNEL_UNSORTEDSEGMENT ( \ <nl> + name , type , index_type , initial_value_functor , reduction_kernel_functor ) \ <nl> + REGISTER_KERNEL_BUILDER ( \ <nl> + Name ( name ) \ <nl> + . Device ( DEVICE_GPU ) \ <nl> + . HostMemory ( " num_segments " ) \ <nl> + . TypeConstraint < type > ( " T " ) \ <nl> + . TypeConstraint < index_type > ( " Tindices " ) , \ <nl> + UnsortedSegmentReductionOp < \ <nl> + type , index_type , \ <nl> + functor : : UnsortedSegmentFunctor < GPUDevice , type , index_type , \ <nl> + initial_value_functor , \ <nl> + reduction_kernel_functor > > ) <nl> + <nl> + / / sum is the only op that supports all input types currently <nl> + # define REGISTER_REAL_GPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> + REGISTER_GPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentMax " , type , index_type , \ <nl> + functor : : Lowest < type > , \ <nl> + functor : : MaxOpGpu < type > ) ; \ <nl> + REGISTER_GPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentMin " , type , index_type , \ <nl> + functor : : Highest < type > , \ <nl> + functor : : MinOpGpu < type > ) ; \ <nl> + REGISTER_GPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentProd " , type , index_type , \ <nl> + functor : : One < type > , \ <nl> + functor : : ProdOpGpu < type > ) ; <nl> + <nl> + # define REGISTER_SUM_GPU_UNSORTED_KERNELS ( type , index_type ) \ <nl> + REGISTER_GPU_KERNEL_UNSORTEDSEGMENT ( " UnsortedSegmentSum " , type , index_type , \ <nl> + functor : : Zero < type > , \ <nl> + functor : : SumOpGpu < type > ) ; <nl> + <nl> + # define REGISTER_REAL_GPU_UNSORTED_KERNELS_ALL ( type ) \ <nl> + REGISTER_REAL_GPU_UNSORTED_KERNELS ( type , int32 ) ; \ <nl> + REGISTER_REAL_GPU_UNSORTED_KERNELS ( type , int64 ) ; <nl> + <nl> + # define REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL ( type ) \ <nl> + REGISTER_SUM_GPU_UNSORTED_KERNELS ( type , int32 ) ; \ <nl> + REGISTER_SUM_GPU_UNSORTED_KERNELS ( type , int64 ) ; <nl> + <nl> + <nl> + TF_CALL_GPU_NUMBER_TYPES ( REGISTER_REAL_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + TF_CALL_int32 ( REGISTER_REAL_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + TF_CALL_GPU_NUMBER_TYPES ( REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + TF_CALL_int32 ( REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + TF_CALL_complex64 ( REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + TF_CALL_complex128 ( REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL ) ; <nl> + <nl> + # undef REGISTER_GPU_KERNEL_UNSORTEDSEGMENT <nl> + # undef REGISTER_REAL_GPU_UNSORTED_KERNELS <nl> + # undef REGISTER_SUM_GPU_UNSORTED_KERNELS <nl> + # undef REGISTER_REAL_GPU_UNSORTED_KERNELS_ALL <nl> + # undef REGISTER_SUM_GPU_UNSORTED_KERNELS_ALL <nl> <nl> - TF_CALL_GPU_NUMBER_TYPES ( REGISTER_GPU_UNSORTED_KERNELS_ALL ) ; <nl> - TF_CALL_complex64 ( REGISTER_GPU_UNSORTED_KERNELS_ALL ) ; <nl> - TF_CALL_complex128 ( REGISTER_GPU_UNSORTED_KERNELS_ALL ) ; <nl> - # undef REGISTER_GPU_UNSORTED_KERNELS <nl> - # undef REGISTER_GPU_UNSORTED_KERNELS_ALL <nl> # endif / / GOOGLE_CUDA <nl> <nl> + / / ____________________________________________________________________________ <nl> + / / Sparse segment reduction ops . <nl> + <nl> / / Same as SegmentReductionOp but takes as input a " sparse " tensor , represented <nl> / / by two dense tensors , one containing the data , and the other containing <nl> / / indices into the data . <nl> mmm a / tensorflow / core / kernels / segment_reduction_ops . h <nl> ppp b / tensorflow / core / kernels / segment_reduction_ops . h <nl> limitations under the License . <nl> # ifndef TENSORFLOW_CORE_KERNELS_SEGMENT_REDUCTION_OPS_H_ <nl> # define TENSORFLOW_CORE_KERNELS_SEGMENT_REDUCTION_OPS_H_ <nl> <nl> + / / This file requires the following include because it uses CudaAtomicMax : <nl> + / / # include " tensorflow / core / util / cuda_kernel_helper . h " <nl> + <nl> + / / Unfortunately we can ' t add the # include , since it breaks compilation for <nl> + / / non - GPU targets . This only breaks in clang , because it ' s more strict for <nl> + / / template code and CudaAtomicMax is used in template context . <nl> + <nl> # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> # include " tensorflow / core / framework / tensor . h " <nl> # include " tensorflow / core / framework / tensor_shape . h " <nl> struct SegmentSumFunctor { <nl> const Index data_size , const T * data , <nl> typename TTypes < T , 2 > : : Tensor output ) ; <nl> } ; <nl> - # endif <nl> <nl> - / / BaseFunctor for definition of UnsorteSegmentReductionOp <nl> - / / for usage without templates . <nl> - template < typename Device , typename T , typename Index > <nl> - struct UnsortedSegmentBaseFunctor { <nl> - virtual ~ UnsortedSegmentBaseFunctor ( ) { } <nl> - virtual void operator ( ) ( OpKernelContext * ctx , const Device & d , <nl> - const Index output_rows , <nl> - const TensorShape & segment_ids_shape , <nl> - typename TTypes < Index > : : ConstFlat segment_ids , <nl> - const Index data_size , const T * data , <nl> - typename TTypes < T , 2 > : : Tensor output ) { } ; <nl> - } ; <nl> + # endif <nl> <nl> - / / Functor for UnsortedSegmentSumOp . <nl> - / / output_rows : the number of output segments ( unique segment ids in <nl> - / / ' segment_ids ' ) . <nl> - / / segment_ids_shape : shape of ' segment_ids ' tensor . <nl> - / / segment_ids : unsorted map from input to output segment ids at which to <nl> - / / perform segment sum operation . <nl> - / / data_size : size of input data tensor . <nl> - / / data : input data tensor . <nl> - / / output : output reshaped to { output_rows , output . size / output_rows } <nl> - template < typename Device , typename T , typename Index > <nl> - struct UnsortedSegmentSumFunctor <nl> - : public UnsortedSegmentBaseFunctor < Device , T , Index > { <nl> - void operator ( ) ( OpKernelContext * ctx , const Device & d , <nl> - const Index output_rows , const TensorShape & segment_ids_shape , <nl> + template < typename Device , typename T , typename Index , typename InitialValueF , <nl> + typename ReductionF > <nl> + struct UnsortedSegmentFunctor { <nl> + void operator ( ) ( OpKernelContext * ctx , const Index num_segments , <nl> + const TensorShape & segment_ids_shape , <nl> typename TTypes < Index > : : ConstFlat segment_ids , <nl> const Index data_size , const T * data , <nl> typename TTypes < T , 2 > : : Tensor output ) ; <nl> } ; <nl> <nl> - / / Functor for UnsortedSegmentMaxOp . <nl> - / / output_rows : the number of output segments ( unique segment ids in <nl> - / / ' segment_ids ' ) . <nl> - / / segment_ids_shape : shape of ' segment_ids ' tensor . <nl> - / / segment_ids : unsorted map from input to output segment ids at which to <nl> - / / perform segment sum operation . <nl> - / / data_size : size of input data tensor . <nl> - / / data : input data tensor . <nl> - / / output : output reshaped to { output_rows , output . size / output_rows } <nl> - template < typename Device , typename T , typename Index > <nl> - struct UnsortedSegmentMaxFunctor <nl> - : public UnsortedSegmentBaseFunctor < Device , T , Index > { <nl> - void operator ( ) ( OpKernelContext * ctx , const Device & d , <nl> - const Index output_rows , const TensorShape & segment_ids_shape , <nl> - typename TTypes < Index > : : ConstFlat segment_ids , <nl> - const Index data_size , const T * data , <nl> - typename TTypes < T , 2 > : : Tensor output ) ; <nl> + # ifdef GOOGLE_CUDA <nl> + / / reduction functors for the gpu <nl> + template < typename T > <nl> + struct SumOpGpu { <nl> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator ( ) ( T * dest , <nl> + const T & value ) { <nl> + CudaAtomicAdd ( dest , value ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct ProdOpGpu { <nl> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator ( ) ( T * dest , <nl> + const T & value ) { <nl> + CudaAtomicMul ( dest , value ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct MaxOpGpu { <nl> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator ( ) ( T * dest , <nl> + const T & value ) { <nl> + CudaAtomicMax ( dest , value ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct MinOpGpu { <nl> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator ( ) ( T * dest , <nl> + const T & value ) { <nl> + CudaAtomicMin ( dest , value ) ; <nl> + } <nl> } ; <nl> + <nl> + # endif / / GOOGLE_CUDA <nl> + <nl> + / / initial value functors <nl> + template < typename T > <nl> + struct Zero { <nl> + EIGEN_STRONG_INLINE T operator ( ) ( ) const { return T ( 0 ) ; } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct One { <nl> + EIGEN_STRONG_INLINE T operator ( ) ( ) const { return T ( 1 ) ; } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct Lowest { <nl> + EIGEN_STRONG_INLINE T operator ( ) ( ) const { <nl> + return Eigen : : NumTraits < T > : : lowest ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct Highest { <nl> + EIGEN_STRONG_INLINE T operator ( ) ( ) const { <nl> + return Eigen : : NumTraits < T > : : highest ( ) ; <nl> + } <nl> + } ; <nl> + <nl> } / / namespace functor <nl> } / / namespace tensorflow <nl> <nl> mmm a / tensorflow / core / kernels / segment_reduction_ops_gpu . cu . cc <nl> ppp b / tensorflow / core / kernels / segment_reduction_ops_gpu . cu . cc <nl> limitations under the License . <nl> <nl> # define EIGEN_USE_GPU <nl> <nl> - # include " tensorflow / core / kernels / segment_reduction_ops . h " <nl> + / / We need to include cuda_kernel_helper . h before segment_reduction_ops . h <nl> + / / See comment in segment_reduction_ops . h for more details . <nl> + # include " tensorflow / core / util / cuda_kernel_helper . h " <nl> <nl> + # include " tensorflow / core / kernels / segment_reduction_ops . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> - # include " tensorflow / core / util / cuda_kernel_helper . h " <nl> + # include " tensorflow / core / util / cuda_device_functions . h " <nl> + <nl> <nl> namespace tensorflow { <nl> <nl> using GPUDevice = Eigen : : GpuDevice ; <nl> <nl> - / / Helper for UnusortedSegmentSumCustomKernel that adds value into dest <nl> - / / atomically . <nl> - template < typename T > <nl> - static __device__ __forceinline__ void AccumulateInto ( T * dest , const T & value ) { <nl> - CudaAtomicAdd ( dest , value ) ; <nl> - } <nl> - <nl> - / / Specializations of AccumulateInto for complex types , which CudaAtomicAdd does <nl> - / / not support . We treat a std : : complex < T > * as a T * ( the C + + standard section <nl> - / / 26 . 4 . 4 allows this explicitly ) and atomic add the real and imaginary <nl> - / / components individually . The operation as a whole is not atomic , but we can <nl> - / / safely treat the components independently for the purpose of accumulating . <nl> - template < > <nl> - __device__ __forceinline__ void AccumulateInto ( <nl> - std : : complex < float > * dest , const std : : complex < float > & value ) { <nl> - auto dest_scalar = reinterpret_cast < float * > ( dest ) ; <nl> - CudaAtomicAdd ( dest_scalar , value . real ( ) ) ; <nl> - CudaAtomicAdd ( dest_scalar + 1 , value . imag ( ) ) ; <nl> - } <nl> - <nl> - template < > <nl> - __device__ __forceinline__ void AccumulateInto ( <nl> - std : : complex < double > * dest , const std : : complex < double > & value ) { <nl> - auto dest_scalar = reinterpret_cast < double * > ( dest ) ; <nl> - CudaAtomicAdd ( dest_scalar , value . real ( ) ) ; <nl> - CudaAtomicAdd ( dest_scalar + 1 , value . imag ( ) ) ; <nl> - } <nl> - <nl> / / SortedSegmentSumFunctor kernel reduces input data just as <nl> / / UnsortedSegmentSumCustomKernel does except that input data <nl> / / is partitioned along the outer reduction dimension . This is <nl> __global__ void SortedSegmentSumCustomKernel ( const Index input_outer_dim_size , <nl> const Index * segment_ids , <nl> const T * input , T * output , <nl> const Index total_stripe_count ) { <nl> - CUDA_1D_KERNEL_LOOP ( stripe_index , total_stripe_count ) { <nl> + for ( int stripe_index : CudaGridRangeX ( total_stripe_count ) ) { <nl> const Index segment_offset = stripe_index % inner_dim_size ; <nl> const Index input_outer_dim_index_base = <nl> stripe_index / inner_dim_size * Index ( OuterDimTileSize ) ; <nl> __global__ void SortedSegmentSumCustomKernel ( const Index input_outer_dim_size , <nl> / / decide whether to write result to global memory using atomic <nl> / / operations <nl> if ( last_output_segment_id = = first_segment_id ) { <nl> - AccumulateInto < T > ( output + output_index , sum ) ; <nl> + CudaAtomicAdd ( output + output_index , sum ) ; <nl> } else { <nl> * ( output + output_index ) = sum ; <nl> } <nl> __global__ void SortedSegmentSumCustomKernel ( const Index input_outer_dim_size , <nl> / / the following strip . <nl> const Index output_index = <nl> last_output_segment_id * inner_dim_size + segment_offset ; <nl> - AccumulateInto < T > ( output + output_index , sum ) ; <nl> + CudaAtomicAdd ( output + output_index , sum ) ; <nl> } <nl> } <nl> <nl> - / / UnsortedSegmentSumFunctor kernel processes ' input_total_size ' elements . <nl> + / / UnsortedSegmentSumKernel processes ' input_total_size ' elements . <nl> / / Each element is mapped from input to output by a combination of its <nl> / / ' segment_ids ' mapping and ' inner_dim_size ' . <nl> - template < typename T , typename Index > <nl> - __global__ void UnsortedSegmentSumCustomKernel ( <nl> - const Index input_outer_dim_size , const Index inner_dim_size , <nl> - const Index output_outer_dim_size , const Index * segment_ids , const T * input , <nl> - T * output ) { <nl> + template < typename T , typename Index , typename KernelReductionFunctor > <nl> + __global__ void UnsortedSegmentCustomKernel ( const Index input_outer_dim_size , <nl> + const Index inner_dim_size , <nl> + const Index output_outer_dim_size , <nl> + const Index * segment_ids , <nl> + const T * input , T * output ) { <nl> const Index input_total_size = input_outer_dim_size * inner_dim_size ; <nl> const Index output_total_size = output_outer_dim_size * inner_dim_size ; <nl> - CUDA_1D_KERNEL_LOOP ( input_index , input_total_size ) { <nl> + for ( int input_index : CudaGridRangeX ( input_total_size ) ) { <nl> const Index input_segment_index = input_index / inner_dim_size ; <nl> const Index segment_offset = input_index % inner_dim_size ; <nl> const Index output_segment_index = segment_ids [ input_segment_index ] ; <nl> - <nl> if ( output_segment_index < 0 | | output_segment_index > = output_total_size ) { <nl> continue ; <nl> } <nl> const Index output_index = <nl> output_segment_index * inner_dim_size + segment_offset ; <nl> - AccumulateInto < T > ( output + output_index , ldg ( input + input_index ) ) ; <nl> + KernelReductionFunctor ( ) ( output + output_index , ldg ( input + input_index ) ) ; <nl> } <nl> } <nl> <nl> void SegmentSumFunctor < T , Index > : : operator ( ) ( <nl> < < < config . block_count , config . thread_per_block , 0 , d . stream ( ) > > > ( <nl> input_outer_dim_size , input_inner_dim_size , output_rows , <nl> segment_ids . data ( ) , data , output . data ( ) , total_stripe_count ) ; <nl> - } ; <nl> + } <nl> <nl> - / / UnsortedSegmentSumFunctor implementation for GPUDevice . <nl> - template < typename T , typename Index > <nl> - struct UnsortedSegmentSumFunctor < GPUDevice , T , Index > <nl> - : UnsortedSegmentBaseFunctor < GPUDevice , T , Index > { <nl> - void operator ( ) ( OpKernelContext * ctx , const GPUDevice & d , <nl> - const Index output_rows , const TensorShape & segment_ids_shape , <nl> + template < typename T , typename Index , typename InitialValueF , <nl> + typename ReductionF > <nl> + struct UnsortedSegmentFunctor < GPUDevice , T , Index , InitialValueF , ReductionF > { <nl> + void operator ( ) ( OpKernelContext * ctx , const Index num_segments , <nl> + const TensorShape & segment_ids_shape , <nl> typename TTypes < Index > : : ConstFlat segment_ids , <nl> const Index data_size , const T * data , <nl> - typename TTypes < T , 2 > : : Tensor output ) override { <nl> + typename TTypes < T , 2 > : : Tensor output ) { <nl> if ( output . size ( ) = = 0 ) { <nl> return ; <nl> } <nl> - / / Set ' output ' to zeros . <nl> + / / Set ' output ' to initial value . <nl> + GPUDevice d = ctx - > template eigen_device < GPUDevice > ( ) ; <nl> CudaLaunchConfig config = GetCudaLaunchConfig ( output . size ( ) , d ) ; <nl> - SetZero < < < config . block_count , config . thread_per_block , 0 , d . stream ( ) > > > ( <nl> - output . size ( ) , output . data ( ) ) ; <nl> + SetToValue < < < config . block_count , config . thread_per_block , 0 , d . stream ( ) > > > ( <nl> + output . size ( ) , output . data ( ) , InitialValueF ( ) ( ) ) ; <nl> if ( data_size = = 0 | | segment_ids_shape . num_elements ( ) = = 0 ) { <nl> return ; <nl> } <nl> - <nl> - / / Launch kernel to compute unsorted segment sum . <nl> + / / Launch kernel to compute unsorted segment reduction . <nl> / / Notes : <nl> - / / * ) ' input_total_size ' is the total number of elements to process . <nl> + / / * ) ' data_size ' is the total number of elements to process . <nl> / / * ) ' segment_ids . shape ' is a prefix of data ' s shape . <nl> / / * ) ' input_outer_dim_size ' is the total number of segments to process . <nl> - const Index input_total_size = data_size ; <nl> const Index input_outer_dim_size = segment_ids . dimension ( 0 ) ; <nl> - const Index input_inner_dim_size = input_total_size / input_outer_dim_size ; <nl> + const Index input_inner_dim_size = data_size / input_outer_dim_size ; <nl> + config = GetCudaLaunchConfig ( data_size , d ) ; <nl> <nl> - config = GetCudaLaunchConfig ( input_total_size , d ) ; <nl> - UnsortedSegmentSumCustomKernel < T , Index > <nl> + UnsortedSegmentCustomKernel < T , Index , ReductionF > <nl> < < < config . block_count , config . thread_per_block , 0 , d . stream ( ) > > > ( <nl> - input_outer_dim_size , input_inner_dim_size , output_rows , <nl> + input_outer_dim_size , input_inner_dim_size , num_segments , <nl> segment_ids . data ( ) , data , output . data ( ) ) ; <nl> } <nl> } ; <nl> struct UnsortedSegmentSumFunctor < GPUDevice , T , Index > <nl> <nl> TF_CALL_GPU_NUMBER_TYPES ( DEFINE_SORTED_GPU_SPECS ) ; <nl> <nl> - # define DEFINE_GPU_SPECS_INDEX ( T , Index ) \ <nl> - template struct UnsortedSegmentSumFunctor < GPUDevice , T , Index > <nl> - <nl> - # define DEFINE_GPU_SPECS ( T ) \ <nl> - DEFINE_GPU_SPECS_INDEX ( T , int32 ) ; \ <nl> - DEFINE_GPU_SPECS_INDEX ( T , int64 ) ; <nl> - <nl> - TF_CALL_GPU_NUMBER_TYPES ( DEFINE_GPU_SPECS ) ; <nl> - TF_CALL_complex64 ( DEFINE_GPU_SPECS ) ; <nl> - TF_CALL_complex128 ( DEFINE_GPU_SPECS ) ; <nl> - <nl> - # undef DEFINE_GPU_SPECS <nl> - # undef DEFINE_GPU_SPECS_INDEX <nl> + # define DEFINE_REAL_UNSORTED_GPU_SPECS_INDEX ( T , Index ) \ <nl> + template struct UnsortedSegmentFunctor < \ <nl> + GPUDevice , T , Index , functor : : Lowest < T > , functor : : MaxOpGpu < T > > ; \ <nl> + template struct UnsortedSegmentFunctor < \ <nl> + GPUDevice , T , Index , functor : : Highest < T > , functor : : MinOpGpu < T > > ; \ <nl> + template struct UnsortedSegmentFunctor < GPUDevice , T , Index , functor : : One < T > , \ <nl> + functor : : ProdOpGpu < T > > ; <nl> + <nl> + / / sum is the only op that supports all input types currently <nl> + # define DEFINE_SUM_UNSORTED_GPU_SPECS_INDEX ( T , Index ) \ <nl> + template struct UnsortedSegmentFunctor < \ <nl> + GPUDevice , T , Index , functor : : Zero < T > , functor : : SumOpGpu < T > > ; <nl> + <nl> + # define DEFINE_REAL_GPU_SPECS ( T ) \ <nl> + DEFINE_REAL_UNSORTED_GPU_SPECS_INDEX ( T , int32 ) ; \ <nl> + DEFINE_REAL_UNSORTED_GPU_SPECS_INDEX ( T , int64 ) ; <nl> + <nl> + # define DEFINE_SUM_GPU_SPECS ( T ) \ <nl> + DEFINE_SUM_UNSORTED_GPU_SPECS_INDEX ( T , int32 ) ; \ <nl> + DEFINE_SUM_UNSORTED_GPU_SPECS_INDEX ( T , int64 ) ; <nl> + <nl> + TF_CALL_GPU_NUMBER_TYPES ( DEFINE_REAL_GPU_SPECS ) ; <nl> + TF_CALL_int32 ( DEFINE_REAL_GPU_SPECS ) ; <nl> + TF_CALL_GPU_NUMBER_TYPES ( DEFINE_SUM_GPU_SPECS ) ; <nl> + TF_CALL_int32 ( DEFINE_SUM_GPU_SPECS ) ; <nl> + TF_CALL_complex64 ( DEFINE_SUM_GPU_SPECS ) ; <nl> + TF_CALL_complex128 ( DEFINE_SUM_GPU_SPECS ) ; <nl> + <nl> + # undef DEFINE_SORTED_GPU_SPECS_INDEX <nl> + # undef DEFINE_SORTED_GPU_SPECS <nl> + # undef DEFINE_REAL_UNSORTED_GPU_SPECS_INDEX <nl> + # undef DEFINE_SUM_UNSORTED_GPU_SPECS_INDEX <nl> + # undef DEFINE_REAL_GPU_SPECS <nl> + # undef DEFINE_SUM_GPU_SPECS <nl> <nl> } / / namespace functor <nl> } / / namespace tensorflow <nl> mmm a / tensorflow / core / kernels / unique_op . cc <nl> ppp b / tensorflow / core / kernels / unique_op . cc <nl> class UniqueOp : public OpKernel { <nl> . Device ( DEVICE_CPU ) \ <nl> . TypeConstraint < type > ( " T " ) \ <nl> . TypeConstraint < int64 > ( " out_idx " ) , \ <nl> + UniqueOp < type , int64 > ) ; \ <nl> + REGISTER_KERNEL_BUILDER ( Name ( " UniqueWithCountsV2 " ) \ <nl> + . Device ( DEVICE_CPU ) \ <nl> + . TypeConstraint < type > ( " T " ) \ <nl> + . TypeConstraint < int32 > ( " out_idx " ) , \ <nl> + UniqueOp < type , int32 > ) \ <nl> + REGISTER_KERNEL_BUILDER ( Name ( " UniqueWithCountsV2 " ) \ <nl> + . Device ( DEVICE_CPU ) \ <nl> + . TypeConstraint < type > ( " T " ) \ <nl> + . TypeConstraint < int64 > ( " out_idx " ) , \ <nl> UniqueOp < type , int64 > ) <nl> TF_CALL_REAL_NUMBER_TYPES ( REGISTER_UNIQUE ) ; <nl> REGISTER_UNIQUE ( string ) <nl> mmm a / tensorflow / core / kernels / unravel_index_op . cc <nl> ppp b / tensorflow / core / kernels / unravel_index_op . cc <nl> limitations under the License . <nl> <nl> # define EIGEN_USE_THREADS <nl> <nl> - # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> # include " tensorflow / core / framework / tensor . h " <nl> # include " tensorflow / core / framework / types . h " <nl> + # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> <nl> namespace tensorflow { <nl> <nl> mmm a / tensorflow / core / ops / array_ops . cc <nl> ppp b / tensorflow / core / ops / array_ops . cc <nl> REGISTER_OP ( " UniqueWithCounts " ) <nl> return Status : : OK ( ) ; <nl> } ) ; <nl> <nl> + REGISTER_OP ( " UniqueWithCountsV2 " ) <nl> + . Input ( " x : T " ) <nl> + . Input ( " axis : Taxis " ) <nl> + . Output ( " y : T " ) <nl> + . Output ( " idx : out_idx " ) <nl> + . Output ( " count : out_idx " ) <nl> + . Attr ( " T : type " ) <nl> + . Attr ( " Taxis : { int32 , int64 } = DT_INT64 " ) <nl> + . Attr ( " out_idx : { int32 , int64 } = DT_INT32 " ) <nl> + . SetShapeFn ( [ ] ( InferenceContext * c ) { <nl> + auto uniq = c - > Vector ( InferenceContext : : kUnknownDim ) ; <nl> + c - > set_output ( 0 , uniq ) ; <nl> + c - > set_output ( 1 , c - > input ( 0 ) ) ; <nl> + c - > set_output ( 2 , uniq ) ; <nl> + return Status : : OK ( ) ; <nl> + } ) ; <nl> + <nl> namespace { <nl> <nl> Status ShapeShapeFn ( InferenceContext * c ) { <nl> mmm a / tensorflow / core / ops / math_ops . cc <nl> ppp b / tensorflow / core / ops / math_ops . cc <nl> REGISTER_OP ( " UnsortedSegmentMax " ) <nl> . Attr ( " Tnumsegments : { int32 , int64 } = DT_INT32 " ) <nl> . SetShapeFn ( UnsortedSegmentReductionShapeFn ) ; <nl> <nl> + REGISTER_OP ( " UnsortedSegmentMin " ) <nl> + . Input ( " data : T " ) <nl> + . Input ( " segment_ids : Tindices " ) <nl> + . Input ( " num_segments : Tnumsegments " ) <nl> + . Output ( " output : T " ) <nl> + . Attr ( " T : realnumbertype " ) <nl> + . Attr ( " Tindices : { int32 , int64 } " ) <nl> + . Attr ( " Tnumsegments : { int32 , int64 } = DT_INT32 " ) <nl> + . SetShapeFn ( UnsortedSegmentReductionShapeFn ) ; <nl> + <nl> + REGISTER_OP ( " UnsortedSegmentProd " ) <nl> + . Input ( " data : T " ) <nl> + . Input ( " segment_ids : Tindices " ) <nl> + . Input ( " num_segments : Tnumsegments " ) <nl> + . Output ( " output : T " ) <nl> + . Attr ( " T : realnumbertype " ) <nl> + . Attr ( " Tindices : { int32 , int64 } " ) <nl> + . Attr ( " Tnumsegments : { int32 , int64 } = DT_INT32 " ) <nl> + . SetShapeFn ( UnsortedSegmentReductionShapeFn ) ; <nl> + <nl> REGISTER_OP ( " SparseSegmentSum " ) <nl> . Input ( " data : T " ) <nl> . Input ( " indices : Tidx " ) <nl> mmm a / tensorflow / core / platform / s3 / s3_file_system . cc <nl> ppp b / tensorflow / core / platform / s3 / s3_file_system . cc <nl> limitations under the License . <nl> # include < aws / core / utils / StringUtils . h > <nl> # include < aws / core / utils / logging / AWSLogging . h > <nl> # include < aws / core / utils / logging / LogSystemInterface . h > <nl> + # include < aws / core / utils / StringUtils . h > <nl> # include < aws / s3 / S3Client . h > <nl> # include < aws / s3 / S3Errors . h > <nl> # include < aws / s3 / model / CopyObjectRequest . h > <nl> mmm a / tensorflow / core / platform / windows / port . cc <nl> ppp b / tensorflow / core / platform / windows / port . cc <nl> limitations under the License . <nl> # endif <nl> <nl> # include < Windows . h > <nl> + # include < shlwapi . h > <nl> <nl> # include " tensorflow / core / platform / cpu_info . h " <nl> # include " tensorflow / core / platform / demangle . h " <nl> bool Snappy_Uncompress ( const char * input , size_t length , char * output ) { <nl> string Demangle ( const char * mangled ) { return mangled ; } <nl> <nl> double NominalCPUFrequency ( ) { <nl> - # ifdef TENSORFLOW_USE_ABSL <nl> - return absl : : base_internal : : NominalCPUFrequency ( ) ; <nl> - # else <nl> + DWORD data ; <nl> + DWORD data_size = sizeof ( data ) ; <nl> + # pragma comment ( lib , " shlwapi . lib " ) / / For SHGetValue ( ) . <nl> + if ( SUCCEEDED ( <nl> + SHGetValueA ( HKEY_LOCAL_MACHINE , <nl> + " HARDWARE \ \ DESCRIPTION \ \ System \ \ CentralProcessor \ \ 0 " , <nl> + " ~ MHz " , nullptr , & data , & data_size ) ) ) { <nl> + return data * 1e6 ; / / Value is MHz . <nl> + } <nl> return 1 . 0 ; <nl> - # endif <nl> } <nl> <nl> int64 AvailableRam ( ) { <nl> mmm a / tensorflow / core / util / cuda_device_functions . h <nl> ppp b / tensorflow / core / util / cuda_device_functions . h <nl> limitations under the License . <nl> <nl> # include < algorithm > <nl> # include < complex > <nl> + # include " third_party / eigen3 / unsupported / Eigen / CXX11 / Tensor " <nl> # include " cuda / include / cuda . h " <nl> - # include " cuda / include / device_functions . h " <nl> # include " tensorflow / core / platform / types . h " <nl> <nl> - # if CUDA_VERSION > = 7050 <nl> - # include " cuda / include / cuda_fp16 . h " <nl> - # endif / / CUDA_VERSION > = 7050 <nl> - <nl> namespace tensorflow { <nl> <nl> namespace detail { <nl> __global__ void SetZero ( const int count , T * ptr ) { <nl> } <nl> } <nl> <nl> + / / Helper to set all tensor entries to a specific value . <nl> + template < typename T > <nl> + __global__ void SetToValue ( const int count , T * ptr , T value ) { <nl> + / / Check that the grid is one dimensional and index doesn ' t overflow . <nl> + assert ( blockDim . y = = 1 & & blockDim . z = = 1 ) ; <nl> + assert ( blockDim . x * gridDim . x / blockDim . x = = gridDim . x ) ; <nl> + for ( int i : CudaGridRangeX ( count ) ) { <nl> + ptr [ i ] = value ; <nl> + } <nl> + } <nl> + <nl> namespace detail { <nl> / / Helper function for atomic accumulation implemented as CAS . <nl> template < typename T , typename F > <nl> __device__ double CudaAtomicCasHelper ( double * ptr , F accumulate ) { <nl> } ) ) ; <nl> } <nl> <nl> + / / Overload of above function for half . Note that we don ' t have <nl> + / / atomicCAS ( ) for anything less than 32 bits , so we need to include the <nl> + / / other 16 bits in the operation . <nl> + / / <nl> + / / This version is going to be very slow <nl> + / / under high concurrency , since most threads will be spinning on failing <nl> + / / their compare - and - swap tests . ( The fact that we get false sharing on the <nl> + / / neighboring fp16 makes this even worse . ) If you are doing a large reduction , <nl> + / / you are much better off with doing the intermediate steps in fp32 and then <nl> + / / switching to fp16 as late as you can in the calculations . <nl> + / / <nl> + / / Note : Assumes little endian . <nl> + template < typename F > <nl> + __device__ Eigen : : half CudaAtomicCasHelper ( Eigen : : half * ptr , F accumulate ) { <nl> + # if defined ( __BYTE_ORDER__ ) & & defined ( __ORDER_LITTLE_ENDIAN__ ) <nl> + static_assert ( __BYTE_ORDER__ = = __ORDER_LITTLE_ENDIAN__ , " Not little endian " ) ; <nl> + # endif <nl> + namespace half_impl = Eigen : : half_impl ; <nl> + intptr_t intptr = reinterpret_cast < intptr_t > ( ptr ) ; <nl> + assert ( ! ( intptr & 0x1 ) ) ; / / should be 2 - aligned . <nl> + if ( intptr & 0x2 ) { <nl> + / / The half is in the second part of the uint32 ( upper 16 bits ) . <nl> + uint32 * address = reinterpret_cast < uint32 * > ( intptr - 2 ) ; <nl> + uint32 result = CudaAtomicCasHelper ( address , [ accumulate ] ( uint32 arg ) { <nl> + unsigned short high = static_cast < unsigned short > ( arg > > 16 ) ; <nl> + Eigen : : half acc = accumulate ( half_impl : : raw_uint16_to_half ( high ) ) ; <nl> + return ( static_cast < uint32 > ( acc . x ) < < 16 ) | ( arg & 0xffff ) ; <nl> + } ) ; <nl> + return half_impl : : raw_uint16_to_half ( static_cast < uint16 > ( result > > 16 ) ) ; <nl> + } else { <nl> + / / The half is in the first part of the uint32 ( lower 16 bits ) . <nl> + uint32 * address = reinterpret_cast < uint32 * > ( intptr ) ; <nl> + uint32 result = CudaAtomicCasHelper ( address , [ accumulate ] ( uint32 arg ) { <nl> + unsigned short low = static_cast < unsigned short > ( arg & 0xffff ) ; <nl> + Eigen : : half acc = accumulate ( half_impl : : raw_uint16_to_half ( low ) ) ; <nl> + return ( arg & 0xffff0000 ) | static_cast < uint32 > ( acc . x ) ; <nl> + } ) ; <nl> + return half_impl : : raw_uint16_to_half ( static_cast < uint16 > ( result & 0xffff ) ) ; <nl> + } <nl> + } <nl> + <nl> template < typename From , typename To > <nl> using ToTypeIfConvertible = <nl> typename std : : enable_if < std : : is_convertible < From , To > : : value , To > : : type ; <nl> template < typename T , typename U > <nl> __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicAdd ( T * ptr , U value ) { <nl> return atomicAdd ( ptr , value ) ; <nl> } <nl> + <nl> + __device__ inline Eigen : : half CudaAtomicAdd ( Eigen : : half * ptr , <nl> + Eigen : : half value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( Eigen : : half a ) { return a + value ; } ) ; <nl> + } <nl> + <nl> + <nl> # if __CUDA_ARCH__ < 600 <nl> __device__ inline double CudaAtomicAdd ( double * ptr , double value ) { <nl> return detail : : CudaAtomicCasHelper ( ptr , <nl> __device__ inline double CudaAtomicAdd ( double * ptr , double value ) { <nl> return result ; <nl> } <nl> # endif <nl> - <nl> + / / CudaAtomicAdd <nl> + / / Specializations of CudaAtomicAdd for complex types , which CudaAtomicAdd does <nl> + / / not support . We treat a std : : complex < T > * as a T * ( the C + + standard section <nl> + / / 26 . 4 . 4 allows this explicitly ) and atomic add the real and imaginary <nl> + / / components individually . The operation as a whole is not atomic , but we can <nl> + / / safely treat the components independently for the purpose of accumulating . <nl> + __device__ inline std : : complex < float > CudaAtomicAdd ( std : : complex < float > * ptr , <nl> + std : : complex < float > value ) { <nl> + auto ptr_scalar = reinterpret_cast < float * > ( ptr ) ; <nl> + return std : : complex < float > ( CudaAtomicAdd ( ptr_scalar , value . real ( ) ) , <nl> + CudaAtomicAdd ( ptr_scalar + 1 , value . imag ( ) ) ) ; <nl> + } <nl> + <nl> + __device__ inline std : : complex < double > CudaAtomicAdd ( <nl> + std : : complex < double > * ptr , std : : complex < double > value ) { <nl> + auto ptr_scalar = reinterpret_cast < double * > ( ptr ) ; <nl> + return std : : complex < double > ( CudaAtomicAdd ( ptr_scalar , value . real ( ) ) , <nl> + CudaAtomicAdd ( ptr_scalar + 1 , value . imag ( ) ) ) ; <nl> + } <nl> + <nl> + / / CudaAtomicSub <nl> template < typename T , typename U > <nl> __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicSub ( T * ptr , U value ) { <nl> return atomicSub ( ptr , value ) ; <nl> } <nl> + <nl> / / Specializations of substraction which add the negative value . <nl> __device__ inline float CudaAtomicSub ( float * ptr , float value ) { <nl> return CudaAtomicAdd ( ptr , - value ) ; <nl> } <nl> + <nl> __device__ inline double CudaAtomicSub ( double * ptr , double value ) { <nl> return CudaAtomicAdd ( ptr , - value ) ; <nl> } <nl> + <nl> __device__ inline tensorflow : : uint64 CudaAtomicSub ( tensorflow : : uint64 * ptr , <nl> tensorflow : : uint64 value ) { <nl> return CudaAtomicAdd ( ptr , - value ) ; <nl> } <nl> <nl> + __device__ inline Eigen : : half CudaAtomicSub ( Eigen : : half * ptr , <nl> + Eigen : : half value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( Eigen : : half a ) { return a - value ; } ) ; <nl> + } <nl> + <nl> + / / CudaAtomicMax <nl> template < typename T , typename U > <nl> __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicMax ( T * ptr , U value ) { <nl> return atomicMax ( ptr , value ) ; <nl> } <nl> + <nl> + __device__ inline float CudaAtomicMax ( float * ptr , float value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( float a ) { return max ( a , value ) ; } ) ; <nl> + } <nl> + <nl> + __device__ inline double CudaAtomicMax ( double * ptr , double value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( double a ) { return max ( a , value ) ; } ) ; <nl> + } <nl> + <nl> + __device__ inline Eigen : : half CudaAtomicMax ( Eigen : : half * ptr , <nl> + Eigen : : half value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( Eigen : : half a ) { return max ( a , value ) ; } ) ; <nl> + } <nl> + <nl> # if __CUDA_ARCH__ < 320 <nl> __device__ inline tensorflow : : uint64 CudaAtomicMax ( tensorflow : : uint64 * ptr , <nl> tensorflow : : uint64 value ) { <nl> __device__ inline tensorflow : : uint64 CudaAtomicMax ( tensorflow : : uint64 * ptr , <nl> } <nl> # endif <nl> <nl> + / / CudaAtomicMin <nl> + template < typename T , typename U > <nl> + __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicMin ( T * ptr , U value ) { <nl> + return atomicMin ( ptr , value ) ; <nl> + } <nl> + <nl> + __device__ inline float CudaAtomicMin ( float * ptr , float value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( float a ) { return min ( a , value ) ; } ) ; <nl> + } <nl> + <nl> + __device__ inline double CudaAtomicMin ( double * ptr , double value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( double a ) { return min ( a , value ) ; } ) ; <nl> + } <nl> + <nl> + __device__ inline Eigen : : half CudaAtomicMin ( Eigen : : half * ptr , <nl> + Eigen : : half value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( Eigen : : half a ) { return min ( a , value ) ; } ) ; <nl> + } <nl> + <nl> + # if __CUDA_ARCH__ < 320 <nl> + __device__ inline tensorflow : : uint64 CudaAtomicMin ( tensorflow : : uint64 * ptr , <nl> + tensorflow : : uint64 value ) { <nl> + return detail : : CudaAtomicCasHelper ( <nl> + ptr , [ value ] ( tensorflow : : uint64 a ) { return min ( a , value ) ; } ) ; <nl> + } <nl> + # endif <nl> + <nl> + / / CudaAtomicMul <nl> template < typename T , typename U > <nl> __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicMul ( T * ptr , U value ) { <nl> return detail : : CudaAtomicCasHelper ( ptr , [ value ] ( T a ) { return a * value ; } ) ; <nl> } <nl> + <nl> + / / CudaAtomicDiv <nl> template < typename T , typename U > <nl> __device__ detail : : ToTypeIfConvertible < U , T > CudaAtomicDiv ( T * ptr , U value ) { <nl> return detail : : CudaAtomicCasHelper ( ptr , [ value ] ( T a ) { return a / value ; } ) ; <nl> mmm a / tensorflow / core / util / cuda_kernel_helper . h <nl> ppp b / tensorflow / core / util / cuda_kernel_helper . h <nl> __device__ EIGEN_ALWAYS_INLINE Eigen : : half CudaShuffleXorSync ( <nl> CudaShuffleXorSync ( mask , static_cast < uint16 > ( value ) , lane_mask , width ) ) ; <nl> } <nl> <nl> - namespace detail { <nl> - / / Overload of above function for half . Note that we don ' t have <nl> - / / atomicCAS ( ) for anything less than 32 bits , so we need to include the <nl> - / / other 16 bits in the operation . <nl> - / / <nl> - / / This version is going to be very slow <nl> - / / under high concurrency , since most threads will be spinning on failing <nl> - / / their compare - and - swap tests . ( The fact that we get false sharing on the <nl> - / / neighboring fp16 makes this even worse . ) If you are doing a large reduction , <nl> - / / you are much better off with doing the intermediate steps in fp32 and then <nl> - / / switching to fp16 as late as you can in the calculations . <nl> - / / <nl> - / / Note : Assumes little endian . <nl> - template < typename F > <nl> - __device__ Eigen : : half CudaAtomicCasHelper ( Eigen : : half * ptr , F accumulate ) { <nl> - # if defined ( __BYTE_ORDER__ ) & & defined ( __ORDER_LITTLE_ENDIAN__ ) <nl> - static_assert ( __BYTE_ORDER__ = = __ORDER_LITTLE_ENDIAN__ , " Not little endian " ) ; <nl> - # endif <nl> - namespace half_impl = Eigen : : half_impl ; <nl> - intptr_t intptr = reinterpret_cast < intptr_t > ( ptr ) ; <nl> - assert ( ! ( intptr & 0x1 ) ) ; / / should be 2 - aligned . <nl> - if ( intptr & 0x2 ) { <nl> - / / The half is in the second part of the uint32 ( upper 16 bits ) . <nl> - uint32 * address = reinterpret_cast < uint32 * > ( intptr - 2 ) ; <nl> - uint32 result = CudaAtomicCasHelper ( address , [ accumulate ] ( uint32 arg ) { <nl> - unsigned short high = static_cast < unsigned short > ( arg > > 16 ) ; <nl> - Eigen : : half acc = accumulate ( half_impl : : raw_uint16_to_half ( high ) ) ; <nl> - return ( static_cast < uint32 > ( acc . x ) < < 16 ) | ( arg & 0xffff ) ; <nl> - } ) ; <nl> - return half_impl : : raw_uint16_to_half ( static_cast < uint16 > ( result > > 16 ) ) ; <nl> - } else { <nl> - / / The half is in the first part of the uint32 ( lower 16 bits ) . <nl> - uint32 * address = reinterpret_cast < uint32 * > ( intptr ) ; <nl> - uint32 result = CudaAtomicCasHelper ( address , [ accumulate ] ( uint32 arg ) { <nl> - unsigned short low = static_cast < unsigned short > ( arg & 0xffff ) ; <nl> - Eigen : : half acc = accumulate ( half_impl : : raw_uint16_to_half ( low ) ) ; <nl> - return ( arg & 0xffff0000 ) | static_cast < uint32 > ( acc . x ) ; <nl> - } ) ; <nl> - return half_impl : : raw_uint16_to_half ( static_cast < uint16 > ( result & 0xffff ) ) ; <nl> - } <nl> - } <nl> - } / / namespace detail <nl> - <nl> - __device__ inline Eigen : : half CudaAtomicAdd ( Eigen : : half * ptr , <nl> - Eigen : : half value ) { <nl> - return detail : : CudaAtomicCasHelper ( <nl> - ptr , [ value ] ( Eigen : : half a ) { return a + value ; } ) ; <nl> - } <nl> - __device__ inline Eigen : : half CudaAtomicSub ( Eigen : : half * ptr , <nl> - Eigen : : half value ) { <nl> - return detail : : CudaAtomicCasHelper ( <nl> - ptr , [ value ] ( Eigen : : half a ) { return a - value ; } ) ; <nl> - } <nl> - <nl> namespace cuda_helper { <nl> template < typename IntType > <nl> __device__ IntType upper_bound ( IntType * first , IntType count , IntType val ) { <nl> mmm a / tensorflow / docs_src / get_started / checkpoints . md <nl> ppp b / tensorflow / docs_src / get_started / checkpoints . md <nl> classifier = tf . estimator . DNNClassifier ( <nl> <nl> The first time you call an Estimator ' s ` train ` method , TensorFlow saves a <nl> checkpoint to the ` model_dir ` . Each subsequent call to the Estimator ' s <nl> - ` train ` , ` eval ` , or ` predict ` method causes the following : <nl> + ` train ` , ` evaluate ` , or ` predict ` method causes the following : <nl> <nl> 1 . The Estimator builds the model ' s <nl> [ graph ] ( https : / / developers . google . com / machine - learning / glossary / # graph ) <nl> does not match the shape stored in checkpoint : [ 20 ] <nl> <nl> To run experiments in which you train and compare slightly different <nl> versions of a model , save a copy of the code that created each <nl> - ` model - dir ` , possibly by creating a separate git branch for each version . <nl> + ` model_dir ` , possibly by creating a separate git branch for each version . <nl> This separation will keep your checkpoints recoverable . <nl> <nl> # # Summary <nl> mmm a / tensorflow / docs_src / get_started / custom_estimators . md <nl> ppp b / tensorflow / docs_src / get_started / custom_estimators . md <nl> is connected to every node in the preceding layer . Here ' s the relevant code : <nl> ` ` ` <nl> <nl> * The ` units ` parameter defines the number of output neurons in a given layer . <nl> - * The ` activation ` parameter defines the [ activation function ] ( https : / / developers . google . com / machine - learning / glossary / # a ) — <nl> + * The ` activation ` parameter defines the [ activation function ] ( https : / / developers . google . com / machine - learning / glossary / # activation_function ) — <nl> [ Relu ] ( https : / / developers . google . com / machine - learning / glossary / # ReLU ) in this <nl> case . <nl> <nl> mmm a / tensorflow / docs_src / performance / xla / operation_semantics . md <nl> ppp b / tensorflow / docs_src / performance / xla / operation_semantics . md <nl> element in ` operand ` . The ` feature_index ` must be a valid index for the feature <nl> dimension in ` operand ` . <nl> <nl> The algorithm goes as follows for each batch in ` operand ` \ \ ( x \ \ ) that <nl> - contains ` m ` elements with ` w ` and ` h ` as the size of spatial dimensions ( <nl> - assuming ` operand ` is an 4 dimensional array ) : <nl> + contains ` m ` elements with ` w ` and ` h ` as the size of spatial dimensions <nl> + ( assuming ` operand ` is an 4 dimensional array ) : <nl> <nl> - Calculates batch mean \ \ ( \ mu_l \ \ ) for each feature ` l ` in feature dimension : <nl> \ \ ( \ mu_l = \ frac { 1 } { mwh } \ sum_ { i = 1 } ^ m \ sum_ { j = 1 } ^ w \ sum_ { k = 1 } ^ h x_ { ijkl } \ \ ) <nl> Similar to a ` tf . bitcast ` in TensorFlow , performs an element - wise bitcast <nl> operation from a data shape to a target shape . The dimensions must match , and <nl> the conversion is an element - wise one ; e . g . ` s32 ` elements become ` f32 ` elements <nl> via bitcast routine . Bitcast is implemented as a low - level cast , so machines <nl> - with different floating point representations will give different results . <nl> + with different floating - point representations will give different results . <nl> <nl> < b > ` BitcastConvertType ( operand , new_element_type ) ` < / b > <nl> <nl> each other ) and contains the arguments in the order that they were specified . <nl> : : : concatenated between the ` operands ` . : <nl> <nl> With the exception of ` dimension ` all dimensions must be the same . This is <nl> - because XLA does not support " ragged " arrays Also note that rank - 0 values <nl> + because XLA does not support " ragged " arrays . Also note that rank - 0 values <nl> cannot be concatenated ( as it ' s impossible to name the dimension along which the <nl> concatenation occurs ) . <nl> <nl> filter / kernel / window . The dimensions are , in this order : <nl> window that moves across the base area . <nl> <nl> The ` window_strides ` argument specifies the stride of the convolutional window <nl> - in the spatial dimensions . For example , if the stride in a the first spatial <nl> + in the spatial dimensions . For example , if the stride in the first spatial <nl> dimension is 3 , then the window can only be placed at coordinates where the <nl> first spatial index is divisible by 3 . <nl> <nl> expand the rank of the lower - rank operand up to the rank of the higher - rank <nl> operand . ` broadcast_dimensions ` maps the dimensions of the lower - rank shape to <nl> the dimensions of the higher - rank shape . The unmapped dimensions of the expanded <nl> shape are filled with dimensions of size one . Degenerate - dimension broadcasting <nl> - then broadcasts the shapes along these degenerate dimension to equalize the <nl> + then broadcasts the shapes along these degenerate dimensions to equalize the <nl> shapes of both operands . The semantics are described in detail on the <nl> @ { $ broadcasting $ broadcasting page } . <nl> <nl> result2 = while ( condition , init = result1 ) { <nl> ` ` ` <nl> <nl> Nested tuple shapes are not supported . For an empty tuple shape , the Infeed <nl> - operation is effectively a nop and proceeds without reading any data from the <nl> + operation is effectively a no - op and proceeds without reading any data from the <nl> Infeed of the device . <nl> <nl> > Note : We plan to allow multiple Infeed operations without a total order , in <nl> dimension . <nl> <nl> ` PaddingConfig ` is a repeated field of ` PaddingConfigDimension ` , which contains <nl> three fields for each dimension : ` edge_padding_low ` , ` edge_padding_high ` , and <nl> - ` interior_padding ` . ` edge_padding_low ` and ` edge_padding_high ` specifies the <nl> + ` interior_padding ` . ` edge_padding_low ` and ` edge_padding_high ` specify the <nl> amount of padding added at the low - end ( next to index 0 ) and the high - end ( next <nl> to the highest index ) of each dimension respectively . The amount of edge padding <nl> can be negative - - the absolute value of negative padding indicates the number <nl> the amount of padding added between any two elements in each dimension . Interior <nl> padding occurs logically before edge padding , so in the case of negative edge <nl> padding elements are removed from the interior - padded operand . This operation is <nl> a no - op if the edge padding pairs are all ( 0 , 0 ) and the interior padding values <nl> - are all 0 . Figure below shows examples of different ` edge_padding ` and <nl> - ` interior_padding ` values for a two dimensional array . <nl> + are all 0 . The figure below shows examples of different ` edge_padding ` and <nl> + ` interior_padding ` values for a two - dimensional array . <nl> <nl> < div style = " width : 95 % ; margin : auto ; margin - bottom : 10px ; margin - top : 20px ; " > <nl> < img style = " width : 100 % " src = " https : / / www . tensorflow . org / images / ops_pad . png " > <nl> mmm a / tensorflow / docs_src / programmers_guide / saved_model . md <nl> ppp b / tensorflow / docs_src / programmers_guide / saved_model . md <nl> executing the computation graph later . For example : <nl> $ saved_model_cli show - - dir \ <nl> / tmp / saved_model_dir - - tag_set serve - - signature_def serving_default <nl> The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' x ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x : 0 <nl> + inputs [ ' x ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x : 0 <nl> The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' y ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y : 0 <nl> + outputs [ ' y ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y : 0 <nl> Method name is : tensorflow / serving / predict <nl> ` ` ` <nl> <nl> $ saved_model_cli show - - dir / tmp / saved_model_dir - - all <nl> MetaGraphDef with tag - set : ' serve ' contains the following SignatureDefs : <nl> <nl> signature_def [ ' classify_x2_to_y3 ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x2 : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' scores ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y3 : 0 <nl> - Method name is : tensorflow / serving / classify <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x2 : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' scores ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y3 : 0 <nl> + Method name is : tensorflow / serving / classify <nl> <nl> . . . <nl> <nl> signature_def [ ' serving_default ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' x ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' y ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y : 0 <nl> - Method name is : tensorflow / serving / predict <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' x ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' y ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y : 0 <nl> + Method name is : tensorflow / serving / predict <nl> ` ` ` <nl> <nl> <nl> mmm a / tensorflow / docs_src / programmers_guide / variables . md <nl> ppp b / tensorflow / docs_src / programmers_guide / variables . md <nl> them . For this reason TensorFlow provides * * collections * * , which are named lists <nl> of tensors or other objects , such as ` tf . Variable ` instances . <nl> <nl> By default every ` tf . Variable ` gets placed in the following two collections : <nl> + <nl> * ` tf . GraphKeys . GLOBAL_VARIABLES ` mmm variables that can be shared across <nl> - multiple devices , <nl> - * ` tf . GraphKeys . TRAINABLE_VARIABLES ` mmm variables for which TensorFlow will <nl> + multiple devices , <nl> + * ` tf . GraphKeys . TRAINABLE_VARIABLES ` mmm variables for which TensorFlow will <nl> calculate gradients . <nl> <nl> If you don ' t want a variable to be trainable , add it to the <nl> mmm a / tensorflow / examples / speech_commands / train . py <nl> ppp b / tensorflow / examples / speech_commands / train . py <nl> def main ( _ ) : <nl> ' - - window_size_ms ' , <nl> type = float , <nl> default = 30 . 0 , <nl> - help = ' How long each spectrogram timeslice is . ' , <nl> - ) <nl> + help = ' How long each spectrogram timeslice is . ' , ) <nl> parser . add_argument ( <nl> ' - - window_stride_ms ' , <nl> type = float , <nl> default = 10 . 0 , <nl> - help = ' How far to move in time between spectogram timeslices . ' , <nl> - ) <nl> + help = ' How far to move in time between spectogram timeslices . ' , ) <nl> parser . add_argument ( <nl> ' - - dct_coefficient_count ' , <nl> type = int , <nl> mmm a / tensorflow / python / framework / test_util . py <nl> ppp b / tensorflow / python / framework / test_util . py <nl> def assertDeviceEqual ( self , device1 , device2 , msg = None ) : <nl> " " " <nl> device1 = pydev . canonical_name ( device1 ) <nl> device2 = pydev . canonical_name ( device2 ) <nl> - self . assertEqual ( device1 , device2 , " Devices % s and % s are not equal . % s " % <nl> + self . assertEqual ( device1 , device2 , <nl> + " Devices % s and % s are not equal . % s " % <nl> ( device1 , device2 , msg ) ) <nl> <nl> # Fix Python 3 compatibility issues <nl> mmm a / tensorflow / python / keras / _impl / keras / layers / lstm_test . py <nl> ppp b / tensorflow / python / keras / _impl / keras / layers / lstm_test . py <nl> def test_static_shape_inference_LSTM ( self ) : <nl> units = 2 <nl> <nl> model = keras . models . Sequential ( ) <nl> - inputs = keras . layers . Dense ( <nl> - embedding_dim , input_shape = ( timesteps , embedding_dim ) ) <nl> + inputs = keras . layers . Dense ( embedding_dim , <nl> + input_shape = ( timesteps , embedding_dim ) ) <nl> model . add ( inputs ) <nl> layer = keras . layers . LSTM ( units , return_sequences = True ) <nl> model . add ( layer ) <nl> mmm a / tensorflow / python / kernel_tests / linalg / linear_operator_diag_test . py <nl> ppp b / tensorflow / python / kernel_tests / linalg / linear_operator_diag_test . py <nl> def test_broadcast_matmul_and_solve ( self ) : <nl> with self . test_session ( ) as sess : <nl> x = random_ops . random_normal ( shape = ( 2 , 2 , 3 , 4 ) ) <nl> <nl> - # This LinearOperatorDiag will be brodacast to ( 2 , 2 , 3 , 3 ) during solve <nl> + # This LinearOperatorDiag will be broadcast to ( 2 , 2 , 3 , 3 ) during solve <nl> # and matmul with ' x ' as the argument . <nl> diag = random_ops . random_uniform ( shape = ( 2 , 1 , 3 ) ) <nl> operator = linalg . LinearOperatorDiag ( diag , is_self_adjoint = True ) <nl> mmm a / tensorflow / python / kernel_tests / segment_reduction_ops_test . py <nl> ppp b / tensorflow / python / kernel_tests / segment_reduction_ops_test . py <nl> def _input ( self , input_shape , dtype = dtypes_lib . int32 ) : <nl> return constant_op . constant ( <nl> np_values , shape = input_shape , dtype = dtype ) , np_values <nl> <nl> - def _segmentReduce ( self , indices , x , op1 , op2 = None , num_segments = None ) : <nl> + def _segmentReduce ( self , indices , x , op1 , op2 = None , num_segments = None , <nl> + initial_value = 0 ) : <nl> if not x . size : <nl> return np . array ( [ ] ) <nl> indices = np . asarray ( indices ) <nl> def _segmentReduce ( self , indices , x , op1 , op2 = None , num_segments = None ) : <nl> else : <nl> output [ index ] = x_flat [ i ] <nl> # zero initialize values that are still uncalcuated . <nl> - # output = [ o if o is not None else np . zeros ( slice_shape ) for o in output ] <nl> - if not op1 = = np . max : <nl> - output = [ o if o is not None else np . zeros ( slice_shape ) for o in output ] <nl> - else : <nl> - zeroslice = np . zeros ( slice_shape ) <nl> - zeroslice . fill ( dtype . min ) <nl> - output = [ o if o is not None else zeroslice for o in output ] <nl> + initial_value_slice = np . ones ( slice_shape ) * initial_value <nl> + output = [ o if o is not None else initial_value_slice for o in output ] <nl> if op2 is not None : <nl> output = [ op2 ( o ) for o in output ] <nl> output = [ o . reshape ( slice_shape ) for o in output ] <nl> def _mean_cum_op ( self , x , y ) : <nl> def _mean_reduce_op ( self , x ) : <nl> return x [ 0 ] / x [ 1 ] if isinstance ( x , tuple ) else x <nl> <nl> + def _sqrt_n_reduce_op ( self , x ) : <nl> + return x [ 0 ] / np . sqrt ( x [ 1 ] ) if isinstance ( x , tuple ) else x <nl> + <nl> <nl> class SegmentReductionOpTest ( SegmentReductionHelper ) : <nl> <nl> def testGradient ( self ) : <nl> self . assertAllClose ( jacob_t , jacob_n ) <nl> <nl> <nl> - class UnsortedSegmentSumTest ( SegmentReductionHelper ) : <nl> + class UnsortedSegmentTest ( SegmentReductionHelper ) : <nl> + <nl> + def __init__ ( self , methodName = ' runTest ' ) : <nl> + # Each item is np_op1 , np_op2 , tf_op , initial_value functor <nl> + self . ops_list = [ ( np . add , None , <nl> + math_ops . unsorted_segment_sum , lambda t : 0 ) , <nl> + ( self . _mean_cum_op , self . _mean_reduce_op , <nl> + math_ops . unsorted_segment_mean , lambda t : 0 ) , <nl> + ( self . _mean_cum_op , self . _sqrt_n_reduce_op , <nl> + math_ops . unsorted_segment_sqrt_n , lambda t : 0 ) , <nl> + ( np . ndarray . __mul__ , None , <nl> + math_ops . unsorted_segment_prod , lambda t : 1 ) , <nl> + ( np . minimum , None , <nl> + math_ops . unsorted_segment_min , lambda t : t . max ) , <nl> + ( np . maximum , None , <nl> + math_ops . unsorted_segment_max , lambda t : t . min ) ] <nl> + <nl> + # A subset of ops has been enabled for complex numbers <nl> + self . complex_ops_list = [ ( np . add , None , <nl> + math_ops . unsorted_segment_sum , lambda t : 0 ) ] <nl> + self . differentiable_dtypes = [ dtypes_lib . float16 , dtypes_lib . float32 , <nl> + dtypes_lib . float64 ] <nl> + self . all_dtypes = ( self . differentiable_dtypes + <nl> + [ dtypes_lib . bfloat16 , <nl> + dtypes_lib . int64 , dtypes_lib . int32 , <nl> + dtypes_lib . complex64 , dtypes_lib . complex128 ] ) <nl> + super ( UnsortedSegmentTest , self ) . __init__ ( methodName = methodName ) <nl> <nl> def testValues ( self ) : <nl> - dtypes = [ <nl> - dtypes_lib . float32 , dtypes_lib . float64 , dtypes_lib . int64 , <nl> - dtypes_lib . int32 , dtypes_lib . complex64 , dtypes_lib . complex128 <nl> - ] <nl> indices_flat = np . array ( [ 0 , 4 , 0 , 8 , 3 , 8 , 4 , 7 , 7 , 3 ] ) <nl> num_segments = 12 <nl> for indices in indices_flat , indices_flat . reshape ( 5 , 2 ) : <nl> shape = indices . shape + ( 2 , ) <nl> - for dtype in dtypes : <nl> - with self . test_session ( use_gpu = True ) : <nl> - tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> - np_ans = self . _segmentReduce ( <nl> - indices , np_x , np . add , op2 = None , num_segments = num_segments ) <nl> - s = math_ops . unsorted_segment_sum ( <nl> - data = tf_x , segment_ids = indices , num_segments = num_segments ) <nl> - tf_ans = s . eval ( ) <nl> - self . assertAllClose ( np_ans , tf_ans ) <nl> - self . assertShapeEqual ( np_ans , s ) <nl> + for dtype in self . all_dtypes : <nl> + ops_list = self . complex_ops_list if dtype . is_complex else self . ops_list <nl> + tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> + for use_gpu in [ True , False ] : <nl> + with self . test_session ( use_gpu = True ) : <nl> + for np_op1 , np_op2 , tf_op , init_op in ops_list : <nl> + # sqrt_n doesn ' t support integers <nl> + if ( np_op2 = = self . _sqrt_n_reduce_op and dtype . is_integer ) : <nl> + continue <nl> + # todo ( philjd ) : enable this test once real_div supports bfloat16 <nl> + if ( np_op2 in [ self . _sqrt_n_reduce_op , self . _mean_reduce_op ] and <nl> + dtype = = dtypes_lib . bfloat16 ) : <nl> + continue <nl> + np_ans = self . _segmentReduce ( <nl> + indices , np_x , np_op1 , np_op2 , num_segments = num_segments , <nl> + initial_value = init_op ( dtype ) ) <nl> + s = tf_op ( tf_x , segment_ids = indices , num_segments = num_segments ) <nl> + tf_ans = s . eval ( ) <nl> + if dtype is dtypes_lib . bfloat16 : <nl> + tf_ans = tf_ans . astype ( np . float32 ) <nl> + self . assertAllClose ( np_ans , tf_ans ) <nl> + self . assertShapeEqual ( np_ans , s ) <nl> <nl> def testNumSegmentsTypes ( self ) : <nl> dtypes = [ dtypes_lib . int32 , dtypes_lib . int64 ] <nl> def testNumSegmentsTypes ( self ) : <nl> self . assertAllClose ( np_ans , tf_ans ) <nl> self . assertShapeEqual ( np_ans , s ) <nl> <nl> - def testGradientSegmentSum ( self ) : <nl> + def testGradients ( self ) : <nl> num_cols = 2 <nl> - indices_flat = np . array ( [ 0 , 4 , 0 , 8 , 3 , 8 , 4 , 7 , 7 , 3 ] ) <nl> + indices_flat = np . array ( [ 0 , 4 , 0 , - 1 , 3 , - 1 , 4 , 7 , 7 , 3 ] ) <nl> num_segments = max ( indices_flat ) + 3 <nl> - for dtype in [ dtypes_lib . float32 , dtypes_lib . float64 , dtypes_lib . complex64 , <nl> - dtypes_lib . complex128 ] : <nl> + for dtype in self . differentiable_dtypes : <nl> + ops_list = self . complex_ops_list if dtype . is_complex else self . ops_list <nl> for indices in indices_flat , indices_flat . reshape ( 5 , 2 ) : <nl> shape = indices . shape + ( num_cols , ) <nl> - with self . test_session ( use_gpu = True ) : <nl> - tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> - s = math_ops . unsorted_segment_sum ( <nl> - data = tf_x , segment_ids = indices , num_segments = num_segments ) <nl> + # test CPU and GPU as tf . gather behaves differently on each device <nl> + for use_gpu in [ False , True ] : <nl> + with self . test_session ( use_gpu = use_gpu ) : <nl> + for _ , _ , tf_op , _ in ops_list : <nl> + tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> + s = tf_op ( tf_x , indices , num_segments ) <nl> + jacob_t , jacob_n = gradient_checker . compute_gradient ( <nl> + tf_x , <nl> + shape , <nl> + s , [ num_segments , num_cols ] , <nl> + x_init_value = np_x , <nl> + delta = 1 ) <nl> + self . assertAllClose ( jacob_t , jacob_n ) <nl> + <nl> + def testProdGrad ( self ) : <nl> + # additional test for the prod gradient to ensure correct handling of zeros <nl> + values = np . array ( [ 0 , 0 , 1 , 0 , 2 , 2 , 3 , 3 , 3 ] , dtype = np . float32 ) <nl> + indices = np . array ( [ 0 , 0 , 0 , 1 , 1 , 1 , 2 , 2 , 2 ] , dtype = np . int32 ) <nl> + indices_neg = np . array ( [ - 1 , 0 , 0 , - 1 , 1 , 1 , - 1 , 2 , 2 ] , dtype = np . int32 ) <nl> + values_tf = constant_op . constant ( values ) <nl> + # ground truth partial derivatives <nl> + gradients_indices = np . zeros ( ( 9 , 3 ) , dtype = np . float32 ) <nl> + gradients_indices_neg = np . zeros ( ( 9 , 3 ) , dtype = np . float32 ) <nl> + # the derivative w . r . t . to the other segments is zero , so here we only <nl> + # explicitly set the grad values for the corresponding segment <nl> + gradients_indices [ range ( 9 ) , indices ] = [ 0 , 0 , 0 , 4 , 0 , 0 , 9 , 9 , 9 ] <nl> + gradients_indices_neg [ range ( 9 ) , indices_neg ] = [ 0 , 1 , 0 , 0 , 2 , 2 , 0 , 3 , 3 ] <nl> + for use_gpu in [ False , True ] : <nl> + with self . test_session ( use_gpu = use_gpu ) : <nl> + for ind , grad_gt in [ ( indices , gradients_indices ) , <nl> + ( indices_neg , gradients_indices_neg ) ] : <nl> + s = math_ops . unsorted_segment_prod ( values_tf , <nl> + constant_op . constant ( ind ) , 3 ) <nl> jacob_t , jacob_n = gradient_checker . compute_gradient ( <nl> - tf_x , <nl> - shape , <nl> - s , [ num_segments , num_cols ] , <nl> - x_init_value = np_x , <nl> - delta = 1 ) <nl> - self . assertAllClose ( jacob_t , jacob_n ) <nl> + values_tf , ( 9 , ) , s , ( 3 , ) , x_init_value = values , delta = 1 ) <nl> + self . assertAllClose ( jacob_t , jacob_n ) <nl> + self . assertAllClose ( jacob_t , grad_gt ) <nl> <nl> def testGradientMatchesSegmentSum ( self ) : <nl> # Strategy : compute the gradient for UnsortedSegmentSum and SegmentSum <nl> def testGradientMatchesSegmentSum ( self ) : <nl> num_cols = 2 <nl> shape = [ n , num_cols ] <nl> num_segments = max ( indices ) + 1 <nl> - for dtype in [ dtypes_lib . float32 , dtypes_lib . float64 , dtypes_lib . complex64 , <nl> - dtypes_lib . complex128 ] : <nl> + for dtype in self . differentiable_dtypes : <nl> with self . test_session ( use_gpu = True ) : <nl> tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> # Results from UnsortedSegmentSum <nl> def testBadIndices ( self ) : <nl> unsorted . eval ( ) <nl> <nl> def testEmptySecondDimension ( self ) : <nl> - dtypes = [ <nl> - np . float32 , np . float64 , np . int64 , np . int32 , np . complex64 , np . complex128 <nl> - ] <nl> + dtypes = [ np . float16 , np . float32 , np . float64 , np . int64 , np . int32 , <nl> + np . complex64 , np . complex128 ] <nl> with self . test_session ( use_gpu = True ) : <nl> for dtype in dtypes : <nl> for itype in ( np . int32 , np . int64 ) : <nl> def testEmptySecondDimension ( self ) : <nl> unsorted = math_ops . unsorted_segment_sum ( data , segment_ids , 2 ) <nl> self . assertAllEqual ( unsorted . eval ( ) , np . zeros ( ( 2 , 0 ) , dtype = dtype ) ) <nl> <nl> - def testGradientSegmentMax ( self ) : <nl> - num_cols = 2 <nl> - indices_flat = np . array ( [ 0 , 4 , 0 , 8 , 3 , 8 , 4 , 7 , 7 , 3 ] ) <nl> - num_segments = max ( indices_flat ) + 3 <nl> - for indices in indices_flat , indices_flat . reshape ( 5 , 2 ) : <nl> - shape = indices . shape + ( num_cols , ) <nl> - with self . test_session ( use_gpu = True ) : <nl> - tf_x , np_x = self . _input ( shape , dtype = dtypes_lib . float64 ) <nl> - s = math_ops . unsorted_segment_max ( <nl> - data = tf_x , segment_ids = indices , num_segments = num_segments ) <nl> - jacob_t , jacob_n = gradient_checker . compute_gradient ( <nl> - tf_x , <nl> - shape , <nl> - s , <nl> - [ num_segments , num_cols ] , <nl> - x_init_value = np_x . astype ( np . double ) , delta = 1 ) <nl> - self . assertAllClose ( jacob_t , jacob_n ) <nl> - <nl> def testDropNegatives ( self ) : <nl> # Note : the test is done by replacing segment_ids with 8 to - 1 <nl> # for index and replace values generated by numpy with 0 . <nl> - dtypes = [ <nl> - dtypes_lib . float32 , dtypes_lib . float64 , dtypes_lib . int64 , <nl> - dtypes_lib . int32 , dtypes_lib . complex64 , dtypes_lib . complex128 <nl> - ] <nl> indices_flat = np . array ( [ 0 , 4 , 0 , 8 , 3 , 8 , 4 , 7 , 7 , 3 ] ) <nl> num_segments = 12 <nl> for indices in indices_flat , indices_flat . reshape ( 5 , 2 ) : <nl> shape = indices . shape + ( 2 , ) <nl> - for dtype in dtypes : <nl> + for dtype in self . all_dtypes : <nl> with self . test_session ( use_gpu = True ) : <nl> tf_x , np_x = self . _input ( shape , dtype = dtype ) <nl> np_ans = self . _segmentReduce ( <nl> mmm a / tensorflow / python / kernel_tests / unique_op_test . py <nl> ppp b / tensorflow / python / kernel_tests / unique_op_test . py <nl> def testString ( self ) : <nl> v = [ 1 if x [ i ] = = value . decode ( ' ascii ' ) else 0 for i in range ( 7000 ) ] <nl> self . assertEqual ( count , sum ( v ) ) <nl> <nl> + def testInt32Axis ( self ) : <nl> + for dtype in [ np . int32 , np . int64 ] : <nl> + x = np . array ( [ [ 1 , 0 , 0 ] , [ 1 , 0 , 0 ] , [ 2 , 0 , 0 ] ] ) <nl> + with self . test_session ( ) as sess : <nl> + y0 , idx0 , count0 = gen_array_ops . unique_with_counts_v2 ( <nl> + x , axis = np . array ( [ 0 ] , dtype ) ) <nl> + tf_y0 , tf_idx0 , tf_count0 = sess . run ( [ y0 , idx0 , count0 ] ) <nl> + y1 , idx1 , count1 = gen_array_ops . unique_with_counts_v2 ( <nl> + x , axis = np . array ( [ 1 ] , dtype ) ) <nl> + tf_y1 , tf_idx1 , tf_count1 = sess . run ( [ y1 , idx1 , count1 ] ) <nl> + self . assertAllEqual ( tf_y0 , np . array ( [ [ 1 , 0 , 0 ] , [ 2 , 0 , 0 ] ] ) ) <nl> + self . assertAllEqual ( tf_idx0 , np . array ( [ 0 , 0 , 1 ] ) ) <nl> + self . assertAllEqual ( tf_count0 , np . array ( [ 2 , 1 ] ) ) <nl> + self . assertAllEqual ( tf_y1 , np . array ( [ [ 1 , 0 ] , [ 1 , 0 ] , [ 2 , 0 ] ] ) ) <nl> + self . assertAllEqual ( tf_idx1 , np . array ( [ 0 , 1 , 1 ] ) ) <nl> + self . assertAllEqual ( tf_count1 , np . array ( [ 1 , 2 ] ) ) <nl> + <nl> + def testInt32V2 ( self ) : <nl> + # This test is only temporary , once V2 is used <nl> + # by default , the axis will be wrapped to allow ` axis = None ` . <nl> + x = np . random . randint ( 2 , high = 10 , size = 7000 ) <nl> + with self . test_session ( ) as sess : <nl> + y , idx , count = gen_array_ops . unique_with_counts_v2 ( <nl> + x , axis = np . array ( [ ] , np . int32 ) ) <nl> + tf_y , tf_idx , tf_count = sess . run ( [ y , idx , count ] ) <nl> + <nl> + self . assertEqual ( len ( x ) , len ( tf_idx ) ) <nl> + self . assertEqual ( len ( tf_y ) , len ( np . unique ( x ) ) ) <nl> + for i in range ( len ( x ) ) : <nl> + self . assertEqual ( x [ i ] , tf_y [ tf_idx [ i ] ] ) <nl> + for value , count in zip ( tf_y , tf_count ) : <nl> + self . assertEqual ( count , np . sum ( x = = value ) ) <nl> + <nl> <nl> if __name__ = = ' __main__ ' : <nl> test . main ( ) <nl> mmm a / tensorflow / python / ops / array_ops . py <nl> ppp b / tensorflow / python / ops / array_ops . py <nl> def unique ( x , out_idx = dtypes . int32 , name = None ) : <nl> unique . __doc__ = gen_array_ops . unique . __doc__ <nl> <nl> <nl> + @ tf_export ( " unique_with_counts " ) <nl> + def unique_with_counts ( x , out_idx = dtypes . int32 , name = None ) : <nl> + # TODO ( yongtang ) : switch to v2 once API deprecation <nl> + # period ( 3 weeks ) pass . <nl> + # TODO ( yongtang ) : The documentation should also <nl> + # be updated when switch to v2 . <nl> + return gen_array_ops . unique_with_counts ( x , out_idx , name ) <nl> + <nl> + <nl> + unique_with_counts . __doc__ = gen_array_ops . unique_with_counts . __doc__ <nl> + <nl> + <nl> @ tf_export ( " split " ) <nl> def split ( value , num_or_size_splits , axis = 0 , num = None , name = " split " ) : <nl> " " " Splits a tensor into sub tensors . <nl> mmm a / tensorflow / python / ops / bitwise_ops_test . py <nl> ppp b / tensorflow / python / ops / bitwise_ops_test . py <nl> def count_bits ( x ) : <nl> self . assertAllEqual ( truth , popcnt_result ) <nl> <nl> def testInvertOp ( self ) : <nl> - dtype_list = [ <nl> - dtypes . int8 , dtypes . int16 , dtypes . int32 , dtypes . int64 , dtypes . uint8 , <nl> - dtypes . uint16 , dtypes . uint32 , dtypes . uint64 <nl> - ] <nl> + dtype_list = [ dtypes . int8 , dtypes . int16 , dtypes . int32 , dtypes . int64 , <nl> + dtypes . uint8 , dtypes . uint16 , dtypes . uint32 , dtypes . uint64 ] <nl> inputs = [ 0 , 5 , 3 , 14 ] <nl> with self . test_session ( use_gpu = True ) as sess : <nl> for dtype in dtype_list : <nl> mmm a / tensorflow / python / ops / check_ops . py <nl> ppp b / tensorflow / python / ops / check_ops . py <nl> def assert_equal ( x , y , data = None , summarize = None , message = None , name = None ) : <nl> @ compatibility { eager } returns None <nl> <nl> Raises : <nl> - InvalidArgumentError if the check can be performed immediately and <nl> - ` x = = y ` is False . The check can be performed immediately during <nl> - eager execution or if ` x ` and ` y ` are statically known . <nl> + InvalidArgumentError : if the check can be performed immediately and <nl> + ` x = = y ` is False . The check can be performed immediately during eager <nl> + execution or if ` x ` and ` y ` are statically known . <nl> " " " <nl> message = message or ' ' <nl> with ops . name_scope ( name , ' assert_equal ' , [ x , y , data ] ) : <nl> mmm a / tensorflow / python / ops / confusion_matrix . py <nl> ppp b / tensorflow / python / ops / confusion_matrix . py <nl> def confusion_matrix ( labels , predictions , num_classes = None , dtype = dtypes . int32 , <nl> name = None , weights = None ) : <nl> " " " Computes the confusion matrix from predictions and labels . <nl> <nl> - Calculate the Confusion Matrix for a pair of prediction and <nl> - label 1 - D int arrays . <nl> - <nl> The matrix columns represent the prediction labels and the rows represent the <nl> real labels . The confusion matrix is always a 2 - D array of shape ` [ n , n ] ` , <nl> where ` n ` is the number of valid labels for a given classification task . Both <nl> prediction and labels must be 1 - D arrays of the same shape in order for this <nl> function to work . <nl> <nl> - If ` num_classes ` is None , then ` num_classes ` will be set to the one plus <nl> - the maximum value in either predictions or labels . <nl> - Class labels are expected to start at 0 . E . g . , if ` num_classes ` was <nl> - three , then the possible labels would be ` [ 0 , 1 , 2 ] ` . <nl> + If ` num_classes ` is ` None ` , then ` num_classes ` will be set to one plus the <nl> + maximum value in either predictions or labels . Class labels are expected to <nl> + start at 0 . For example , if ` num_classes ` is 3 , then the possible labels <nl> + would be ` [ 0 , 1 , 2 ] ` . <nl> <nl> If ` weights ` is not ` None ` , then each prediction contributes its <nl> corresponding weight to the total value of the confusion matrix cell . <nl> def confusion_matrix ( labels , predictions , num_classes = None , dtype = dtypes . int32 , <nl> weights : An optional ` Tensor ` whose shape matches ` predictions ` . <nl> <nl> Returns : <nl> - A k X k matrix representing the confusion matrix , where k is the number of <nl> - possible labels in the classification task . <nl> + A ` Tensor ` of type ` dtype ` with shape ` [ n , n ] ` representing the confusion <nl> + matrix , where ` n ` is the number of possible labels in the classification <nl> + task . <nl> <nl> Raises : <nl> ValueError : If both predictions and labels are not 1 - D vectors and have <nl> def confusion_matrix ( labels , predictions , num_classes = None , dtype = dtypes . int32 , <nl> weights = math_ops . cast ( weights , dtype ) <nl> <nl> shape = array_ops . stack ( [ num_classes , num_classes ] ) <nl> - indices = array_ops . transpose ( array_ops . stack ( [ labels , predictions ] ) ) <nl> + indices = array_ops . stack ( [ labels , predictions ] , axis = 1 ) <nl> values = ( array_ops . ones_like ( predictions , dtype ) <nl> if weights is None else weights ) <nl> cm_sparse = sparse_tensor . SparseTensor ( <nl> mmm a / tensorflow / python / ops / distributions / special_math . py <nl> ppp b / tensorflow / python / ops / distributions / special_math . py <nl> def _create_polynomial ( var , coeffs ) : <nl> <nl> # Compute x for p < = exp ( - 2 ) : x = z - log ( z ) / z - ( 1 / z ) P ( 1 / z ) / Q ( 1 / z ) , <nl> # where z = sqrt ( - 2 . * log ( p ) ) , and P / Q are chosen between two different <nl> - # arrays based on wether p < exp ( - 32 ) . <nl> + # arrays based on whether p < exp ( - 32 ) . <nl> z = math_ops . sqrt ( - 2 . * math_ops . log ( sanitized_mcp ) ) <nl> first_term = z - math_ops . log ( z ) / z <nl> second_term_small_p = ( _create_polynomial ( 1 . / z , p2 ) <nl> mmm a / tensorflow / python / ops / hidden_ops . txt <nl> ppp b / tensorflow / python / ops / hidden_ops . txt <nl> TileGrad # Exported through array_grad instead of array_ops . <nl> ZerosLike # TODO ( josh11b ) : Use this instead of the Python version . <nl> Unique <nl> UniqueV2 <nl> + UniqueWithCounts <nl> + UniqueWithCountsV2 <nl> Unpack <nl> <nl> # candidate_sampling_ops <nl> mmm a / tensorflow / python / ops / image_ops_impl . py <nl> ppp b / tensorflow / python / ops / image_ops_impl . py <nl> def _rot90 ( ) : <nl> <nl> def _rot180 ( ) : <nl> return array_ops . reverse_v2 ( images , [ 1 , 2 ] ) <nl> - <nl> def _rot270 ( ) : <nl> return array_ops . reverse_v2 ( array_ops . transpose ( images , [ 0 , 2 , 1 , 3 ] ) , [ 2 ] ) <nl> <nl> def _rot270 ( ) : <nl> result . set_shape ( [ shape [ 0 ] , None , None , shape [ 3 ] ] ) <nl> return result <nl> <nl> - <nl> @ tf_export ( ' image . transpose_image ' ) <nl> def transpose_image ( image ) : <nl> " " " Transpose image ( s ) by swapping the height and width dimension . <nl> mmm a / tensorflow / python / ops / image_ops_test . py <nl> ppp b / tensorflow / python / ops / image_ops_test . py <nl> def testPartialShapes ( self ) : <nl> with self . assertRaisesRegexp ( ValueError , " must be three - dimensional " ) : <nl> op ( p_wrong_rank ) <nl> <nl> + <nl> def testRot90GroupOrder ( self ) : <nl> image = np . arange ( 24 , dtype = np . uint8 ) . reshape ( [ 2 , 4 , 3 ] ) <nl> with self . test_session ( use_gpu = True ) : <nl> def testRot90NumpyEquivalenceWithBatch ( self ) : <nl> y_np = np . rot90 ( image , k = k , axes = ( 1 , 2 ) ) <nl> self . assertAllEqual ( y_np , y_tf . eval ( { k_placeholder : k } ) ) <nl> <nl> - <nl> class RandomFlipTest ( test_util . TensorFlowTestCase ) : <nl> <nl> def testRandomLeftRight ( self ) : <nl> mmm a / tensorflow / python / ops / linalg / linear_operator_diag . py <nl> ppp b / tensorflow / python / ops / linalg / linear_operator_diag . py <nl> class LinearOperatorDiag ( linear_operator . LinearOperator ) : <nl> operator = LinearOperatorDiag ( diag ) <nl> <nl> # Create a shape [ 2 , 1 , 4 , 2 ] vector . Note that this shape is compatible <nl> - # since the batch dimensions , [ 2 , 1 ] , are brodcast to <nl> + # since the batch dimensions , [ 2 , 1 ] , are broadcast to <nl> # operator . batch_shape = [ 2 , 3 ] . <nl> y = tf . random_normal ( shape = [ 2 , 1 , 4 , 2 ] ) <nl> x = operator . solve ( y ) <nl> mmm a / tensorflow / python / ops / losses / losses_impl . py <nl> ppp b / tensorflow / python / ops / losses / losses_impl . py <nl> def sigmoid_cross_entropy ( <nl> <nl> Args : <nl> multi_class_labels : ` [ batch_size , num_classes ] ` target integer labels in <nl> - ` ( 0 , 1 ) ` . <nl> + ` { 0 , 1 } ` . <nl> logits : Float ` [ batch_size , num_classes ] ` logits outputs of the network . <nl> weights : Optional ` Tensor ` whose rank is either 0 , or the same rank as <nl> ` labels ` , and must be broadcastable to ` labels ` ( i . e . , all dimensions must <nl> mmm a / tensorflow / python / ops / math_grad . py <nl> ppp b / tensorflow / python / ops / math_grad . py <nl> def _SparseSegmentSqrtNWithNumSegmentsGrad ( op , grad ) : <nl> dim0 ) , None , None , None ) <nl> <nl> <nl> - def _SegmentMinOrMaxGrad ( op , grad , is_sorted ) : <nl> - " " " Gradient for SegmentMin and ( unsorted ) SegmentMax . <nl> - <nl> - They share similar code . <nl> - " " " <nl> - zeros = array_ops . zeros ( <nl> - array_ops . shape ( op . inputs [ 0 ] ) , dtype = op . inputs [ 0 ] . dtype ) <nl> - <nl> + def _SegmentMinOrMaxGrad ( op , grad ) : <nl> + " " " Gradient for SegmentMin and SegmentMax . " " " <nl> + zeros = array_ops . zeros_like ( op . inputs [ 0 ] , dtype = op . inputs [ 0 ] . dtype ) <nl> # Get the number of selected ( minimum or maximum ) elements in each segment . <nl> gathered_outputs = array_ops . gather ( op . outputs [ 0 ] , op . inputs [ 1 ] ) <nl> is_selected = math_ops . equal ( op . inputs [ 0 ] , gathered_outputs ) <nl> - if is_sorted : <nl> - num_selected = math_ops . segment_sum ( <nl> - math_ops . cast ( is_selected , grad . dtype ) , op . inputs [ 1 ] ) <nl> - else : <nl> - num_selected = math_ops . unsorted_segment_sum ( <nl> - math_ops . cast ( is_selected , grad . dtype ) , op . inputs [ 1 ] , op . inputs [ 2 ] ) <nl> - <nl> + num_selected = math_ops . segment_sum ( math_ops . cast ( is_selected , grad . dtype ) , <nl> + op . inputs [ 1 ] ) <nl> # Compute the gradient for each segment . The gradient for the ith segment is <nl> # divided evenly among the selected elements in that segment . <nl> weighted_grads = math_ops . div ( grad , num_selected ) <nl> gathered_grads = array_ops . gather ( weighted_grads , op . inputs [ 1 ] ) <nl> - <nl> - if is_sorted : <nl> - return array_ops . where ( is_selected , gathered_grads , zeros ) , None <nl> - else : <nl> - return array_ops . where ( is_selected , gathered_grads , zeros ) , None , None <nl> + return array_ops . where ( is_selected , gathered_grads , zeros ) , None <nl> <nl> <nl> @ ops . RegisterGradient ( " SegmentMin " ) <nl> def _SegmentMinGrad ( op , grad ) : <nl> " " " Gradient for SegmentMin . " " " <nl> - return _SegmentMinOrMaxGrad ( op , grad , True ) <nl> + return _SegmentMinOrMaxGrad ( op , grad ) <nl> <nl> <nl> @ ops . RegisterGradient ( " SegmentMax " ) <nl> def _SegmentMaxGrad ( op , grad ) : <nl> " " " Gradient for SegmentMax . " " " <nl> - return _SegmentMinOrMaxGrad ( op , grad , True ) <nl> + return _SegmentMinOrMaxGrad ( op , grad ) <nl> + <nl> + <nl> + def _GatherDropNegatives ( params , ids , zero_clipped_indices = None , <nl> + is_positive = None ) : <nl> + " " " Helper function for unsorted segment ops . Gathers params for <nl> + positive segment ids and gathers 0 for inputs with negative segment id . <nl> + Also returns the clipped indices and a boolean mask with the same shape <nl> + as ids where a positive id is masked as true . With this , the latter two <nl> + can be passed as arguments to this function to reuse them . <nl> + " " " <nl> + if zero_clipped_indices is None : <nl> + zero_clipped_indices = math_ops . maximum ( ids , array_ops . zeros_like ( ids ) ) <nl> + gathered = array_ops . gather ( params , zero_clipped_indices ) <nl> + if is_positive is None : <nl> + is_positive = math_ops . greater_equal ( ids , 0 ) <nl> + # tf . where ( condition , x , y ) requires condition to have the same shape as x <nl> + # and y . <nl> + # todo ( philjd ) : remove this if tf . where supports broadcasting ( # 9284 ) <nl> + for _ in range ( gathered . shape . ndims - is_positive . shape . ndims ) : <nl> + is_positive = array_ops . expand_dims ( is_positive , - 1 ) <nl> + is_positive = ( is_positive & <nl> + array_ops . ones_like ( gathered , dtype = dtypes . bool ) ) <nl> + # replace gathered params of negative indices with 0 <nl> + zero_slice = array_ops . zeros_like ( gathered ) <nl> + return ( array_ops . where ( is_positive , gathered , zero_slice ) , <nl> + zero_clipped_indices , is_positive ) <nl> + <nl> + <nl> + def _UnsortedSegmentMinOrMaxGrad ( op , grad ) : <nl> + " " " Gradient for UnsortedSegmentMin and UnsortedSegmentMax . " " " <nl> + # Get the number of selected ( minimum or maximum ) elements in each segment . <nl> + gathered_outputs , zero_clipped_indices , is_positive = \ <nl> + _GatherDropNegatives ( op . outputs [ 0 ] , op . inputs [ 1 ] ) <nl> + is_selected = math_ops . equal ( op . inputs [ 0 ] , gathered_outputs ) <nl> + is_selected = math_ops . logical_and ( is_selected , is_positive ) <nl> + num_selected = math_ops . unsorted_segment_sum ( <nl> + math_ops . cast ( is_selected , grad . dtype ) , op . inputs [ 1 ] , op . inputs [ 2 ] ) <nl> + # Compute the gradient for each segment . The gradient for the ith segment is <nl> + # divided evenly among the selected elements in that segment . <nl> + weighted_grads = math_ops . div ( grad , num_selected ) <nl> + gathered_grads , _ , _ = _GatherDropNegatives ( weighted_grads , None , <nl> + zero_clipped_indices , <nl> + is_positive ) <nl> + zeros = array_ops . zeros_like ( gathered_grads ) <nl> + return array_ops . where ( is_selected , gathered_grads , zeros ) , None , None <nl> <nl> <nl> @ ops . RegisterGradient ( " UnsortedSegmentSum " ) <nl> def _UnsortedSegmentSumGrad ( op , grad ) : <nl> - " " " Gradient for SegmentSum . " " " <nl> - return array_ops . gather ( grad , op . inputs [ 1 ] ) , None , None <nl> + " " " Gradient for UnsortedSegmentSum . " " " <nl> + return _GatherDropNegatives ( grad , op . inputs [ 1 ] ) [ 0 ] , None , None <nl> <nl> <nl> @ ops . RegisterGradient ( " UnsortedSegmentMax " ) <nl> def _UnsortedSegmentMaxGrad ( op , grad ) : <nl> - return _SegmentMinOrMaxGrad ( op , grad , False ) <nl> + " " " Gradient for UnsortedSegmentMax . " " " <nl> + return _UnsortedSegmentMinOrMaxGrad ( op , grad ) <nl> + <nl> + <nl> + @ ops . RegisterGradient ( " UnsortedSegmentMin " ) <nl> + def _UnsortedSegmentMinGrad ( op , grad ) : <nl> + " " " Gradient for UnsortedSegmentMin . " " " <nl> + return _UnsortedSegmentMinOrMaxGrad ( op , grad ) <nl> + <nl> + <nl> + @ ops . RegisterGradient ( " UnsortedSegmentProd " ) <nl> + def _UnsortedSegmentProdGrad ( op , grad ) : <nl> + " " " Gradient for UnsortedSegmentProd . <nl> + The gradient can be expressed for each segment by dividing the segment ' s <nl> + product by each element of the segment input tensor , but this approach can ' t <nl> + deal with zeros in the input . <nl> + Unlike reduce_prod we can ' t use cumsum here as individual segments may have <nl> + a different number of elements . Therefore we consider three cases : <nl> + 1 ) A segment input contains no zeros and we can safely divide by the input <nl> + tensor . <nl> + 2 ) A segment contains exactly one zero . Then the gradient of each input of <nl> + the segment is zero except for the 0 - input , there the gradient is <nl> + the product of the remaining segment entries . <nl> + 3 ) A segment contains at least two zeros . The gradient is zero for all <nl> + segment inputs . <nl> + " " " <nl> + # Note that unsorted_segment_sum will filter out the negative indices , <nl> + # so we don ' t need to do a logical_and with is_positive here <nl> + is_zero = math_ops . equal ( op . inputs [ 0 ] , 0 ) <nl> + num_zeros = gen_math_ops . unsorted_segment_sum ( <nl> + math_ops . cast ( is_zero , dtype = dtypes . int32 ) , op . inputs [ 1 ] , op . inputs [ 2 ] ) <nl> + # handle case 3 and set the gradient to 0 for segments with more than one <nl> + # 0 as input <nl> + grad = array_ops . where ( math_ops . greater ( num_zeros , 1 ) , <nl> + array_ops . zeros_like ( grad ) , grad ) <nl> + # replace all zeros with ones and compute the unsorted_segment_prod <nl> + non_zero_data = array_ops . where ( is_zero , array_ops . ones_like ( op . inputs [ 0 ] ) , <nl> + op . inputs [ 0 ] ) <nl> + non_zero_prod = gen_math_ops . unsorted_segment_prod ( <nl> + non_zero_data , op . inputs [ 1 ] , op . inputs [ 2 ] ) <nl> + # clip the indices for gather to be positive <nl> + zero_clipped_indices = math_ops . maximum ( op . inputs [ 1 ] , <nl> + array_ops . zeros_like ( op . inputs [ 1 ] ) ) <nl> + gathered_prod = array_ops . gather ( op . outputs [ 0 ] , zero_clipped_indices ) <nl> + gathered_non_zero_prod = array_ops . gather ( non_zero_prod , <nl> + zero_clipped_indices ) <nl> + prod_divided_by_el = gathered_prod / op . inputs [ 0 ] # May contain nan / inf . <nl> + # Now fetch the individual results for segments containing 0 and those that <nl> + # don ' t . is_zero will also fetch results for entries with negative index <nl> + # but the following gather_drop_negatives sets the corresponding entry in <nl> + # grad to 0 for these <nl> + partial_derivative = array_ops . where ( is_zero , gathered_non_zero_prod , <nl> + prod_divided_by_el ) <nl> + gathered_grad = _GatherDropNegatives ( grad , op . inputs [ 1 ] , <nl> + zero_clipped_indices ) [ 0 ] <nl> + return gathered_grad * partial_derivative , None , None <nl> <nl> <nl> @ ops . RegisterGradient ( " Abs " ) <nl> mmm a / tensorflow / python / ops / math_ops . py <nl> ppp b / tensorflow / python / ops / math_ops . py <nl> <nl> @ @ segment_mean <nl> @ @ unsorted_segment_sum <nl> @ @ unsorted_segment_max <nl> + @ @ unsorted_segment_min <nl> + @ @ unsorted_segment_prod <nl> + @ @ unsorted_segment_sqrt_n <nl> @ @ sparse_segment_sum <nl> @ @ sparse_segment_mean <nl> @ @ sparse_segment_sqrt_n <nl> def to_bfloat16 ( x , name = " ToBFloat16 " ) : <nl> return cast ( x , dtypes . bfloat16 , name = name ) <nl> <nl> <nl> + @ tf_export ( " to_complex64 " ) <nl> + def to_complex64 ( x , name = " ToComplex64 " ) : <nl> + " " " Casts a tensor to type ` complex64 ` . <nl> + <nl> + Args : <nl> + x : A ` Tensor ` or ` SparseTensor ` . <nl> + name : A name for the operation ( optional ) . <nl> + <nl> + Returns : <nl> + A ` Tensor ` or ` SparseTensor ` with same shape as ` x ` with type ` complex64 ` . <nl> + <nl> + Raises : <nl> + TypeError : If ` x ` cannot be cast to the ` complex64 ` . <nl> + " " " <nl> + return cast ( x , dtypes . complex64 , name = name ) <nl> + <nl> + <nl> + @ tf_export ( " to_complex128 " ) <nl> + def to_complex128 ( x , name = " ToComplex128 " ) : <nl> + " " " Casts a tensor to type ` complex128 ` . <nl> + <nl> + Args : <nl> + x : A ` Tensor ` or ` SparseTensor ` . <nl> + name : A name for the operation ( optional ) . <nl> + <nl> + Returns : <nl> + A ` Tensor ` or ` SparseTensor ` with same shape as ` x ` with type ` complex128 ` . <nl> + <nl> + Raises : <nl> + TypeError : If ` x ` cannot be cast to the ` complex128 ` . <nl> + " " " <nl> + return cast ( x , dtypes . complex128 , name = name ) <nl> + <nl> + <nl> ops . Tensor . _override_operator ( " __neg__ " , gen_math_ops . neg ) <nl> ops . Tensor . _override_operator ( " __abs__ " , abs ) <nl> # __invert__ corresponds to the ~ operator . Here we follow the numpy convention <nl> def reduced_shape ( input_shape , axes ) : <nl> ] ) # [ 1 , 1 ] <nl> <nl> <nl> + def _unsorted_segment_N ( data , segment_ids , num_segments ) : <nl> + " " " Helper function for unsorted_segment_mean / _sqrtN . Computes the number <nl> + of segment entries with 0 - entries set to 1 to allow division by N . <nl> + " " " <nl> + # bincount doesn ' t support negative indices so we use unsorted_segment_sum <nl> + ones_tensor = array_ops . ones ( segment_ids . shape , dtype = data . dtype ) <nl> + N = gen_math_ops . unsorted_segment_sum ( ones_tensor , segment_ids , num_segments ) <nl> + # add dimensions for all non - reduced axes <nl> + ndims_output = data . shape . ndims - segment_ids . shape . ndims <nl> + broadcast_shape = [ num_segments ] + [ 1 ] * ndims_output <nl> + N = array_ops . reshape ( N , broadcast_shape ) <nl> + return gen_math_ops . maximum ( N , 1 ) <nl> + <nl> + <nl> + @ tf_export ( " unsorted_segment_mean " ) <nl> + def unsorted_segment_mean ( data , segment_ids , num_segments , name = None ) : <nl> + r " " " Computes the mean along segments of a tensor . <nl> + <nl> + Read @ { $ math_ops # segmentation $ the section on segmentation } for an explanation <nl> + of segments . <nl> + <nl> + This operator is similar to the unsorted segment sum operator found <nl> + [ here ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> + Instead of computing the sum over segments , it computes the mean of all <nl> + entries belonging to a segment such that : <nl> + <nl> + \ \ ( output_i = 1 / N_i \ sum data_j \ \ ) where the sum is over ` j ` such <nl> + that ` segment_ids [ j ] = = i ` with \ \ N_i \ \ being the number of occurrences <nl> + of id \ \ i \ \ . <nl> + <nl> + If there is no entry for a given segment ID ` i ` , it outputs 0 . <nl> + <nl> + segment_ids : A 1 - D tensor whose rank is equal to the rank of ` data ` ' s <nl> + first dimension . <nl> + <nl> + output : Has same shape as data , except for dimension 0 which <nl> + has size ` num_segments ` . <nl> + " " " <nl> + with ops . name_scope ( name , " UnsortedSegmentMean " ) : <nl> + data = ops . convert_to_tensor ( data ) <nl> + segment_ids = ops . convert_to_tensor ( segment_ids ) <nl> + N = _unsorted_segment_N ( data , segment_ids , num_segments ) <nl> + summed = gen_math_ops . unsorted_segment_sum ( data , segment_ids , num_segments ) <nl> + return summed / N <nl> + <nl> + <nl> + @ tf_export ( " unsorted_segment_sqrt_n " ) <nl> + def unsorted_segment_sqrt_n ( data , segment_ids , num_segments , name = None ) : <nl> + r " " " Computes the sum along segments of a tensor divided by the sqrt ( N ) . <nl> + <nl> + Read @ { $ math_ops # segmentation $ the section on segmentation } for an explanation <nl> + of segments . <nl> + <nl> + This operator is similar to the unsorted segment sum operator found <nl> + [ here ] ( . . / . . / . . / api_docs / python / math_ops . md # UnsortedSegmentSum ) . <nl> + Additionally to computing the sum over segments , it divides the results by <nl> + sqrt ( N ) . <nl> + <nl> + \ \ ( output_i = 1 / sqrt ( N_i ) \ sum data_j \ \ ) where the sum is over ` j ` such <nl> + that ` segment_ids [ j ] = = i ` with \ \ N_i \ \ being the number of occurrences <nl> + of id \ \ i \ \ . <nl> + <nl> + If there is no entry for a given segment ID ` i ` , it outputs 0 . <nl> + <nl> + Note that this op only supports floating point and complex dtypes , <nl> + due to tf . sqrt only supporting these types . <nl> + <nl> + segment_ids : A 1 - D tensor whose rank is equal to the rank of ` data ` ' s <nl> + first dimension . <nl> + <nl> + output : Has same shape as data , except for dimension 0 which <nl> + has size ` num_segments ` . <nl> + " " " <nl> + with ops . name_scope ( name , " UnsortedSegmentSqrtN " ) : <nl> + data = ops . convert_to_tensor ( data ) <nl> + segment_ids = ops . convert_to_tensor ( segment_ids ) <nl> + N = _unsorted_segment_N ( data , segment_ids , num_segments ) <nl> + summed = gen_math_ops . unsorted_segment_sum ( data , segment_ids , num_segments ) <nl> + return summed / gen_math_ops . sqrt ( N ) <nl> + <nl> + <nl> @ tf_export ( " sparse_segment_sum " ) <nl> def sparse_segment_sum ( data , indices , segment_ids , name = None , <nl> num_segments = None ) : <nl> mmm a / tensorflow / python / ops / nn_impl . py <nl> ppp b / tensorflow / python / ops / nn_impl . py <nl> def sampled_softmax_loss ( weights , <nl> sampled_losses = nn_ops . softmax_cross_entropy_with_logits ( <nl> labels = labels , logits = logits ) <nl> # sampled_losses is a [ batch_size ] tensor . <nl> - return sampled_losses <nl> + return sampled_losses <nl> \ No newline at end of file <nl> mmm a / tensorflow / python / tools / saved_model_cli . py <nl> ppp b / tensorflow / python / tools / saved_model_cli . py <nl> def _get_outputs_tensor_info_from_meta_graph_def ( meta_graph_def , <nl> signature_def_key ) . outputs <nl> <nl> <nl> - def _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key ) : <nl> + def _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key , indent = 0 ) : <nl> " " " Prints input and output TensorInfos . <nl> <nl> Prints the details of input and output TensorInfos for the SignatureDef mapped <nl> def _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key ) : <nl> tag_set : Group of tag ( s ) of the MetaGraphDef , in string format , separated by <nl> ' , ' . For tag - set contains multiple tags , all tags must be passed in . <nl> signature_def_key : A SignatureDef key string . <nl> + indent : How far ( in increments of 2 spaces ) to indent each line of output . <nl> " " " <nl> meta_graph_def = saved_model_utils . get_meta_graph_def ( saved_model_dir , <nl> tag_set ) <nl> def _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key ) : <nl> outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def ( <nl> meta_graph_def , signature_def_key ) <nl> <nl> - print ( ' The given SavedModel SignatureDef contains the following input ( s ) : ' ) <nl> + indent_str = " " * indent <nl> + def in_print ( s ) : <nl> + print ( indent_str + s ) <nl> + <nl> + in_print ( ' The given SavedModel SignatureDef contains the following input ( s ) : ' ) <nl> for input_key , input_tensor in sorted ( inputs_tensor_info . items ( ) ) : <nl> - print ( ' inputs [ \ ' % s \ ' ] tensor_info : ' % input_key ) <nl> - _print_tensor_info ( input_tensor ) <nl> + in_print ( ' inputs [ \ ' % s \ ' ] tensor_info : ' % input_key ) <nl> + _print_tensor_info ( input_tensor , indent + 1 ) <nl> <nl> - print ( ' The given SavedModel SignatureDef contains the following output ( s ) : ' ) <nl> + in_print ( ' The given SavedModel SignatureDef contains the following ' <nl> + ' output ( s ) : ' ) <nl> for output_key , output_tensor in sorted ( outputs_tensor_info . items ( ) ) : <nl> - print ( ' outputs [ \ ' % s \ ' ] tensor_info : ' % output_key ) <nl> - _print_tensor_info ( output_tensor ) <nl> + in_print ( ' outputs [ \ ' % s \ ' ] tensor_info : ' % output_key ) <nl> + _print_tensor_info ( output_tensor , indent + 1 ) <nl> <nl> - print ( ' Method name is : % s ' % <nl> - meta_graph_def . signature_def [ signature_def_key ] . method_name ) <nl> + in_print ( ' Method name is : % s ' % <nl> + meta_graph_def . signature_def [ signature_def_key ] . method_name ) <nl> <nl> <nl> - def _print_tensor_info ( tensor_info ) : <nl> + def _print_tensor_info ( tensor_info , indent = 0 ) : <nl> " " " Prints details of the given tensor_info . <nl> <nl> Args : <nl> tensor_info : TensorInfo object to be printed . <nl> + indent : How far ( in increments of 2 spaces ) to indent each line output <nl> " " " <nl> - print ( ' dtype : ' + <nl> - { value : key <nl> - for ( key , value ) in types_pb2 . DataType . items ( ) } [ tensor_info . dtype ] ) <nl> + indent_str = " " * indent <nl> + def in_print ( s ) : <nl> + print ( indent_str + s ) <nl> + <nl> + in_print ( ' dtype : ' + <nl> + { value : key <nl> + for ( key , value ) in types_pb2 . DataType . items ( ) } [ tensor_info . dtype ] ) <nl> # Display shape as tuple . <nl> if tensor_info . tensor_shape . unknown_rank : <nl> shape = ' unknown_rank ' <nl> def _print_tensor_info ( tensor_info ) : <nl> dims = [ str ( dim . size ) for dim in tensor_info . tensor_shape . dim ] <nl> shape = ' , ' . join ( dims ) <nl> shape = ' ( ' + shape + ' ) ' <nl> - print ( ' shape : ' + shape ) <nl> - print ( ' name : ' + tensor_info . name ) <nl> + in_print ( ' shape : ' + shape ) <nl> + in_print ( ' name : ' + tensor_info . name ) <nl> <nl> <nl> def _show_all ( saved_model_dir ) : <nl> def _show_all ( saved_model_dir ) : <nl> signature_def_map = get_signature_def_map ( saved_model_dir , tag_set ) <nl> for signature_def_key in sorted ( signature_def_map . keys ( ) ) : <nl> print ( ' \ nsignature_def [ \ ' ' + signature_def_key + ' \ ' ] : ' ) <nl> - _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key ) <nl> + _show_inputs_outputs ( saved_model_dir , tag_set , signature_def_key , <nl> + indent = 1 ) <nl> <nl> <nl> def get_meta_graph_def ( saved_model_dir , tag_set ) : <nl> def create_parser ( ) : <nl> show_msg = ( <nl> ' Usage examples : \ n ' <nl> ' To show all tag - sets in a SavedModel : \ n ' <nl> - ' $ saved_model_cli show - - dir / tmp / saved_model \ n ' <nl> + ' $ saved_model_cli show - - dir / tmp / saved_model \ n \ n ' <nl> ' To show all available SignatureDef keys in a ' <nl> ' MetaGraphDef specified by its tag - set : \ n ' <nl> - ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve \ n ' <nl> + ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve \ n \ n ' <nl> ' For a MetaGraphDef with multiple tags in the tag - set , all tags must be ' <nl> ' passed in , separated by \ ' ; \ ' : \ n ' <nl> ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve , gpu \ n \ n ' <nl> ' To show all inputs and outputs TensorInfo for a specific ' <nl> ' SignatureDef specified by the SignatureDef key in a ' <nl> ' MetaGraph . \ n ' <nl> - ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve ' <nl> - ' - - signature_def serving_default \ n \ n ' <nl> - ' To show all available information in the SavedModel \ n : ' <nl> + ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve ' <nl> + ' - - signature_def serving_default \ n \ n ' <nl> + ' To show all available information in the SavedModel : \ n ' <nl> ' $ saved_model_cli show - - dir / tmp / saved_model - - all ' ) <nl> parser_show = subparsers . add_parser ( <nl> ' show ' , <nl> def create_parser ( ) : <nl> run_msg = ( ' Usage example : \ n ' <nl> ' To run input tensors from files through a MetaGraphDef and save ' <nl> ' the output tensors to files : \ n ' <nl> - ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve ' <nl> - ' - - signature_def serving_default ' <nl> - ' - - inputs input1_key = / tmp / 124 . npz [ x ] , input2_key = / tmp / 123 . npy ' <nl> - ' - - input_exprs \ ' input3_key = np . ones ( 2 ) \ ' - - input_examples ' <nl> - ' \ ' input4_key = [ { " id " : [ 26 ] , " weights " : [ 0 . 5 , 0 . 5 ] } ] \ ' ' <nl> - ' - - outdir = / out \ n \ n ' <nl> + ' $ saved_model_cli show - - dir / tmp / saved_model - - tag_set serve \ \ \ n ' <nl> + ' - - signature_def serving_default \ \ \ n ' <nl> + ' - - inputs input1_key = / tmp / 124 . npz [ x ] , input2_key = / tmp / 123 . npy ' <nl> + ' \ \ \ n ' <nl> + ' - - input_exprs \ ' input3_key = np . ones ( 2 ) \ ' \ \ \ n ' <nl> + ' - - input_examples ' <nl> + ' \ ' input4_key = [ { " id " : [ 26 ] , " weights " : [ 0 . 5 , 0 . 5 ] } ] \ ' \ \ \ n ' <nl> + ' - - outdir = / out \ n \ n ' <nl> ' For more information about input file format , please see : \ n ' <nl> ' https : / / www . tensorflow . org / programmers_guide / saved_model_cli \ n ' ) <nl> parser_run = subparsers . add_parser ( <nl> mmm a / tensorflow / python / tools / saved_model_cli_test . py <nl> ppp b / tensorflow / python / tools / saved_model_cli_test . py <nl> def testShowCommandAll ( self ) : <nl> exp_out = " " " MetaGraphDef with tag - set : ' serve ' contains the following SignatureDefs : <nl> <nl> signature_def [ ' classify_x2_to_y3 ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x2 : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' scores ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y3 : 0 <nl> - Method name is : tensorflow / serving / classify <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x2 : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' scores ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y3 : 0 <nl> + Method name is : tensorflow / serving / classify <nl> <nl> signature_def [ ' classify_x_to_y ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_STRING <nl> - shape : unknown_rank <nl> - name : tf_example : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' scores ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y : 0 <nl> - Method name is : tensorflow / serving / classify <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_STRING <nl> + shape : unknown_rank <nl> + name : tf_example : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' scores ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y : 0 <nl> + Method name is : tensorflow / serving / classify <nl> <nl> signature_def [ ' regress_x2_to_y3 ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x2 : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' outputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y3 : 0 <nl> - Method name is : tensorflow / serving / regress <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x2 : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' outputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y3 : 0 <nl> + Method name is : tensorflow / serving / regress <nl> <nl> signature_def [ ' regress_x_to_y ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_STRING <nl> - shape : unknown_rank <nl> - name : tf_example : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' outputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y : 0 <nl> - Method name is : tensorflow / serving / regress <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_STRING <nl> + shape : unknown_rank <nl> + name : tf_example : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' outputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y : 0 <nl> + Method name is : tensorflow / serving / regress <nl> <nl> signature_def [ ' regress_x_to_y2 ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' inputs ' ] tensor_info : <nl> - dtype : DT_STRING <nl> - shape : unknown_rank <nl> - name : tf_example : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' outputs ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y2 : 0 <nl> - Method name is : tensorflow / serving / regress <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' inputs ' ] tensor_info : <nl> + dtype : DT_STRING <nl> + shape : unknown_rank <nl> + name : tf_example : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' outputs ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y2 : 0 <nl> + Method name is : tensorflow / serving / regress <nl> <nl> signature_def [ ' serving_default ' ] : <nl> - The given SavedModel SignatureDef contains the following input ( s ) : <nl> - inputs [ ' x ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : x : 0 <nl> - The given SavedModel SignatureDef contains the following output ( s ) : <nl> - outputs [ ' y ' ] tensor_info : <nl> - dtype : DT_FLOAT <nl> - shape : ( - 1 , 1 ) <nl> - name : y : 0 <nl> - Method name is : tensorflow / serving / predict " " " <nl> + The given SavedModel SignatureDef contains the following input ( s ) : <nl> + inputs [ ' x ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : x : 0 <nl> + The given SavedModel SignatureDef contains the following output ( s ) : <nl> + outputs [ ' y ' ] tensor_info : <nl> + dtype : DT_FLOAT <nl> + shape : ( - 1 , 1 ) <nl> + name : y : 0 <nl> + Method name is : tensorflow / serving / predict " " " <nl> # pylint : enable = line - too - long <nl> + self . maxDiff = None # Produce a useful error msg if the comparison fails <nl> self . assertMultiLineEqual ( output , exp_out ) <nl> self . assertEqual ( err . getvalue ( ) . strip ( ) , ' ' ) <nl> <nl> def testShowCommandInputsOutputs ( self ) : <nl> output = out . getvalue ( ) . strip ( ) <nl> expected_output = ( <nl> ' The given SavedModel SignatureDef contains the following input ( s ) : \ n ' <nl> - ' inputs [ \ ' x \ ' ] tensor_info : \ n ' <nl> - ' dtype : DT_FLOAT \ n shape : ( - 1 , 1 ) \ n name : x : 0 \ n ' <nl> + ' inputs [ \ ' x \ ' ] tensor_info : \ n ' <nl> + ' dtype : DT_FLOAT \ n shape : ( - 1 , 1 ) \ n name : x : 0 \ n ' <nl> ' The given SavedModel SignatureDef contains the following output ( s ) : \ n ' <nl> - ' outputs [ \ ' y \ ' ] tensor_info : \ n ' <nl> - ' dtype : DT_FLOAT \ n shape : ( - 1 , 1 ) \ n name : y : 0 \ n ' <nl> + ' outputs [ \ ' y \ ' ] tensor_info : \ n ' <nl> + ' dtype : DT_FLOAT \ n shape : ( - 1 , 1 ) \ n name : y : 0 \ n ' <nl> ' Method name is : tensorflow / serving / predict ' ) <nl> self . assertEqual ( output , expected_output ) <nl> self . assertEqual ( err . getvalue ( ) . strip ( ) , ' ' ) <nl> mmm a / tensorflow / python / training / checkpoint_utils . py <nl> ppp b / tensorflow / python / training / checkpoint_utils . py <nl> def _set_checkpoint_initializer ( variable , <nl> name : Name of the operation . <nl> " " " <nl> base_type = variable . dtype . base_dtype <nl> - with ops . colocate_with ( variable . op ) : <nl> + # Do not colocate with variable since RestoreV2 op only runs on CPU and <nl> + # colocation will force variable ( and other ops that colocate with variable ) <nl> + # to be on CPU as well . It is okay to place the variable ' s initializer op on <nl> + # CPU since it will only be run once at the start . <nl> + with ops . device ( variable . device ) , ops . device ( " / cpu : 0 " ) : <nl> restore_op = io_ops . restore_v2 ( <nl> ckpt_file , [ tensor_name ] , [ slice_spec ] , [ base_type ] , name = name ) [ 0 ] <nl> if isinstance ( variable , resource_variable_ops . ResourceVariable ) : <nl> mmm a / tensorflow / python / training / checkpoint_utils_test . py <nl> ppp b / tensorflow / python / training / checkpoint_utils_test . py <nl> def testRestoreRunsOnSameDevice ( self ) : <nl> <nl> checkpoint_utils . init_from_checkpoint ( checkpoint_dir , <nl> { " useful_scope / " : " useful_scope / " } ) <nl> - self . assertEqual ( my4 . _initializer_op . op . inputs [ 1 ] . device , " / job : ps " ) <nl> + # initializer runs on the same task but always on CPU . <nl> + self . assertEqual ( my4 . _initializer_op . op . inputs [ 1 ] . device , <nl> + " / job : ps / device : CPU : 0 " ) <nl> <nl> def testInitFromRootCheckpoint ( self ) : <nl> checkpoint_dir = self . get_temp_dir ( ) <nl> mmm a / tensorflow / tools / api / golden / tensorflow . pbtxt <nl> ppp b / tensorflow / tools / api / golden / tensorflow . pbtxt <nl> tf_module { <nl> name : " unsorted_segment_max " <nl> argspec : " args = [ \ ' data \ ' , \ ' segment_ids \ ' , \ ' num_segments \ ' , \ ' name \ ' ] , varargs = None , keywords = None , defaults = [ \ ' None \ ' ] , " <nl> } <nl> + member_method { <nl> + name : " unsorted_segment_min " <nl> + argspec : " args = [ \ ' data \ ' , \ ' segment_ids \ ' , \ ' num_segments \ ' , \ ' name \ ' ] , varargs = None , keywords = None , defaults = [ \ ' None \ ' ] , " <nl> + } <nl> + member_method { <nl> + name : " unsorted_segment_prod " <nl> + argspec : " args = [ \ ' data \ ' , \ ' segment_ids \ ' , \ ' num_segments \ ' , \ ' name \ ' ] , varargs = None , keywords = None , defaults = [ \ ' None \ ' ] , " <nl> + } <nl> + member_method { <nl> + name : " unsorted_segment_sqrt_n " <nl> + argspec : " args = [ \ ' data \ ' , \ ' segment_ids \ ' , \ ' num_segments \ ' , \ ' name \ ' ] , varargs = None , keywords = None , defaults = [ \ ' None \ ' ] , " <nl> + } <nl> member_method { <nl> name : " unsorted_segment_sum " <nl> argspec : " args = [ \ ' data \ ' , \ ' segment_ids \ ' , \ ' num_segments \ ' , \ ' name \ ' ] , varargs = None , keywords = None , defaults = [ \ ' None \ ' ] , " <nl> mmm a / tensorflow / tools / ci_build / builds / with_the_same_user <nl> ppp b / tensorflow / tools / ci_build / builds / with_the_same_user <nl> else <nl> rm / this_is_writable_file_system <nl> fi <nl> <nl> + if [ - n " $ { CI_BUILD_USER_FORCE_BADNAME } " ] ; then <nl> + ADDUSER_OPTS = " - - force - badname " <nl> + fi <nl> + <nl> getent group " $ { CI_BUILD_GID } " | | addgroup - - gid " $ { CI_BUILD_GID } " " $ { CI_BUILD_GROUP } " <nl> - getent passwd " $ { CI_BUILD_UID } " | | adduser - - gid " $ { CI_BUILD_GID } " - - uid " $ { CI_BUILD_UID } " \ <nl> + getent passwd " $ { CI_BUILD_UID } " | | adduser $ { ADDUSER_OPTS } \ <nl> + - - gid " $ { CI_BUILD_GID } " - - uid " $ { CI_BUILD_UID } " \ <nl> - - gecos " $ { CI_BUILD_USER } ( generated by with_the_same_user script ) " \ <nl> - - disabled - password - - home " $ { CI_BUILD_HOME } " - - quiet " $ { CI_BUILD_USER } " <nl> usermod - a - G sudo " $ { CI_BUILD_USER } " <nl> mmm a / tensorflow / tools / ci_build / install / install_bazel . sh <nl> ppp b / tensorflow / tools / ci_build / install / install_bazel . sh <nl> <nl> # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> # Select bazel version . <nl> - BAZEL_VERSION = " 0 . 10 . 0 " <nl> + BAZEL_VERSION = " 0 . 11 . 0 " <nl> <nl> set + e <nl> local_bazel_ver = $ ( bazel version 2 > & 1 | grep - i label | awk ' { print $ 3 } ' ) <nl> mmm a / tensorflow / tools / docker / Dockerfile . devel <nl> ppp b / tensorflow / tools / docker / Dockerfile . devel <nl> RUN echo " startup - - batch " > > / etc / bazel . bazelrc <nl> RUN echo " build - - spawn_strategy = standalone - - genrule_strategy = standalone " \ <nl> > > / etc / bazel . bazelrc <nl> # Install the most recent bazel release . <nl> - ENV BAZEL_VERSION 0 . 8 . 0 <nl> + ENV BAZEL_VERSION 0 . 11 . 0 <nl> WORKDIR / <nl> RUN mkdir / bazel & & \ <nl> cd / bazel & & \ <nl> mmm a / tensorflow / tools / docker / Dockerfile . devel - gpu <nl> ppp b / tensorflow / tools / docker / Dockerfile . devel - gpu <nl> RUN echo " startup - - batch " > > / etc / bazel . bazelrc <nl> RUN echo " build - - spawn_strategy = standalone - - genrule_strategy = standalone " \ <nl> > > / etc / bazel . bazelrc <nl> # Install the most recent bazel release . <nl> - ENV BAZEL_VERSION 0 . 8 . 0 <nl> + ENV BAZEL_VERSION 0 . 11 . 0 <nl> WORKDIR / <nl> RUN mkdir / bazel & & \ <nl> cd / bazel & & \ <nl> mmm a / tensorflow / tools / graph_transforms / BUILD <nl> ppp b / tensorflow / tools / graph_transforms / BUILD <nl> cc_library ( <nl> " / / tensorflow / core : tensorflow " , <nl> " / / tensorflow / contrib / rnn : gru_ops_op_lib " , <nl> " / / tensorflow / contrib / rnn : lstm_ops_op_lib " , <nl> + " / / tensorflow / core / kernels : quantization_utils " , <nl> ] + if_not_windows ( [ <nl> - " / / tensorflow / core / kernels : quantized_ops " , <nl> " / / tensorflow / core / kernels : remote_fused_graph_rewriter_transform " , <nl> " / / tensorflow / core / kernels / hexagon : hexagon_rewriter_transform " , <nl> ] ) , <nl> mmm a / tensorflow / tools / graph_transforms / remove_control_dependencies . cc <nl> ppp b / tensorflow / tools / graph_transforms / remove_control_dependencies . cc <nl> namespace graph_transforms { <nl> / / inputs which are referenced with " ^ tensor_name " . <nl> / / See node_def . proto for more details . <nl> Status RemoveControlDependencies ( const GraphDef & input_graph_def , <nl> - const TransformFuncContext & context , <nl> - GraphDef * output_graph_def ) { <nl> - output_graph_def - > Clear ( ) ; <nl> - for ( const NodeDef & node : input_graph_def . node ( ) ) { <nl> - NodeDef * new_node = output_graph_def - > mutable_node ( ) - > Add ( ) ; <nl> - * new_node = node ; <nl> - new_node - > clear_input ( ) ; <nl> - for ( const auto & input : node . input ( ) ) { <nl> - if ( input [ 0 ] ! = ' ^ ' ) { <nl> - new_node - > add_input ( input ) ; <nl> - } <nl> + const TransformFuncContext & context , <nl> + GraphDef * output_graph_def ) { <nl> + output_graph_def - > Clear ( ) ; <nl> + for ( const NodeDef & node : input_graph_def . node ( ) ) { <nl> + NodeDef * new_node = output_graph_def - > mutable_node ( ) - > Add ( ) ; <nl> + * new_node = node ; <nl> + new_node - > clear_input ( ) ; <nl> + for ( const auto & input : node . input ( ) ) { <nl> + if ( input [ 0 ] ! = ' ^ ' ) { <nl> + new_node - > add_input ( input ) ; <nl> + } <nl> + } <nl> } <nl> - } <nl> - return Status : : OK ( ) ; <nl> + return Status : : OK ( ) ; <nl> } <nl> <nl> - REGISTER_GRAPH_TRANSFORM ( " remove_control_dependencies " , <nl> - RemoveControlDependencies ) ; <nl> + REGISTER_GRAPH_TRANSFORM ( " remove_control_dependencies " , RemoveControlDependencies ) ; <nl> <nl> } / / namespace graph_transforms <nl> } / / namespace tensorflow <nl> mmm a / tensorflow / tools / lib_package / BUILD <nl> ppp b / tensorflow / tools / lib_package / BUILD <nl> pkg_tar ( <nl> " : cheaders " , <nl> " : clib " , <nl> " : clicenses " , <nl> + " : eager_cheaders " , <nl> ] , <nl> ) <nl> <nl> pkg_tar ( <nl> name = " cheaders " , <nl> files = [ <nl> " / / tensorflow / c : headers " , <nl> - " / / tensorflow / c / eager : headers " , <nl> ] , <nl> package_dir = " include / tensorflow / c " , <nl> # Mark as " manual " till <nl> pkg_tar ( <nl> tags = [ " manual " ] , <nl> ) <nl> <nl> + pkg_tar ( <nl> + name = " eager_cheaders " , <nl> + files = [ <nl> + " / / tensorflow / c / eager : headers " , <nl> + ] , <nl> + package_dir = " include / tensorflow / c / eager " , <nl> + # Mark as " manual " till <nl> + # https : / / github . com / bazelbuild / bazel / issues / 2352 <nl> + # and https : / / github . com / bazelbuild / bazel / issues / 1580 <nl> + # are resolved , otherwise these rules break when built <nl> + # with Python 3 . <nl> + tags = [ " manual " ] , <nl> + ) <nl> + <nl> pkg_tar ( <nl> name = " clib " , <nl> files = [ " / / tensorflow : libtensorflow . so " ] , <nl>
Merge changes from github .
tensorflow/tensorflow
7144571f2fc59c8705e4e3d7b922fa0ebf44f3fa
2018-03-13T02:37:39Z
mmm a / THCTensorMath2 . cu <nl> ppp b / THCTensorMath2 . cu <nl> void THCudaTensor_atan2 ( THCState * state , THCudaTensor * self_ , THCudaTensor * tx , <nl> THCudaCheck ( cudaGetLastError ( ) ) ; <nl> } <nl> <nl> - struct dist_functor <nl> - { <nl> - const float exponent ; <nl> - <nl> - dist_functor ( float exponent_ ) : exponent ( exponent_ ) { } <nl> - <nl> - __host__ __device__ float operator ( ) ( const float & x , const float & y ) const <nl> - { <nl> - return pow ( fabs ( x - y ) , exponent ) ; <nl> - } <nl> - } ; <nl> - <nl> float THCudaTensor_dist ( THCState * state , THCudaTensor * self , THCudaTensor * src , float value ) <nl> { <nl> THAssert ( THCudaTensor_checkGPU ( state , 2 , self , src ) ) ; <nl> float THCudaTensor_dist ( THCState * state , THCudaTensor * self , THCudaTensor * src , <nl> thrust : : cuda : : par . on ( THCState_getCurrentStream ( state ) ) , <nl> # endif <nl> self_data , self_data + size , src_data , ( float ) 0 , <nl> - thrust : : plus < float > ( ) , dist_functor ( value ) ) ; <nl> + thrust : : plus < float > ( ) , TensorDistOp < float > ( value ) ) ; <nl> <nl> THCudaTensor_free ( state , src ) ; <nl> THCudaTensor_free ( state , self ) ; <nl> mmm a / THCTensorMathReduce . cuh <nl> ppp b / THCTensorMathReduce . cuh <nl> struct TensorNormOp < half , StaticExp > <nl> } ; <nl> # endif <nl> <nl> + template < typename T > <nl> + struct TensorDistOp <nl> + { <nl> + TensorDistOp ( T exp ) : exponent ( exp ) { } <nl> + <nl> + __host__ __device__ T operator ( ) ( T x , T y ) const { <nl> + return THCNumerics < T > : : pow ( <nl> + THCNumerics < T > : : abs ( THCNumerics < T > : : sub ( x , y ) ) , <nl> + exponent <nl> + ) ; <nl> + } <nl> + <nl> + const T exponent ; <nl> + } ; <nl> + <nl> # include < thrust / functional . h > <nl> <nl> / / Given the sum of values and the sum of squares , compute the variance or standard deviation . <nl>
[ cutorch refactor ] make dist ( . . . ) ' s op generic , add missing unit test
pytorch/pytorch
e88e0026b1a64cd63f3435f5cfa96abb0f273ecd
2016-10-07T18:50:28Z
new file mode 100644 <nl> index 00000000000 . . 997da4ee958 <nl> mmm / dev / null <nl> ppp b / src / liveobjectlist - inl . h <nl> <nl> + / / Copyright 2011 the V8 project authors . All rights reserved . <nl> + / / Redistribution and use in source and binary forms , with or without <nl> + / / modification , are permitted provided that the following conditions are <nl> + / / met : <nl> + / / <nl> + / / * Redistributions of source code must retain the above copyright <nl> + / / notice , this list of conditions and the following disclaimer . <nl> + / / * Redistributions in binary form must reproduce the above <nl> + / / copyright notice , this list of conditions and the following <nl> + / / disclaimer in the documentation and / or other materials provided <nl> + / / with the distribution . <nl> + / / * Neither the name of Google Inc . nor the names of its <nl> + / / contributors may be used to endorse or promote products derived <nl> + / / from this software without specific prior written permission . <nl> + / / <nl> + / / THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + / / " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + / / LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + / / A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + / / OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + / / SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + / / LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + / / DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + / / THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + / / ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + / / OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # ifndef V8_LIVEOBJECTLIST_INL_H_ <nl> + # define V8_LIVEOBJECTLIST_INL_H_ <nl> + <nl> + # include " v8 . h " <nl> + <nl> + # include " liveobjectlist . h " <nl> + <nl> + # endif / / V8_LIVEOBJECTLIST_INL_H_ <nl> + <nl> new file mode 100644 <nl> index 00000000000 . . 28a3d6d6ecc <nl> mmm / dev / null <nl> ppp b / src / liveobjectlist . cc <nl> <nl> + / / Copyright 2011 the V8 project authors . All rights reserved . <nl> + / / Redistribution and use in source and binary forms , with or without <nl> + / / modification , are permitted provided that the following conditions are <nl> + / / met : <nl> + / / <nl> + / / * Redistributions of source code must retain the above copyright <nl> + / / notice , this list of conditions and the following disclaimer . <nl> + / / * Redistributions in binary form must reproduce the above <nl> + / / copyright notice , this list of conditions and the following <nl> + / / disclaimer in the documentation and / or other materials provided <nl> + / / with the distribution . <nl> + / / * Neither the name of Google Inc . nor the names of its <nl> + / / contributors may be used to endorse or promote products derived <nl> + / / from this software without specific prior written permission . <nl> + / / <nl> + / / THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + / / " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + / / LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + / / A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + / / OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + / / SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + / / LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + / / DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + / / THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + / / ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + / / OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # ifdef LIVE_OBJECT_LIST <nl> + <nl> + # include < ctype . h > <nl> + # include < stdlib . h > <nl> + <nl> + # include " v8 . h " <nl> + <nl> + # include " checks . h " <nl> + # include " global - handles . h " <nl> + # include " heap . h " <nl> + # include " inspector . h " <nl> + # include " list - inl . h " <nl> + # include " liveobjectlist . h " <nl> + # include " string - stream . h " <nl> + # include " top . h " <nl> + # include " v8utils . h " <nl> + <nl> + namespace v8 { <nl> + namespace internal { <nl> + <nl> + <nl> + <nl> + } } / / namespace v8 : : internal <nl> + <nl> + # endif / / LIVE_OBJECT_LIST <nl> + <nl> new file mode 100644 <nl> index 00000000000 . . 11f5c451782 <nl> mmm / dev / null <nl> ppp b / src / liveobjectlist . h <nl> <nl> + / / Copyright 2011 the V8 project authors . All rights reserved . <nl> + / / Redistribution and use in source and binary forms , with or without <nl> + / / modification , are permitted provided that the following conditions are <nl> + / / met : <nl> + / / <nl> + / / * Redistributions of source code must retain the above copyright <nl> + / / notice , this list of conditions and the following disclaimer . <nl> + / / * Redistributions in binary form must reproduce the above <nl> + / / copyright notice , this list of conditions and the following <nl> + / / disclaimer in the documentation and / or other materials provided <nl> + / / with the distribution . <nl> + / / * Neither the name of Google Inc . nor the names of its <nl> + / / contributors may be used to endorse or promote products derived <nl> + / / from this software without specific prior written permission . <nl> + / / <nl> + / / THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + / / " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + / / LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + / / A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + / / OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + / / SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + / / LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + / / DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + / / THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + / / ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + / / OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # ifndef V8_LIVEOBJECTLIST_H_ <nl> + # define V8_LIVEOBJECTLIST_H_ <nl> + <nl> + # include " v8 . h " <nl> + <nl> + # include " checks . h " <nl> + # include " heap . h " <nl> + # include " objects . h " <nl> + # include " globals . h " <nl> + <nl> + namespace v8 { <nl> + namespace internal { <nl> + <nl> + # ifdef LIVE_OBJECT_LIST <nl> + <nl> + <nl> + / / Temporary stubbed out LiveObjectList implementation . <nl> + class LiveObjectList { <nl> + public : <nl> + inline static void GCEpilogue ( ) { } <nl> + inline static void GCPrologue ( ) { } <nl> + inline static void IterateElements ( ObjectVisitor * v ) { } <nl> + inline static void ProcessNonLive ( HeapObject * obj ) { } <nl> + inline static void UpdateReferencesForScavengeGC ( ) { } <nl> + <nl> + static MaybeObject * Capture ( ) { return Heap : : undefined_value ( ) ; } <nl> + static bool Delete ( int id ) { return false ; } <nl> + static MaybeObject * Dump ( int id1 , <nl> + int id2 , <nl> + int start_idx , <nl> + int dump_limit , <nl> + Handle < JSObject > filter_obj ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + static MaybeObject * Info ( int start_idx , int dump_limit ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + static MaybeObject * Summarize ( int id1 , <nl> + int id2 , <nl> + Handle < JSObject > filter_obj ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + <nl> + static void Reset ( ) { } <nl> + static Object * GetObj ( int obj_id ) { return Heap : : undefined_value ( ) ; } <nl> + static Object * GetObjId ( Handle < String > address ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + static MaybeObject * GetObjRetainers ( int obj_id , <nl> + Handle < JSObject > instance_filter , <nl> + bool verbose , <nl> + int start , <nl> + int count , <nl> + Handle < JSObject > filter_obj ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + <nl> + static Object * GetPath ( int obj_id1 , <nl> + int obj_id2 , <nl> + Handle < JSObject > instance_filter ) { <nl> + return Heap : : undefined_value ( ) ; <nl> + } <nl> + static Object * PrintObj ( int obj_id ) { return Heap : : undefined_value ( ) ; } <nl> + } ; <nl> + <nl> + <nl> + # else / / ! LIVE_OBJECT_LIST <nl> + <nl> + <nl> + class LiveObjectList { <nl> + public : <nl> + static void GCEpilogue ( ) { } <nl> + static void GCPrologue ( ) { } <nl> + static void IterateElements ( ObjectVisitor * v ) { } <nl> + static void ProcessNonLive ( HeapObject * obj ) { } <nl> + static void UpdateReferencesForScavengeGC ( ) { } <nl> + } ; <nl> + <nl> + <nl> + # endif / / LIVE_OBJECT_LIST <nl> + <nl> + } } / / namespace v8 : : internal <nl> + <nl> + # endif / / V8_LIVEOBJECTLIST_H_ <nl> + <nl>
Stubbed out empty liveobjectlist files .
v8/v8
e528223fe2bd6d114d786bd1910431c0115da469
2011-01-20T08:11:53Z
new file mode 100644 <nl> index 00000000000 . . dffa16eaec2 <nl> mmm / dev / null <nl> ppp b / tests / queries / 0_stateless / 01342_query_parameters_alias . reference <nl> <nl> + a <nl> + Nullable ( Nothing ) <nl> + \ N <nl> new file mode 100755 <nl> index 00000000000 . . 1f46f6b388e <nl> mmm / dev / null <nl> ppp b / tests / queries / 0_stateless / 01342_query_parameters_alias . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + $ CLICKHOUSE_CLIENT - - param_x ' \ N ' - - query ' SELECT { x : Nullable ( Nothing ) } as a ' - - format TSVWithNamesAndTypes <nl>
Added a test
ClickHouse/ClickHouse
c7d6d531f51c41274c82640cb189b27b844cc825
2020-06-24T13:20:39Z
mmm a / tensorflow / lite / examples / label_image / label_image . cc <nl> ppp b / tensorflow / lite / examples / label_image / label_image . cc <nl> int Main ( int argc , char * * argv ) { <nl> strtol ( optarg , nullptr , 10 ) ; / / NOLINT ( runtime / deprecated_fn ) <nl> break ; <nl> case ' x ' : <nl> - s . xnnpack_delegate = optarg ; <nl> + s . xnnpack_delegate = <nl> + strtol ( optarg , nullptr , 10 ) ; / / NOLINT ( runtime / deprecated_fn ) <nl> break ; <nl> case ' h ' : <nl> case ' ? ' : <nl>
Merge pull request from JerryShih : fix_label_image_xnnpack
tensorflow/tensorflow
391188971270b71fa243df5bb0ed14e4a5498e56
2020-09-28T16:55:06Z
mmm a / dlib / CMakeLists . txt <nl> ppp b / dlib / CMakeLists . txt <nl> set ( dlib_needed_includes ) <nl> # dlib_needed_includes which will get pushed into the parent cmake scope at the <nl> # end of this CMakeLists . txt file . This way , it is available to users of dlib / cmake . <nl> macro ( add_include_directories dir ) <nl> - include_directories ( $ { dir } ) <nl> set ( dlib_needed_includes $ { dlib_needed_includes } $ { dir } ) <nl> endmacro ( ) <nl> <nl> if ( NOT TARGET dlib ) <nl> else ( ) <nl> add_library ( dlib STATIC $ { source_files } ) <nl> endif ( ) <nl> - target_link_libraries ( dlib $ { dlib_needed_libraries } ) <nl> + target_link_libraries ( dlib PRIVATE $ { dlib_needed_libraries } ) <nl> if ( UNIX AND NOT DLIB_IN_PROJECT_BUILD ) <nl> if ( DLIB_USE_CUDA ) <nl> cuda_add_library ( dlib_shared SHARED $ { source_files } ) <nl> if ( NOT TARGET dlib ) <nl> add_library ( dlib_shared SHARED $ { source_files } ) <nl> add_dependencies ( dlib_shared dlib ) <nl> endif ( ) <nl> - target_link_libraries ( dlib_shared $ { dlib_needed_libraries } ) <nl> + target_link_libraries ( dlib_shared PRIVATE $ { dlib_needed_libraries } ) <nl> endif ( ) <nl> <nl> endif ( ) # # # # # end of if NOT DLIB_ISO_CPP_ONLY # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> if ( NOT TARGET dlib ) <nl> endif ( ) <nl> <nl> # Specify the include directory for CMake targets relying on dlib . <nl> - target_include_directories ( dlib INTERFACE $ < INSTALL_INTERFACE : include > ) <nl> - target_include_directories ( dlib_shared INTERFACE $ < INSTALL_INTERFACE : include > ) <nl> + target_include_directories ( dlib <nl> + INTERFACE $ < BUILD_INTERFACE : $ { CMAKE_CURRENT_SOURCE_DIR } / . . > <nl> + INTERFACE $ < INSTALL_INTERFACE : include > <nl> + PUBLIC $ { dlib_needed_includes } <nl> + ) <nl> + target_include_directories ( dlib_shared <nl> + INTERFACE $ < BUILD_INTERFACE : $ { CMAKE_CURRENT_SOURCE_DIR } / . . > <nl> + INTERFACE $ < INSTALL_INTERFACE : include > <nl> + PUBLIC $ { dlib_needed_includes } <nl> + ) <nl> <nl> # Install the library <nl> if ( NOT DLIB_IN_PROJECT_BUILD ) <nl>
Add target_include_directories for build interface and for optional libraries
davisking/dlib
3eaa463ec6d98baa900892d23a0278f84b480bbc
2017-02-27T17:01:22Z
mmm a / ports / allegro5 / portfile . cmake <nl> ppp b / ports / allegro5 / portfile . cmake <nl> <nl> # <nl> <nl> include ( vcpkg_common_functions ) <nl> - set ( SOURCE_PATH $ { CURRENT_BUILDTREES_DIR } / src / allegro5 - e8b209bc20a60224859eb8a0cae082bd20d32ed1 ) <nl> vcpkg_from_github ( <nl> - OUT_SOURCE_PATH $ { SOURCE_PATH } <nl> + OUT_SOURCE_PATH SOURCE_PATH <nl> REPO liballeg / allegro5 <nl> REF e8b209bc20a60224859eb8a0cae082bd20d32ed1 <nl> SHA512 50b30d4b539bd4a2488d2b33e9fbfc6fdfd340039d9086993a5719bab3cb020ee6fe7f6d3578755a52c8aab9816d25cd74710ce93b0b374a2f97620b6138419d <nl> mmm a / ports / arb / portfile . cmake <nl> ppp b / ports / arb / portfile . cmake <nl> if ( VCPKG_LIBRARY_LINKAGE STREQUAL dynamic ) <nl> endif ( ) <nl> <nl> include ( vcpkg_common_functions ) <nl> - set ( SOURCE_PATH $ { CURRENT_BUILDTREES_DIR } / src / arb - 2 . 11 . 1 ) <nl> <nl> vcpkg_from_github ( <nl> - OUT_SOURCE_PATH $ { SOURCE_PATH } <nl> + OUT_SOURCE_PATH SOURCE_PATH <nl> REPO fredrik - johansson / arb <nl> REF 2 . 11 . 1 <nl> SHA512 7a014da5208b55f20c7a3cd3eb51070b09ae107b04cbbd6329925780c2ab4d7c38e1fb3619f21456fa806939818370fcae921f59eb013661b6bdd3d0971e3353 <nl> mmm a / ports / libsodium / portfile . cmake <nl> ppp b / ports / libsodium / portfile . cmake <nl> <nl> include ( vcpkg_common_functions ) <nl> <nl> set ( LIBSODIUM_VERSION 1 . 0 . 15 ) <nl> - set ( SOURCE_PATH $ { CURRENT_BUILDTREES_DIR } / src / libsodium - $ { LIBSODIUM_VERSION } ) <nl> <nl> vcpkg_from_github ( <nl> - OUT_SOURCE_PATH $ { SOURCE_PATH } <nl> + OUT_SOURCE_PATH SOURCE_PATH <nl> REPO jedisct1 / libsodium <nl> REF $ { LIBSODIUM_VERSION } <nl> SHA512 ec497cb0007597efaeae0aecaa7484d6dcc53367607ec3fd28a98c6209f0cdecd5a6f560c15badd3a69b8da7d63676b11fb395ef4ed4da9b80467dbdc5f65a72 <nl> mmm a / ports / refprop - headers / portfile . cmake <nl> ppp b / ports / refprop - headers / portfile . cmake <nl> include ( vcpkg_common_functions ) <nl> set ( PORT_COMMIT 882aec454b2bc3d5323b8691736ff09c288f4ed6 ) <nl> <nl> vcpkg_from_github ( <nl> - OUT_SOURCE_PATH $ { SOURCE_PATH } <nl> + OUT_SOURCE_PATH SOURCE_PATH <nl> REPO CoolProp / REFPROP - headers <nl> REF $ { PORT_COMMIT } <nl> SHA512 23ee3df4ffe21b2d790efa27a1b8ea5fa4fce0a274d78e493a2d71043670420e19216f925d23d04f6139ca084a21b97028bd2547f3dbd00ffbb33d0c0bbfece5 <nl>
[ allegro5 ] [ refprop - headers ] [ libsodium ] [ arb ] Fix use of vcpkg_from_github ' s OUT_SOURCE_PATH parameter . Fixes .
microsoft/vcpkg
ca947c664ace9039b14126dedccd12616add09c9
2017-11-12T08:22:51Z
mmm a / src / video_core / renderer_opengl / gl_state . cpp <nl> ppp b / src / video_core / renderer_opengl / gl_state . cpp <nl> <nl> namespace OpenGL { <nl> <nl> OpenGLState OpenGLState : : cur_state ; <nl> + <nl> bool OpenGLState : : s_rgb_used ; <nl> + <nl> OpenGLState : : OpenGLState ( ) { <nl> / / These all match default OpenGL values <nl> geometry_shaders . enabled = false ; <nl> void OpenGLState : : ApplyDefaultState ( ) { <nl> } <nl> <nl> void OpenGLState : : ApplySRgb ( ) const { <nl> - / / sRGB <nl> if ( framebuffer_srgb . enabled ! = cur_state . framebuffer_srgb . enabled ) { <nl> if ( framebuffer_srgb . enabled ) { <nl> / / Track if sRGB is used <nl> void OpenGLState : : ApplySRgb ( ) const { <nl> } <nl> <nl> void OpenGLState : : ApplyCulling ( ) const { <nl> - / / Culling <nl> - const bool cull_changed = cull . enabled ! = cur_state . cull . enabled ; <nl> - if ( cull_changed ) { <nl> + if ( cull . enabled ! = cur_state . cull . enabled ) { <nl> if ( cull . enabled ) { <nl> glEnable ( GL_CULL_FACE ) ; <nl> } else { <nl> glDisable ( GL_CULL_FACE ) ; <nl> } <nl> } <nl> - if ( cull . enabled ) { <nl> - if ( cull_changed | | cull . mode ! = cur_state . cull . mode ) { <nl> - glCullFace ( cull . mode ) ; <nl> - } <nl> <nl> - if ( cull_changed | | cull . front_face ! = cur_state . cull . front_face ) { <nl> - glFrontFace ( cull . front_face ) ; <nl> - } <nl> + if ( cull . mode ! = cur_state . cull . mode ) { <nl> + glCullFace ( cull . mode ) ; <nl> + } <nl> + <nl> + if ( cull . front_face ! = cur_state . cull . front_face ) { <nl> + glFrontFace ( cull . front_face ) ; <nl> } <nl> } <nl> <nl> void OpenGLState : : ApplyColorMask ( ) const { <nl> } <nl> <nl> void OpenGLState : : ApplyDepth ( ) const { <nl> - / / Depth test <nl> - const bool depth_test_changed = depth . test_enabled ! = cur_state . depth . test_enabled ; <nl> - if ( depth_test_changed ) { <nl> + if ( depth . test_enabled ! = cur_state . depth . test_enabled ) { <nl> if ( depth . test_enabled ) { <nl> glEnable ( GL_DEPTH_TEST ) ; <nl> } else { <nl> glDisable ( GL_DEPTH_TEST ) ; <nl> } <nl> } <nl> - if ( depth . test_enabled & & <nl> - ( depth_test_changed | | depth . test_func ! = cur_state . depth . test_func ) ) { <nl> + <nl> + if ( depth . test_func ! = cur_state . depth . test_func ) { <nl> glDepthFunc ( depth . test_func ) ; <nl> } <nl> - / / Depth mask <nl> + <nl> if ( depth . write_mask ! = cur_state . depth . write_mask ) { <nl> glDepthMask ( depth . write_mask ) ; <nl> } <nl> } <nl> <nl> void OpenGLState : : ApplyPrimitiveRestart ( ) const { <nl> - const bool primitive_restart_changed = <nl> - primitive_restart . enabled ! = cur_state . primitive_restart . enabled ; <nl> - if ( primitive_restart_changed ) { <nl> + if ( primitive_restart . enabled ! = cur_state . primitive_restart . enabled ) { <nl> if ( primitive_restart . enabled ) { <nl> glEnable ( GL_PRIMITIVE_RESTART ) ; <nl> } else { <nl> glDisable ( GL_PRIMITIVE_RESTART ) ; <nl> } <nl> } <nl> - if ( primitive_restart_changed | | <nl> - ( primitive_restart . enabled & & <nl> - primitive_restart . index ! = cur_state . primitive_restart . index ) ) { <nl> + <nl> + if ( primitive_restart . index ! = cur_state . primitive_restart . index ) { <nl> glPrimitiveRestartIndex ( primitive_restart . index ) ; <nl> } <nl> } <nl> <nl> void OpenGLState : : ApplyStencilTest ( ) const { <nl> - const bool stencil_test_changed = stencil . test_enabled ! = cur_state . stencil . test_enabled ; <nl> - if ( stencil_test_changed ) { <nl> + if ( stencil . test_enabled ! = cur_state . stencil . test_enabled ) { <nl> if ( stencil . test_enabled ) { <nl> glEnable ( GL_STENCIL_TEST ) ; <nl> } else { <nl> glDisable ( GL_STENCIL_TEST ) ; <nl> } <nl> } <nl> - if ( stencil . test_enabled ) { <nl> - auto config_stencil = [ stencil_test_changed ] ( GLenum face , const auto & config , <nl> - const auto & prev_config ) { <nl> - if ( stencil_test_changed | | config . test_func ! = prev_config . test_func | | <nl> - config . test_ref ! = prev_config . test_ref | | <nl> - config . test_mask ! = prev_config . test_mask ) { <nl> - glStencilFuncSeparate ( face , config . test_func , config . test_ref , config . test_mask ) ; <nl> - } <nl> - if ( stencil_test_changed | | config . action_depth_fail ! = prev_config . action_depth_fail | | <nl> - config . action_depth_pass ! = prev_config . action_depth_pass | | <nl> - config . action_stencil_fail ! = prev_config . action_stencil_fail ) { <nl> - glStencilOpSeparate ( face , config . action_stencil_fail , config . action_depth_fail , <nl> - config . action_depth_pass ) ; <nl> - } <nl> - if ( config . write_mask ! = prev_config . write_mask ) { <nl> - glStencilMaskSeparate ( face , config . write_mask ) ; <nl> - } <nl> - } ; <nl> - config_stencil ( GL_FRONT , stencil . front , cur_state . stencil . front ) ; <nl> - config_stencil ( GL_BACK , stencil . back , cur_state . stencil . back ) ; <nl> - } <nl> + <nl> + const auto ConfigStencil = [ ] ( GLenum face , const auto & config , const auto & prev_config ) { <nl> + if ( config . test_func ! = prev_config . test_func | | config . test_ref ! = prev_config . test_ref | | <nl> + config . test_mask ! = prev_config . test_mask ) { <nl> + glStencilFuncSeparate ( face , config . test_func , config . test_ref , config . test_mask ) ; <nl> + } <nl> + if ( config . action_depth_fail ! = prev_config . action_depth_fail | | <nl> + config . action_depth_pass ! = prev_config . action_depth_pass | | <nl> + config . action_stencil_fail ! = prev_config . action_stencil_fail ) { <nl> + glStencilOpSeparate ( face , config . action_stencil_fail , config . action_depth_fail , <nl> + config . action_depth_pass ) ; <nl> + } <nl> + if ( config . write_mask ! = prev_config . write_mask ) { <nl> + glStencilMaskSeparate ( face , config . write_mask ) ; <nl> + } <nl> + } ; <nl> + ConfigStencil ( GL_FRONT , stencil . front , cur_state . stencil . front ) ; <nl> + ConfigStencil ( GL_BACK , stencil . back , cur_state . stencil . back ) ; <nl> } <nl> / / Viewport does not affects glClearBuffer so emulate viewport using scissor test <nl> void OpenGLState : : EmulateViewportWithScissor ( ) { <nl> void OpenGLState : : ApplyViewport ( ) const { <nl> updated . depth_range_far ! = current . depth_range_far ) { <nl> glDepthRangeIndexed ( i , updated . depth_range_near , updated . depth_range_far ) ; <nl> } <nl> - const bool scissor_changed = updated . scissor . enabled ! = current . scissor . enabled ; <nl> - if ( scissor_changed ) { <nl> + <nl> + if ( updated . scissor . enabled ! = current . scissor . enabled ) { <nl> if ( updated . scissor . enabled ) { <nl> glEnablei ( GL_SCISSOR_TEST , i ) ; <nl> } else { <nl> glDisablei ( GL_SCISSOR_TEST , i ) ; <nl> } <nl> } <nl> - if ( updated . scissor . enabled & & <nl> - ( scissor_changed | | updated . scissor . x ! = current . scissor . x | | <nl> - updated . scissor . y ! = current . scissor . y | | <nl> - updated . scissor . width ! = current . scissor . width | | <nl> - updated . scissor . height ! = current . scissor . height ) ) { <nl> + <nl> + if ( updated . scissor . x ! = current . scissor . x | | updated . scissor . y ! = current . scissor . y | | <nl> + updated . scissor . width ! = current . scissor . width | | <nl> + updated . scissor . height ! = current . scissor . height ) { <nl> glScissorIndexed ( i , updated . scissor . x , updated . scissor . y , updated . scissor . width , <nl> updated . scissor . height ) ; <nl> } <nl> void OpenGLState : : ApplyViewport ( ) const { <nl> updated . height ! = current . height ) { <nl> glViewport ( updated . x , updated . y , updated . width , updated . height ) ; <nl> } <nl> + <nl> if ( updated . depth_range_near ! = current . depth_range_near | | <nl> updated . depth_range_far ! = current . depth_range_far ) { <nl> glDepthRange ( updated . depth_range_near , updated . depth_range_far ) ; <nl> } <nl> - const bool scissor_changed = updated . scissor . enabled ! = current . scissor . enabled ; <nl> - if ( scissor_changed ) { <nl> + <nl> + if ( updated . scissor . enabled ! = current . scissor . enabled ) { <nl> if ( updated . scissor . enabled ) { <nl> glEnable ( GL_SCISSOR_TEST ) ; <nl> } else { <nl> glDisable ( GL_SCISSOR_TEST ) ; <nl> } <nl> } <nl> - if ( updated . scissor . enabled & & ( scissor_changed | | updated . scissor . x ! = current . scissor . x | | <nl> - updated . scissor . y ! = current . scissor . y | | <nl> - updated . scissor . width ! = current . scissor . width | | <nl> - updated . scissor . height ! = current . scissor . height ) ) { <nl> + <nl> + if ( updated . scissor . x ! = current . scissor . x | | updated . scissor . y ! = current . scissor . y | | <nl> + updated . scissor . width ! = current . scissor . width | | <nl> + updated . scissor . height ! = current . scissor . height ) { <nl> glScissor ( updated . scissor . x , updated . scissor . y , updated . scissor . width , <nl> updated . scissor . height ) ; <nl> } <nl> void OpenGLState : : ApplyViewport ( ) const { <nl> void OpenGLState : : ApplyGlobalBlending ( ) const { <nl> const Blend & current = cur_state . blend [ 0 ] ; <nl> const Blend & updated = blend [ 0 ] ; <nl> - const bool blend_changed = updated . enabled ! = current . enabled ; <nl> - if ( blend_changed ) { <nl> + if ( updated . enabled ! = current . enabled ) { <nl> if ( updated . enabled ) { <nl> glEnable ( GL_BLEND ) ; <nl> } else { <nl> void OpenGLState : : ApplyGlobalBlending ( ) const { <nl> if ( ! updated . enabled ) { <nl> return ; <nl> } <nl> - if ( blend_changed | | updated . src_rgb_func ! = current . src_rgb_func | | <nl> + if ( updated . src_rgb_func ! = current . src_rgb_func | | <nl> updated . dst_rgb_func ! = current . dst_rgb_func | | updated . src_a_func ! = current . src_a_func | | <nl> updated . dst_a_func ! = current . dst_a_func ) { <nl> glBlendFuncSeparate ( updated . src_rgb_func , updated . dst_rgb_func , updated . src_a_func , <nl> updated . dst_a_func ) ; <nl> } <nl> <nl> - if ( blend_changed | | updated . rgb_equation ! = current . rgb_equation | | <nl> - updated . a_equation ! = current . a_equation ) { <nl> + if ( updated . rgb_equation ! = current . rgb_equation | | updated . a_equation ! = current . a_equation ) { <nl> glBlendEquationSeparate ( updated . rgb_equation , updated . a_equation ) ; <nl> } <nl> } <nl> void OpenGLState : : ApplyGlobalBlending ( ) const { <nl> void OpenGLState : : ApplyTargetBlending ( std : : size_t target , bool force ) const { <nl> const Blend & updated = blend [ target ] ; <nl> const Blend & current = cur_state . blend [ target ] ; <nl> - const bool blend_changed = updated . enabled ! = current . enabled | | force ; <nl> - if ( blend_changed ) { <nl> + if ( updated . enabled ! = current . enabled | | force ) { <nl> if ( updated . enabled ) { <nl> glEnablei ( GL_BLEND , static_cast < GLuint > ( target ) ) ; <nl> } else { <nl> glDisablei ( GL_BLEND , static_cast < GLuint > ( target ) ) ; <nl> } <nl> } <nl> - if ( ! updated . enabled ) { <nl> - return ; <nl> - } <nl> - if ( blend_changed | | updated . src_rgb_func ! = current . src_rgb_func | | <nl> + <nl> + if ( updated . src_rgb_func ! = current . src_rgb_func | | <nl> updated . dst_rgb_func ! = current . dst_rgb_func | | updated . src_a_func ! = current . src_a_func | | <nl> updated . dst_a_func ! = current . dst_a_func ) { <nl> glBlendFuncSeparatei ( static_cast < GLuint > ( target ) , updated . src_rgb_func , <nl> updated . dst_rgb_func , updated . src_a_func , updated . dst_a_func ) ; <nl> } <nl> <nl> - if ( blend_changed | | updated . rgb_equation ! = current . rgb_equation | | <nl> - updated . a_equation ! = current . a_equation ) { <nl> + if ( updated . rgb_equation ! = current . rgb_equation | | updated . a_equation ! = current . a_equation ) { <nl> glBlendEquationSeparatei ( static_cast < GLuint > ( target ) , updated . rgb_equation , <nl> updated . a_equation ) ; <nl> } <nl> void OpenGLState : : ApplyBlending ( ) const { <nl> } <nl> <nl> void OpenGLState : : ApplyLogicOp ( ) const { <nl> - const bool logic_op_changed = logic_op . enabled ! = cur_state . logic_op . enabled ; <nl> - if ( logic_op_changed ) { <nl> + if ( logic_op . enabled ! = cur_state . logic_op . enabled ) { <nl> if ( logic_op . enabled ) { <nl> glEnable ( GL_COLOR_LOGIC_OP ) ; <nl> } else { <nl> void OpenGLState : : ApplyLogicOp ( ) const { <nl> } <nl> } <nl> <nl> - if ( logic_op . enabled & & <nl> - ( logic_op_changed | | logic_op . operation ! = cur_state . logic_op . operation ) ) { <nl> + if ( logic_op . operation ! = cur_state . logic_op . operation ) { <nl> glLogicOp ( logic_op . operation ) ; <nl> } <nl> } <nl> <nl> void OpenGLState : : ApplyPolygonOffset ( ) const { <nl> - <nl> const bool fill_enable_changed = <nl> polygon_offset . fill_enable ! = cur_state . polygon_offset . fill_enable ; <nl> const bool line_enable_changed = <nl> void OpenGLState : : ApplyPolygonOffset ( ) const { <nl> } <nl> } <nl> <nl> - if ( ( polygon_offset . fill_enable | | polygon_offset . line_enable | | polygon_offset . point_enable ) & & <nl> - ( factor_changed | | units_changed | | clamp_changed ) ) { <nl> - <nl> + if ( factor_changed | | units_changed | | clamp_changed ) { <nl> if ( GLAD_GL_EXT_polygon_offset_clamp & & polygon_offset . clamp ! = 0 ) { <nl> glPolygonOffsetClamp ( polygon_offset . factor , polygon_offset . units , polygon_offset . clamp ) ; <nl> } else { <nl> void OpenGLState : : ApplyDepthClamp ( ) const { <nl> depth_clamp . near_plane = = cur_state . depth_clamp . near_plane ) { <nl> return ; <nl> } <nl> - if ( depth_clamp . far_plane ! = depth_clamp . near_plane ) { <nl> - UNIMPLEMENTED_MSG ( " Unimplemented Depth Clamp Separation ! " ) ; <nl> - } <nl> + UNIMPLEMENTED_IF_MSG ( depth_clamp . far_plane ! = depth_clamp . near_plane , <nl> + " Unimplemented Depth Clamp Separation ! " ) ; <nl> + <nl> if ( depth_clamp . far_plane | | depth_clamp . near_plane ) { <nl> glEnable ( GL_DEPTH_CLAMP ) ; <nl> } else { <nl>
Merge pull request from ReinUsesLisp / fixup - glstate
yuzu-emu/yuzu
9539c4203b4e39d8715ba0fed88f56f063d0a548
2019-02-21T02:47:46Z
mmm a / src / btree / secondary_operations . cc <nl> ppp b / src / btree / secondary_operations . cc <nl> void initialize_secondary_indexes ( transaction_t * txn , buf_lock_t * sindex_block ) <nl> data - > magic = btree_sindex_block_t : : expected_magic ; <nl> memset ( data - > sindex_blob , 0 , btree_sindex_block_t : : SINDEX_BLOB_MAXREFLEN ) ; <nl> <nl> - / / RSI : This doesn ' t actually do anything , right ? <nl> - blob_t sindex_blob ( txn - > get_cache ( ) - > get_block_size ( ) , <nl> - data - > sindex_blob , <nl> - btree_sindex_block_t : : SINDEX_BLOB_MAXREFLEN ) ; <nl> - <nl> set_secondary_indexes_internal ( txn , sindex_block , std : : map < std : : string , secondary_index_t > ( ) ) ; <nl> } <nl> <nl>
Removed no - op blob_t construction in initialize_secondary_indexes .
rethinkdb/rethinkdb
b0497eddf512c2d0a0c37308794bb259b6dcb96f
2013-08-09T04:47:52Z
mmm a / hphp / test / zend / good / tests / lang / operators / postdec_variationStr . php <nl> ppp b / hphp / test / zend / good / tests / lang / operators / postdec_variationStr . php <nl> <nl> < ? hh <nl> - <nl> + < < __EntryPoint > > function main ( ) : void { <nl> $ strVals = varray [ " 0 " , " 65 " , " - 44 " , " 1 . 2 " , " - 7 . 7 " , " 123e5 " ] ; <nl> <nl> <nl> <nl> } <nl> <nl> echo " = = = DONE = = = \ n " ; <nl> + } <nl> mmm a / hphp / test / zend / good / tests / lang / operators / predec_variationStr . php <nl> ppp b / hphp / test / zend / good / tests / lang / operators / predec_variationStr . php <nl> <nl> < ? hh <nl> - <nl> + < < __EntryPoint > > function main ( ) : void { <nl> $ strVals = varray [ " 0 " , " 65 " , " - 44 " , " 1 . 2 " , " - 7 . 7 " , " 123e5 " ] ; <nl> <nl> <nl> <nl> } <nl> <nl> echo " = = = DONE = = = \ n " ; <nl> + } <nl> mmm a / hphp / test / zend / good / tests / lang / operators / preinc_variationStr . php <nl> ppp b / hphp / test / zend / good / tests / lang / operators / preinc_variationStr . php <nl> <nl> < ? hh <nl> - <nl> + < < __EntryPoint > > function main ( ) : void { <nl> $ strVals = varray [ " 0 " , " 65 " , " - 44 " , " 1 . 2 " , " - 7 . 7 " , " 123e5 " ] ; <nl> <nl> <nl> <nl> } <nl> <nl> echo " = = = DONE = = = \ n " ; <nl> + } <nl>
Add EntryPoints to three more tests ( now that D22423925 has landed ) .
facebook/hhvm
f6bf1a2e9f13a88976e3d01591e095a22862f8e4
2020-07-08T23:12:54Z
mmm a / lib / Conversion / LoopsToGPU / LoopsToGPUPass . cpp <nl> ppp b / lib / Conversion / LoopsToGPU / LoopsToGPUPass . cpp <nl> namespace { <nl> / / A pass that traverses top - level loops in the function and converts them to <nl> / / GPU launch operations . Nested launches are not allowed , so this does not <nl> / / walk the function recursively to avoid considering nested loops . <nl> - struct AffineForGPUMapper : public FunctionPass < AffineForGPUMapper > { <nl> - AffineForGPUMapper ( unsigned numBlockDims , unsigned numThreadDims ) <nl> + struct ForLoopMapper : public FunctionPass < ForLoopMapper > { <nl> + ForLoopMapper ( unsigned numBlockDims , unsigned numThreadDims ) <nl> : numBlockDims ( numBlockDims ) , numThreadDims ( numThreadDims ) { } <nl> <nl> void runOnFunction ( ) override { <nl> struct AffineForGPUMapper : public FunctionPass < AffineForGPUMapper > { <nl> unsigned numBlockDims ; <nl> unsigned numThreadDims ; <nl> } ; <nl> - <nl> - struct AffineForGPUMapperCLI : public AffineForGPUMapper { <nl> - AffineForGPUMapperCLI ( ) <nl> - : AffineForGPUMapper ( clNumBlockDims . getValue ( ) , <nl> - clNumThreadDims . getValue ( ) ) { } <nl> - } ; <nl> } / / namespace <nl> <nl> FunctionPassBase * mlir : : createSimpleLoopsToGPUPass ( unsigned numBlockDims , <nl> unsigned numThreadDims ) { <nl> - return new AffineForGPUMapper ( numBlockDims , numThreadDims ) ; <nl> + return new ForLoopMapper ( numBlockDims , numThreadDims ) ; <nl> } <nl> <nl> - static PassRegistration < AffineForGPUMapperCLI > <nl> - registration ( PASS_NAME , " Convert top - level loops to GPU kernels " ) ; <nl> + static PassRegistration < ForLoopMapper > <nl> + registration ( PASS_NAME , " Convert top - level loops to GPU kernels " , [ ] { <nl> + return new ForLoopMapper ( clNumBlockDims . getValue ( ) , <nl> + clNumThreadDims . getValue ( ) ) ; <nl> + } ) ; <nl>
LoopsToGPU : use PassRegistration with constructor
tensorflow/tensorflow
9f2f3d9b19c1e81bef56ec1f0653ff1818609b75
2019-07-12T15:44:14Z
mmm a / lib / AST / ASTVerifier . cpp <nl> ppp b / lib / AST / ASTVerifier . cpp <nl> class Verifier : public ASTWalker { <nl> verifyCheckedBase ( nominal ) ; <nl> } <nl> <nl> - void verifyCheckedAlways ( GenericTypeParamDecl * GTPD ) { <nl> - PrettyStackTraceDecl debugStack ( " verifying GenericTypeParamDecl " , GTPD ) ; <nl> - <nl> - const DeclContext * DC = GTPD - > getDeclContext ( ) ; <nl> - if ( ! GTPD - > getDeclContext ( ) - > isInnermostContextGeneric ( ) ) { <nl> - Out < < " DeclContext of GenericTypeParamDecl does not have " <nl> - " generic params " ; <nl> - abort ( ) ; <nl> - } <nl> - <nl> - GenericParamList * paramList = <nl> - static_cast < const GenericContext * > ( DC ) - > getGenericParams ( ) ; <nl> - if ( ! paramList ) { <nl> - Out < < " DeclContext of GenericTypeParamDecl does not have " <nl> - " generic params " ; <nl> - abort ( ) ; <nl> - } <nl> - <nl> - if ( paramList - > size ( ) < = GTPD - > getIndex ( ) | | <nl> - paramList - > getParams ( ) [ GTPD - > getIndex ( ) ] ! = GTPD ) { <nl> - Out < < " GenericTypeParamDecl has incorrect index " ; <nl> - abort ( ) ; <nl> - } <nl> - if ( paramList - > getDepth ( ) ! = GTPD - > getDepth ( ) ) { <nl> - Out < < " GenericTypeParamDecl has incorrect depth " ; <nl> - abort ( ) ; <nl> - } <nl> - <nl> - verifyCheckedBase ( GTPD ) ; <nl> - } <nl> - <nl> void verifyChecked ( ExtensionDecl * ext ) { <nl> / / Make sure that the protocol conformances are complete . <nl> for ( auto conformance : ext - > getLocalConformances ( ) ) { <nl>
Merge remote - tracking branch ' origin / master ' into master - next
apple/swift
f8dad3f899fb0f6c51c91a9a6d5cedfc0ec44d72
2018-11-08T20:30:39Z
mmm a / programs / cleos / httpc . cpp <nl> ppp b / programs / cleos / httpc . cpp <nl> namespace eosio { namespace client { namespace http { <nl> <nl> for ( const auto & r : result ) { <nl> const auto & addr = r . endpoint ( ) . address ( ) ; <nl> + if ( addr . is_v6 ( ) ) continue ; <nl> uint16_t port = r . endpoint ( ) . port ( ) ; <nl> resolved_addresses . emplace_back ( addr . to_string ( ) ) ; <nl> is_loopback = is_loopback & & addr . is_loopback ( ) ; <nl>
fix ignore ipv6
EOSIO/eos
e417f2f55bafef28c89d2a3e23356d1b7c270e76
2018-07-06T08:43:56Z
mmm a / imgui . h <nl> ppp b / imgui . h <nl> namespace ImGui <nl> / / - 1 . Call BeginTable ( ) <nl> / / - 2 . Optionally call TableSetupColumn ( ) to submit column name / flags / defaults <nl> / / - 3 . Optionally call TableSetupScrollFreeze ( ) to request scroll freezing of columns / rows <nl> - / / - 4 . Optionally call TableAutoHeaders ( ) to submit a header row ( names will be pulled from data submitted to TableSetupColumns ) <nl> + / / - 4 . Optionally call TableHeadersRow ( ) to submit a header row ( names will be pulled from data submitted to TableSetupColumns ) <nl> / / - 4 . Populate contents <nl> / / - In most situations you can use TableNextRow ( ) + TableSetColumnIndex ( ) to start appending into a column . <nl> / / - If you are using tables as a sort of grid , where every columns is holding the same type of contents , <nl> namespace ImGui <nl> / / Tables : Headers & Columns declaration <nl> / / - Use TableSetupScrollFreeze ( ) to lock columns ( from the right ) or rows ( from the top ) so they stay visible when scrolled . <nl> / / - Use TableSetupColumn ( ) to specify label , resizing policy , default width , id , various other flags etc . <nl> - / / Important : this will not display anything ! The name passed to TableSetupColumn ( ) is used by TableAutoHeaders ( ) and context - menus . <nl> - / / - Use TableAutoHeaders ( ) to create a row and automatically submit a TableHeader ( ) for each column . <nl> + / / Important : this will not display anything ! The name passed to TableSetupColumn ( ) is used by TableHeadersRow ( ) and context - menus . <nl> + / / - Use TableHeadersRow ( ) to create a row and automatically submit a TableHeader ( ) for each column . <nl> / / Headers are required to perform some interactions : reordering , sorting , context menu ( FIXME - TABLE : context menu should work without ! ) <nl> / / - You may manually submit headers using TableNextRow ( ) + TableHeader ( ) calls , but this is only useful in some advanced cases ( e . g . adding custom widgets in header row ) . <nl> IMGUI_API void TableSetupScrollFreeze ( int columns , int rows ) ; <nl> IMGUI_API void TableSetupColumn ( const char * label , ImGuiTableColumnFlags flags = 0 , float init_width_or_weight = - 1 . 0f , ImU32 user_id = 0 ) ; <nl> - IMGUI_API void TableAutoHeaders ( ) ; / / submit all headers cells based on data provided to TableSetupColumn ( ) + submit context menu <nl> + IMGUI_API void TableHeadersRow ( ) ; / / submit all headers cells based on data provided to TableSetupColumn ( ) + submit context menu <nl> IMGUI_API void TableHeader ( const char * label ) ; / / submit one header cell manually ( rarely used ) <nl> / / Tables : Miscellaneous functions <nl> / / - Most functions taking ' int column_n ' treat the default value of - 1 as the same as passing the current column index <nl> namespace ImGui <nl> / / When ' SpecsDirty = = true ' you should sort your data . It will be true when sorting specs have changed since last call , or the first time . <nl> / / Make sure to set ' SpecsDirty = false ' after sorting , else you may wastefully sort your data every frame ! <nl> / / Lifetime : don ' t hold on this pointer over multiple frames or past any subsequent call to BeginTable ( ) . <nl> + IMGUI_API int TableGetColumnCount ( ) ; / / return number of columns ( value passed to BeginTable ) <nl> IMGUI_API const char * TableGetColumnName ( int column_n = - 1 ) ; / / return NULL if column didn ' t have a name declared by TableSetupColumn ( ) . Pass - 1 to use current column . <nl> IMGUI_API bool TableGetColumnIsVisible ( int column_n = - 1 ) ; / / return true if column is visible . Same value is also returned by TableNextCell ( ) and TableSetColumnIndex ( ) . Pass - 1 to use current column . <nl> IMGUI_API bool TableGetColumnIsSorted ( int column_n = - 1 ) ; / / return true if column is included in the sort specs . Rarely used , can be useful to tell if a data change should trigger resort . Equivalent to test ImGuiTableSortSpecs ' s - > ColumnsMask & ( 1 < < column_n ) . Pass - 1 to use current column . <nl> enum ImGuiTableFlags_ <nl> / / Features <nl> ImGuiTableFlags_None = 0 , <nl> ImGuiTableFlags_Resizable = 1 < < 0 , / / Allow resizing columns . <nl> - ImGuiTableFlags_Reorderable = 1 < < 1 , / / Allow reordering columns ( need calling TableSetupColumn ( ) + TableAutoHeaders ( ) or TableHeaders ( ) to display headers ) <nl> + ImGuiTableFlags_Reorderable = 1 < < 1 , / / Allow reordering columns ( need calling TableSetupColumn ( ) + TableHeadersRow ( ) to display headers ) <nl> ImGuiTableFlags_Hideable = 1 < < 2 , / / Allow hiding columns ( with right - click on header ) ( FIXME - TABLE : allow without headers ) . <nl> ImGuiTableFlags_Sortable = 1 < < 3 , / / Allow sorting on one column ( sort_specs_count will always be = = 1 ) . Call TableGetSortSpecs ( ) to obtain sort specs . <nl> ImGuiTableFlags_MultiSortable = 1 < < 4 , / / Allow sorting on multiple columns by holding Shift ( sort_specs_count may be > 1 ) . Call TableGetSortSpecs ( ) to obtain sort specs . <nl> mmm a / imgui_demo . cpp <nl> ppp b / imgui_demo . cpp <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " AAA " , ImGuiTableColumnFlags_WidthFixed ) ; / / | ImGuiTableColumnFlags_NoResize ) ; <nl> ImGui : : TableSetupColumn ( " BBB " , ImGuiTableColumnFlags_WidthFixed ) ; <nl> ImGui : : TableSetupColumn ( " CCC " , ImGuiTableColumnFlags_WidthStretch ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 5 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " DDD " , ImGuiTableColumnFlags_WidthStretch ) ; <nl> ImGui : : TableSetupColumn ( " EEE " , ImGuiTableColumnFlags_WidthStretch ) ; <nl> ImGui : : TableSetupColumn ( " FFF " , ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 5 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> <nl> if ( ImGui : : BeginTable ( " # # table1 " , 3 , flags ) ) <nl> { <nl> - / / Submit columns name with TableSetupColumn ( ) and call TableAutoHeaders ( ) to create a row with a header in each column . <nl> + / / Submit columns name with TableSetupColumn ( ) and call TableHeadersRow ( ) to create a row with a header in each column . <nl> / / ( Later we will show how TableSetupColumn ( ) has other uses , optional flags , sizing weight etc . ) <nl> ImGui : : TableSetupColumn ( " One " ) ; <nl> ImGui : : TableSetupColumn ( " Two " ) ; <nl> ImGui : : TableSetupColumn ( " Three " ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 6 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " One " ) ; <nl> ImGui : : TableSetupColumn ( " Two " ) ; <nl> ImGui : : TableSetupColumn ( " Three " ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 6 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " One " , ImGuiTableColumnFlags_None ) ; <nl> ImGui : : TableSetupColumn ( " Two " , ImGuiTableColumnFlags_None ) ; <nl> ImGui : : TableSetupColumn ( " Three " , ImGuiTableColumnFlags_None ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> ImGuiListClipper clipper ; <nl> clipper . Begin ( 1000 ) ; <nl> while ( clipper . Step ( ) ) <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " Four " , ImGuiTableColumnFlags_None ) ; <nl> ImGui : : TableSetupColumn ( " Five " , ImGuiTableColumnFlags_None ) ; <nl> ImGui : : TableSetupColumn ( " Six " , ImGuiTableColumnFlags_None ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 20 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> { <nl> for ( int column = 0 ; column < column_count ; column + + ) <nl> ImGui : : TableSetupColumn ( column_names [ column ] , column_flags [ column ] ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 8 ; row + + ) <nl> { <nl> ImGui : : Indent ( 2 . 0f ) ; / / Add some indentation to demonstrate usage of per - column IndentEnable / IndentDisable flags . <nl> static void ShowDemoWindowTables ( ) <nl> { <nl> ImGui : : TableSetupColumn ( " A0 " ) ; <nl> ImGui : : TableSetupColumn ( " A1 " ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> <nl> ImGui : : TableNextRow ( ) ; ImGui : : Text ( " A0 Cell 0 " ) ; <nl> { <nl> static void ShowDemoWindowTables ( ) <nl> { <nl> ImGui : : TableSetupColumn ( " B0 " ) ; <nl> ImGui : : TableSetupColumn ( " B1 " ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> <nl> ImGui : : TableNextRow ( ImGuiTableRowFlags_None , rows_height ) ; <nl> ImGui : : Text ( " B0 Cell 0 " ) ; <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " Name " , ImGuiTableColumnFlags_NoHide ) ; <nl> ImGui : : TableSetupColumn ( " Size " , ImGuiTableColumnFlags_WidthFixed , ImGui : : GetFontSize ( ) * 6 ) ; <nl> ImGui : : TableSetupColumn ( " Type " , ImGuiTableColumnFlags_WidthFixed , ImGui : : GetFontSize ( ) * 10 ) ; <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> <nl> / / Simple storage to output a dummy file - system . <nl> struct MyTreeNode <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TreePop ( ) ; <nl> } <nl> <nl> - / / Demonstrate using TableHeader ( ) calls instead of TableAutoHeaders ( ) <nl> + / / Demonstrate using TableHeader ( ) calls instead of TableHeadersRow ( ) <nl> if ( open_action ! = - 1 ) <nl> ImGui : : SetNextItemOpen ( open_action ! = 0 ) ; <nl> if ( ImGui : : TreeNode ( " Custom headers " ) ) <nl> static void ShowDemoWindowTables ( ) <nl> / / FIXME : It would be nice to actually demonstrate full - featured selection using those checkbox . <nl> static bool column_selected [ 3 ] = { } ; <nl> <nl> - / / Instead of calling TableAutoHeaders ( ) we ' ll submit custom headers ourselves <nl> + / / Instead of calling TableHeadersRow ( ) we ' ll submit custom headers ourselves <nl> ImGui : : TableNextRow ( ImGuiTableRowFlags_Headers ) ; <nl> for ( int column = 0 ; column < COLUMNS_COUNT ; column + + ) <nl> { <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TreePop ( ) ; <nl> } <nl> <nl> - / / Demonstrate creating custom context menus inside columns , while playing it nice with context menus provided by TableHeader ( ) / TableAutoHeaders ( ) <nl> + / / Demonstrate creating custom context menus inside columns , while playing it nice with context menus provided by TableHeadersRow ( ) / TableHeader ( ) <nl> if ( open_action ! = - 1 ) <nl> ImGui : : SetNextItemOpen ( open_action ! = 0 ) ; <nl> if ( ImGui : : TreeNode ( " Context menus " ) ) <nl> { <nl> - HelpMarker ( " By default , TableHeader ( ) / TableAutoHeaders ( ) will open a context - menu on right - click . " ) ; <nl> + HelpMarker ( " By default , TableHeadersRow ( ) / TableHeader ( ) will open a context - menu on right - click . " ) ; <nl> ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders ; <nl> const int COLUMNS_COUNT = 3 ; <nl> if ( ImGui : : BeginTable ( " # # table1 " , COLUMNS_COUNT , flags ) ) <nl> static void ShowDemoWindowTables ( ) <nl> ImGui : : TableSetupColumn ( " Three " ) ; <nl> <nl> / / Context Menu 1 : right - click on header ( including empty section after the third column ! ) should open Default Table Popup <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> for ( int row = 0 ; row < 4 ; row + + ) <nl> { <nl> ImGui : : TableNextRow ( ) ; <nl> static void ShowDemoWindowTables ( ) <nl> } <nl> <nl> / / Display data <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> ImGuiListClipper clipper ; <nl> clipper . Begin ( items . Size ) ; <nl> while ( clipper . Step ( ) ) <nl> static void ShowDemoWindowTables ( ) <nl> <nl> / / Show headers <nl> if ( show_headers ) <nl> - ImGui : : TableAutoHeaders ( ) ; <nl> + ImGui : : TableHeadersRow ( ) ; <nl> <nl> / / Show data <nl> / / FIXME - TABLE FIXME - NAV : How we can get decent up / down even though we have the buttons here ? <nl> mmm a / imgui_tables . cpp <nl> ppp b / imgui_tables . cpp <nl> <nl> / / | TableUpdateBorders ( ) - detect hovering columns for resize , ahead of contents submission <nl> / / | TableDrawContextMenu ( ) - draw right - click context menu <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - / / - TableAutoHeaders ( ) or TableHeader ( ) user submit a headers row ( optional ) <nl> + / / - TableHeadersRow ( ) or TableHeader ( ) user submit a headers row ( optional ) <nl> / / | TableSortSpecsClickColumn ( ) - when left - clicked : alter sort order and sort direction <nl> / / | TableOpenContextMenu ( ) - when right - clicked : trigger opening of the default context menu <nl> / / - TableGetSortSpecs ( ) user queries updated sort specs ( optional , generally after submitting headers ) <nl> - / / - TableNextRow ( ) / TableNextCell ( ) user begin into the first row , also automatically called by TableAutoHeaders ( ) <nl> + / / - TableNextRow ( ) / TableNextCell ( ) user begin into the first row , also automatically called by TableHeadersRow ( ) <nl> / / | TableEndCell ( ) - close existing cell if not the first time <nl> / / | TableBeginCell ( ) - enter into current cell <nl> / / - [ . . . ] user emit contents <nl> bool ImGui : : TableNextCell ( ) <nl> return ( table - > VisibleUnclippedMaskByIndex & ( ( ImU64 ) 1 < < column_n ) ) ! = 0 ; <nl> } <nl> <nl> + int ImGui : : TableGetColumnCount ( ) <nl> + { <nl> + ImGuiContext & g = * GImGui ; <nl> + ImGuiTable * table = g . CurrentTable ; <nl> + return table ? table - > ColumnsCount : 0 ; <nl> + } <nl> + <nl> const char * ImGui : : TableGetColumnName ( int column_n ) <nl> { <nl> ImGuiContext & g = * GImGui ; <nl> void ImGui : : TableOpenContextMenu ( ImGuiTable * table , int column_n ) <nl> / / This is a helper to output TableHeader ( ) calls based on the column names declared in TableSetupColumn ( ) . <nl> / / The intent is that advanced users willing to create customized headers would not need to use this helper <nl> / / and can create their own ! For example : TableHeader ( ) may be preceeded by Checkbox ( ) or other custom widgets . <nl> - void ImGui : : TableAutoHeaders ( ) <nl> + / / See ' Demo - > Tables - > Custom headers ' for a demonstration of implementing a custom version of this . <nl> + void ImGui : : TableHeadersRow ( ) <nl> { <nl> ImGuiStyle & style = ImGui : : GetStyle ( ) ; <nl> <nl> ImGuiContext & g = * GImGui ; <nl> ImGuiTable * table = g . CurrentTable ; <nl> - IM_ASSERT ( table ! = NULL & & " Need to call TableAutoHeaders ( ) after BeginTable ( ) ! " ) ; <nl> - const int columns_count = table - > ColumnsCount ; <nl> + IM_ASSERT ( table ! = NULL & & " Need to call TableHeadersRow ( ) after BeginTable ( ) ! " ) ; <nl> <nl> / / Calculate row height ( for the unlikely case that labels may be are multi - line ) <nl> - float row_y1 = GetCursorScreenPos ( ) . y ; <nl> + / / If we didn ' t do that , uneven header height would work but their highlight won ' t cover the full row height . <nl> float row_height = GetTextLineHeight ( ) ; <nl> + const float row_y1 = GetCursorScreenPos ( ) . y ; <nl> + const int columns_count = TableGetColumnCount ( ) ; <nl> for ( int column_n = 0 ; column_n < columns_count ; column_n + + ) <nl> if ( TableGetColumnIsVisible ( column_n ) ) <nl> row_height = ImMax ( row_height , CalcTextSize ( TableGetColumnName ( column_n ) ) . y ) ; <nl> void ImGui : : TableAutoHeaders ( ) <nl> if ( ! TableSetColumnIndex ( column_n ) ) <nl> continue ; <nl> <nl> - const char * name = TableGetColumnName ( column_n ) ; <nl> - <nl> / / [ DEBUG ] Test custom user elements <nl> # if 0 <nl> if ( column_n < 2 ) <nl> void ImGui : : TableAutoHeaders ( ) <nl> # endif <nl> <nl> / / Push an id to allow unnamed labels ( generally accidental , but let ' s behave nicely with them ) <nl> - / / - in your own code you may omit the PushID / PopID all - together , provided you know you know they won ' t collide <nl> + / / - in your own code you may omit the PushID / PopID all - together , provided you know they won ' t collide <nl> / / - table - > InstanceCurrent is only > 0 when we use multiple BeginTable / EndTable calls with same identifier . <nl> + const char * name = TableGetColumnName ( column_n ) ; <nl> PushID ( table - > InstanceCurrent * table - > ColumnsCount + column_n ) ; <nl> TableHeader ( name ) ; <nl> PopID ( ) ; <nl> } <nl> <nl> - / / FIXME - TABLE : This is not user - land code any more + need to explain WHY this is here ! ( added in fa88f023 ) <nl> - / / window - > SkipItems = table - > HostSkipItems ; <nl> - <nl> / / Allow opening popup from the right - most section after the last column . <nl> - / / ( We don ' t actually need to use ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally <nl> - / / not required anymore . . because popup opening code tends to be reacting on IsMouseReleased ( ) and the click would <nl> - / / already have closed any other popups ! ) <nl> / / FIXME - TABLE : TableOpenContextMenu ( ) is not public yet . <nl> + ImVec2 mouse_pos = ImGui : : GetMousePos ( ) ; <nl> if ( IsMouseReleased ( 1 ) & & TableGetHoveredColumn ( ) = = columns_count ) <nl> - if ( g . IO . MousePos . y > = row_y1 & & g . IO . MousePos . y < row_y1 + row_height ) <nl> + if ( mouse_pos . y > = row_y1 & & mouse_pos . y < row_y1 + row_height ) <nl> TableOpenContextMenu ( table , - 1 ) ; / / Will open a non - column - specific popup . <nl> } <nl> <nl> void ImGui : : TableHeader ( const char * label ) <nl> return ; <nl> <nl> ImGuiTable * table = g . CurrentTable ; <nl> - IM_ASSERT ( table ! = NULL & & " Need to call TableAutoHeaders ( ) after BeginTable ( ) ! " ) ; <nl> + IM_ASSERT ( table ! = NULL & & " Need to call TableHeader ( ) after BeginTable ( ) ! " ) ; <nl> IM_ASSERT ( table - > CurrentColumn ! = - 1 ) ; <nl> const int column_n = table - > CurrentColumn ; <nl> ImGuiTableColumn * column = & table - > Columns [ column_n ] ; <nl>
Tables : ( Breaking ) Rename TableAutoHeaders ( ) to TableHeadersRow ( ) + added TableGetColumnCount ( ) .
ocornut/imgui
9b37087fbee0d8b9a33bb4ec456a5a349ba1a18b
2020-12-04T18:15:23Z
mmm a / tensorflow / python / BUILD <nl> ppp b / tensorflow / python / BUILD <nl> py_library ( <nl> " / / tensorflow / core : protos_all_py " , <nl> " / / tensorflow / python / eager : context " , <nl> " / / tensorflow / python / eager : custom_gradient " , <nl> + " / / tensorflow / python / eager : tape " , <nl> " / / tensorflow / python / eager : tensor " , <nl> ] , <nl> ) <nl> py_library ( <nl> " : util " , <nl> " : variable_scope " , <nl> " : variables " , <nl> + " / / tensorflow / python / eager : context " , <nl> " / / third_party / py / numpy " , <nl> " @ six_archive / / : six " , <nl> ] , <nl> py_test ( <nl> deps = [ <nl> " : client_testlib " , <nl> " : framework_for_generated_wrappers " , <nl> + " : framework_test_lib " , <nl> " : init_ops " , <nl> " : layers " , <nl> " : math_ops " , <nl> py_test ( <nl> " : array_ops " , <nl> " : client_testlib " , <nl> " : framework_for_generated_wrappers " , <nl> + " : framework_test_lib " , <nl> " : layers " , <nl> " : math_ops " , <nl> " : nn_ops " , <nl> py_test ( <nl> deps = [ <nl> " : client_testlib " , <nl> " : framework_for_generated_wrappers " , <nl> + " : framework_test_lib " , <nl> " : layers " , <nl> " : math_ops " , <nl> " : nn_ops " , <nl> py_test ( <nl> srcs_version = " PY2AND3 " , <nl> deps = [ <nl> " : client_testlib " , <nl> + " : framework_test_lib " , <nl> " : layers " , <nl> " : random_ops " , <nl> ] , <nl> cuda_py_test ( <nl> " : array_ops " , <nl> " : client_testlib " , <nl> " : framework_for_generated_wrappers " , <nl> + " : framework_test_lib " , <nl> " : layers " , <nl> " : math_ops " , <nl> " : random_ops " , <nl> mmm a / tensorflow / python / layers / base . py <nl> ppp b / tensorflow / python / layers / base . py <nl> <nl> import numpy as np <nl> import six <nl> <nl> + from tensorflow . python . eager import context <nl> from tensorflow . python . estimator import util as estimator_util <nl> from tensorflow . python . framework import ops <nl> from tensorflow . python . framework import dtypes <nl> def __init__ ( self , trainable = True , name = None , <nl> self . _per_input_updates = { } <nl> self . dtype = dtypes . as_dtype ( dtype ) . name <nl> self . input_spec = None <nl> + self . _compute_previous_mask = ( ' mask ' in estimator_util . fn_args ( self . call ) <nl> + or hasattr ( self , ' compute_mask ' ) ) <nl> <nl> # These lists will be filled via successive calls <nl> # to self . _add_inbound_node ( ) . <nl> def variables ( self ) : <nl> <nl> @ property <nl> def updates ( self ) : <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . updates not supported in Eager mode . ' ) <nl> return self . _updates <nl> <nl> def add_update ( self , updates , inputs = None ) : <nl> def add_update ( self , updates , inputs = None ) : <nl> match the ` inputs ` argument passed to the ` __call__ ` method at the time <nl> the updates are created . If ` None ` is passed , the updates are assumed <nl> to be unconditional , and will apply across all dataflows of the layer . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . add_update not supported in Eager mode . ' ) <nl> updates = _to_list ( updates ) <nl> if not updates : <nl> return <nl> def get_updates_for ( self , inputs ) : <nl> <nl> Returns : <nl> List of update ops of the layer that depend on ` inputs ` . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . get_updates_for not supported in Eager mode . ' ) <nl> if inputs is not None : <nl> inputs = _to_list ( inputs ) <nl> if not inputs : <nl> def get_updates_for ( self , inputs ) : <nl> <nl> @ property <nl> def losses ( self ) : <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . losses not supported in Eager mode . ' ) <nl> return self . _losses <nl> <nl> def add_loss ( self , losses , inputs = None ) : <nl> def add_loss ( self , losses , inputs = None ) : <nl> the losses are created . If ` None ` is passed , the losses are assumed <nl> to be unconditional , and will apply across all dataflows of the layer <nl> ( e . g . weight regularization losses ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . add_loss not supported in Eager mode . ' ) <nl> losses = _to_list ( losses ) <nl> if not losses : <nl> return <nl> def get_losses_for ( self , inputs ) : <nl> <nl> Returns : <nl> List of loss tensors of the layer that depend on ` inputs ` . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . get_losses_for not supported in Eager mode . ' ) <nl> if inputs is not None : <nl> inputs = _to_list ( inputs ) <nl> if not inputs : <nl> def add_variable ( self , name , shape , dtype = None , <nl> <nl> Returns : <nl> The created variable . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode with regularizers . <nl> " " " <nl> + # Note that we currently don ' t support variable regularization in Eager <nl> + # mode . An alternative is for users to directly compute these losses before <nl> + # performing a backward pass . <nl> + if regularizer is not None and context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Variable regularization not supported in Eager mode . ' ) <nl> if dtype is None : <nl> dtype = self . dtype <nl> existing_variables = set ( tf_variables . global_variables ( ) ) <nl> <nl> self . _set_scope ( None ) <nl> <nl> - with vs . variable_scope ( self . _scope , <nl> - reuse = self . built or self . _reuse ) as scope : <nl> + vs_reuse = ( ( self . built or self . _reuse ) <nl> + if context . in_graph_mode ( ) else vs . AUTO_REUSE ) <nl> + with vs . variable_scope ( self . _scope , reuse = vs_reuse ) as scope : <nl> with ops . name_scope ( scope . original_name_scope ) : <nl> variable = vs . get_variable ( name , <nl> shape = shape , <nl> def __call__ ( self , inputs , * args , * * kwargs ) : <nl> " " " <nl> self . _set_scope ( kwargs . pop ( ' scope ' , None ) ) <nl> <nl> + in_graph_mode = context . in_graph_mode ( ) <nl> # Ensure the Layer , if being reused , is working with inputs from <nl> # the same graph as where it was created . <nl> - try : <nl> - ops . _get_graph_from_inputs ( nest . flatten ( inputs ) , graph = self . graph ) # pylint : disable = protected - access <nl> - except ValueError as e : <nl> - raise ValueError ( ' Input graph and Layer graph are not the same : % s ' % e ) <nl> + if in_graph_mode : <nl> + try : <nl> + ops . _get_graph_from_inputs ( nest . flatten ( inputs ) , graph = self . graph ) # pylint : disable = protected - access <nl> + except ValueError as e : <nl> + raise ValueError ( ' Input graph and Layer graph are not the same : % s ' % e ) <nl> + user_kwargs = copy . copy ( kwargs ) <nl> <nl> # Handle Keras mask propagation from previous layer to current layer . <nl> - previous_mask = _collect_previous_mask ( inputs ) <nl> - user_kwargs = copy . copy ( kwargs ) <nl> - if not _is_all_none ( previous_mask ) : <nl> - # The previous layer generated a mask , which we should use as default <nl> - # for any " mask " argument in ` call ` . <nl> - if ' mask ' in estimator_util . fn_args ( self . call ) : <nl> - if ' mask ' not in kwargs : <nl> - # If mask is explicitly passed to __call__ , <nl> - # we should override the default mask . <nl> - kwargs [ ' mask ' ] = previous_mask <nl> - <nl> - with vs . variable_scope ( self . _scope , <nl> - reuse = self . built or self . _reuse ) as scope : <nl> + previous_mask = None <nl> + if ( not hasattr ( self , ' _compute_previous_mask ' ) or <nl> + self . _compute_previous_mask ) : <nl> + previous_mask = _collect_previous_mask ( inputs ) <nl> + if ( ' mask ' in estimator_util . fn_args ( self . call ) and <nl> + ' mask ' not in kwargs and <nl> + not _is_all_none ( previous_mask ) ) : <nl> + # The previous layer generated a mask , and mask was not explicitly pass <nl> + # to __call__ , hence we set previous_mask as the default value . <nl> + kwargs [ ' mask ' ] = previous_mask <nl> + <nl> + vs_reuse = ( ( self . built or self . _reuse ) <nl> + if context . in_graph_mode else vs . AUTO_REUSE ) <nl> + with vs . variable_scope ( self . _scope , reuse = vs_reuse ) as scope : <nl> with ops . name_scope ( scope . original_name_scope ) : <nl> if not self . built : <nl> + if not in_graph_mode : <nl> + # Activity regularization is unsupported in Eager mode . <nl> + if hasattr ( self , <nl> + ' activity_regularizer ' ) and self . activity_regularizer : <nl> + raise ValueError ( ' activity_regularizer currently unsupported in ' <nl> + ' Eager mode . Found an activity_regularizer in ' <nl> + ' % s ( % s ) . ' % ( self . __class__ . __name__ , self ) ) <nl> + # TODO ( agarwal ) : support _keras_history in Eager mode . <nl> + for x in _to_list ( inputs ) : <nl> + if hasattr ( x , ' _keras_history ' ) : <nl> + raise ValueError ( ' _keras_history currently unsupported in ' <nl> + ' Eager mode . Found _keras_history in % s while ' <nl> + ' executing __call__ for % s ( % s ) ' % <nl> + ( x , self . __class_ . __name__ , self ) ) <nl> + <nl> # Check input assumptions set before layer building , e . g . input rank . <nl> self . _assert_input_compatibility ( inputs ) <nl> input_list = nest . flatten ( inputs ) <nl> def __call__ ( self , inputs , * args , * * kwargs ) : <nl> if ' scope ' in estimator_util . fn_args ( self . call ) : <nl> kwargs [ ' scope ' ] = scope <nl> # Check input assumptions set after layer building , e . g . input shape . <nl> - self . _assert_input_compatibility ( inputs ) <nl> + if in_graph_mode : <nl> + self . _assert_input_compatibility ( inputs ) <nl> outputs = self . call ( inputs , * args , * * kwargs ) <nl> <nl> if outputs is None : <nl> raise ValueError ( ' A layer \ ' s ` call ` method should return a Tensor ' <nl> ' or a list of Tensors , not None . ' ) <nl> <nl> - # Apply activity regularization . <nl> - # Note that it should be applied every time the layer creates a new <nl> - # output , since it is output - specific . <nl> - if hasattr ( self , ' activity_regularizer ' ) and self . activity_regularizer : <nl> - output_list = _to_list ( outputs ) <nl> - for output in output_list : <nl> - with ops . name_scope ( ' ActivityRegularizer ' ) : <nl> - activity_regularization = self . activity_regularizer ( output ) <nl> - self . add_loss ( activity_regularization ) <nl> - _add_elements_to_collection ( <nl> - activity_regularization , ops . GraphKeys . REGULARIZATION_LOSSES ) <nl> + if in_graph_mode : <nl> + # Apply activity regularization . <nl> + # Note that it should be applied every time the layer creates a new <nl> + # output , since it is output - specific . <nl> + if hasattr ( self , <nl> + ' activity_regularizer ' ) and self . activity_regularizer : <nl> + output_list = _to_list ( outputs ) <nl> + for output in output_list : <nl> + with ops . name_scope ( ' ActivityRegularizer ' ) : <nl> + activity_regularization = self . activity_regularizer ( output ) <nl> + self . add_loss ( activity_regularization ) <nl> + _add_elements_to_collection ( activity_regularization , <nl> + ops . GraphKeys . REGULARIZATION_LOSSES ) <nl> <nl> # Handle mask computation and propagation to the next layer . <nl> if hasattr ( self , ' compute_mask ' ) : <nl> def __call__ ( self , inputs , * args , * * kwargs ) : <nl> else : <nl> outputs . _keras_mask = output_mask # pylint : disable = protected - access <nl> <nl> - # If all input tensors have history metadata , <nl> - # we update the output tensors <nl> - # with corresponding history metadata , thus eventually allowing to use <nl> - # these tensors to instantiate a Network . <nl> - if _have_all_keras_metadata ( inputs ) : <nl> - # If the layer returns tensors from its inputs , unmodified , <nl> - # we copy them to avoid loss of tensor metadata . <nl> - output_ls = _to_list ( outputs ) <nl> - inputs_ls = _to_list ( inputs ) <nl> - output_ls_copy = [ ] <nl> - for x in output_ls : <nl> - if x in inputs_ls : <nl> - with ops . name_scope ( scope . original_name_scope ) : <nl> - x = array_ops . identity ( x ) <nl> - output_ls_copy . append ( x ) <nl> - if len ( output_ls_copy ) = = 1 : <nl> - outputs = output_ls_copy [ 0 ] <nl> - else : <nl> - outputs = output_ls_copy <nl> + if in_graph_mode : <nl> + # If all input tensors have history metadata , <nl> + # we update the output tensors <nl> + # with corresponding history metadata , thus eventually allowing to use <nl> + # these tensors to instantiate a Network . <nl> + if _have_all_keras_metadata ( inputs ) : <nl> + # If the layer returns tensors from its inputs , unmodified , <nl> + # we copy them to avoid loss of tensor metadata . <nl> + output_ls = _to_list ( outputs ) <nl> + inputs_ls = _to_list ( inputs ) <nl> + output_ls_copy = [ ] <nl> + for x in output_ls : <nl> + if x in inputs_ls : <nl> + with ops . name_scope ( scope . original_name_scope ) : <nl> + x = array_ops . identity ( x ) <nl> + output_ls_copy . append ( x ) <nl> + if len ( output_ls_copy ) = = 1 : <nl> + outputs = output_ls_copy [ 0 ] <nl> + else : <nl> + outputs = output_ls_copy <nl> <nl> - # Add an inbound node to the layer , so it can keep track of this call . <nl> - # This updates the layer history of the output tensor ( s ) . <nl> - self . _add_inbound_node ( <nl> - input_tensors = inputs , <nl> - output_tensors = outputs , <nl> - arguments = user_kwargs ) <nl> + # Add an inbound node to the layer , so it can keep track of this call . <nl> + # This updates the layer history of the output tensor ( s ) . <nl> + self . _add_inbound_node ( <nl> + input_tensors = inputs , output_tensors = outputs , arguments = user_kwargs ) <nl> + <nl> + # Update global default collections . <nl> + _add_elements_to_collection ( self . updates , ops . GraphKeys . UPDATE_OPS ) <nl> <nl> - # Update global default collections . <nl> - _add_elements_to_collection ( self . updates , ops . GraphKeys . UPDATE_OPS ) <nl> self . built = True <nl> return outputs <nl> <nl> @ property <nl> def graph ( self ) : <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . graph not supported in Eager mode . ' ) <nl> return self . _graph <nl> <nl> def __deepcopy__ ( self , memo ) : <nl> def _add_inbound_node ( self , <nl> arguments : dictionary of keyword arguments that were passed to the <nl> ` call ` method of the layer at the call that created the node . <nl> " " " <nl> + assert context . in_graph_mode ( ) <nl> input_tensors = _to_list ( input_tensors ) <nl> output_tensors = _to_list ( output_tensors ) <nl> <nl> def _get_node_attribute_at_index ( self , node_index , attr , attr_name ) : <nl> The layer ' s attribute ` attr ` at the node of index ` node_index ` . <nl> <nl> Raises : <nl> - RuntimeError : If the layer has no inbound nodes . <nl> + RuntimeError : If the layer has no inbound nodes , or if called in Eager <nl> + mode . <nl> ValueError : If the index provided does not match any node . <nl> " " " <nl> + assert context . in_graph_mode ( ) <nl> if not self . inbound_nodes : <nl> raise RuntimeError ( ' The layer has never been called ' <nl> ' and thus has no defined ' + attr_name + ' . ' ) <nl> def get_input_shape_at ( self , node_index ) : <nl> Returns : <nl> A shape tuple <nl> ( or list of shape tuples if the layer has multiple inputs ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( <nl> + ' Layer . get_input_shape_at not supported in Eager mode . ' ) <nl> return self . _get_node_attribute_at_index ( node_index , ' input_shapes ' , <nl> ' input shape ' ) <nl> <nl> def get_output_shape_at ( self , node_index ) : <nl> Returns : <nl> A shape tuple <nl> ( or list of shape tuples if the layer has multiple outputs ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( <nl> + ' Layer . get_output_shape_at not supported in Eager mode . ' ) <nl> return self . _get_node_attribute_at_index ( node_index , ' output_shapes ' , <nl> ' output shape ' ) <nl> <nl> def get_input_at ( self , node_index ) : <nl> <nl> Returns : <nl> A tensor ( or list of tensors if the layer has multiple inputs ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . get_input_at not supported in Eager mode . ' ) <nl> return self . _get_node_attribute_at_index ( node_index , ' input_tensors ' , <nl> ' input ' ) <nl> <nl> def get_output_at ( self , node_index ) : <nl> <nl> Returns : <nl> A tensor ( or list of tensors if the layer has multiple outputs ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . get_output_at not supported in Eager mode . ' ) <nl> return self . _get_node_attribute_at_index ( node_index , ' output_tensors ' , <nl> ' output ' ) <nl> <nl> def input ( self ) : <nl> Raises : <nl> AttributeError : if the layer is connected to <nl> more than one incoming layers . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> + AttributeError : If no inbound nodes are found . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . input not supported in Eager mode . ' ) <nl> if not self . inbound_nodes : <nl> raise AttributeError ( ' Layer ' + self . name + <nl> ' is not connected , no input to return . ' ) <nl> def output ( self ) : <nl> i . e . if it is connected to one incoming layer . <nl> <nl> Returns : <nl> - Output tensor or list of output tensors . <nl> + Output tensor or list of output tensors . <nl> <nl> Raises : <nl> - AttributeError : if the layer is connected to <nl> - more than one incoming layers . <nl> + AttributeError : if the layer is connected to more than one incoming <nl> + layers . <nl> + RuntimeError : if called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . output not supported in Eager mode . ' ) <nl> if not self . inbound_nodes : <nl> raise AttributeError ( ' Layer ' + self . name + ' has no inbound nodes . ' ) <nl> return self . _get_node_attribute_at_index ( 0 , ' output_tensors ' , ' output ' ) <nl> def input_shape ( self ) : <nl> <nl> Raises : <nl> AttributeError : if the layer has no defined input_shape . <nl> + RuntimeError : if called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . input_shape not supported in Eager mode . ' ) <nl> if not self . inbound_nodes : <nl> raise AttributeError ( ' The layer has never been called ' <nl> ' and thus has no defined input shape . ' ) <nl> def output_shape ( self ) : <nl> <nl> Raises : <nl> AttributeError : if the layer has no defined output shape . <nl> + RuntimeError : if called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Layer . output_shape not supported in Eager mode . ' ) <nl> if not self . inbound_nodes : <nl> raise AttributeError ( ' The layer has never been called ' <nl> ' and thus has no defined output shape . ' ) <nl> def _assert_input_compatibility ( self , inputs ) : <nl> if ndim ! = spec . ndim : <nl> raise ValueError ( ' Input ' + str ( input_index ) + ' of layer ' + <nl> self . name + ' is incompatible with the layer : ' <nl> - ' expected ndim = ' + str ( spec . ndim ) + ' , found ndim = ' <nl> - + str ( ndim ) + ' . Full shape received : ' + <nl> + ' expected ndim = ' + str ( spec . ndim ) + ' , found ndim = ' + <nl> + str ( ndim ) + ' . Full shape received : ' + <nl> str ( x . get_shape ( ) . as_list ( ) ) ) <nl> if spec . max_ndim is not None : <nl> ndim = x . get_shape ( ) . ndims <nl> class InputLayer ( Layer ) : <nl> sparse : Boolean , whether the placeholder created <nl> is meant to be sparse . <nl> name : Name of the layer ( string ) . <nl> + <nl> + Raises : <nl> + RuntimeError : If created in Eager mode . <nl> " " " <nl> <nl> def __init__ ( self , <nl> def __init__ ( self , <nl> input_tensor = None , <nl> sparse = False , <nl> name = None ) : <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' InputLayer not supported in Eager mode . ' ) <nl> super ( InputLayer , self ) . __init__ ( dtype = dtype , name = name ) <nl> self . built = True <nl> self . sparse = sparse <nl> def Input ( # pylint : disable = invalid - name <nl> Returns : <nl> A tensor : either a new placeholder ( with history metadata ) or <nl> ` tensor ` ( if passed ) , with added history metadata . <nl> + <nl> + Raises : <nl> + RuntimeError : If called in Eager mode . <nl> " " " <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Input not supported in Eager mode . ' ) <nl> input_layer = InputLayer ( <nl> input_shape = shape , <nl> batch_size = batch_size , <nl> class Network ( Layer ) : <nl> Methods : <nl> Network has the same methods as Layer . On top of it , it also has : <nl> - get_layer : retrieves a child layer by name or index in the graph . <nl> + <nl> + Raises : <nl> + RuntimeError : If created in Eager mode . <nl> " " " <nl> <nl> def __init__ ( self , inputs , outputs , name = None ) : # pylint : disable = super - init - not - called <nl> + # TODO ( agarwal ) : Make Network work in Eager mode . <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Network not supported in Eager mode . ' ) <nl> # Set layer name and scope <nl> if isinstance ( name , vs . VariableScope ) : <nl> base_name = name . name <nl> def __init__ ( self , inputs , outputs , name = None ) : # pylint : disable = super - init - no <nl> self . name = _unique_layer_name ( base_name ) <nl> self . _scope = next ( vs . variable_scope ( None , default_name = base_name ) . gen ) <nl> self . _base_name = base_name <nl> + self . _compute_previous_mask = ( ' mask ' in estimator_util . fn_args ( self . call ) <nl> + or hasattr ( self , ' compute_mask ' ) ) <nl> <nl> # This acts just like the ` trainable ` attribute of any layer instance . <nl> # It does not affect users of the underlying layers , only users of the <nl> def _to_list ( x ) : <nl> <nl> <nl> def _add_elements_to_collection ( elements , collection_list ) : <nl> + if context . in_eager_mode ( ) : <nl> + raise RuntimeError ( ' Using collections from Layers not supported in Eager ' <nl> + ' mode . Tried to add % s to % s ' % ( elements , <nl> + collection_list ) ) <nl> elements = _to_list ( elements ) <nl> collection_list = _to_list ( collection_list ) <nl> for name in collection_list : <nl> def _collect_previous_mask ( input_tensors ) : <nl> return masks [ 0 ] <nl> return masks <nl> <nl> + <nl> # A global dictionary mapping graph objects to an index of counters used <nl> # for various layer names in each graph . <nl> # Allows to give unique autogenerated names to layers , in a graph - specific way . <nl> mmm a / tensorflow / python / layers / base_test . py <nl> ppp b / tensorflow / python / layers / base_test . py <nl> <nl> <nl> import copy <nl> <nl> + from tensorflow . python . eager import context <nl> + from tensorflow . python . framework import constant_op <nl> + from tensorflow . python . framework import dtypes <nl> from tensorflow . python . framework import ops <nl> + from tensorflow . python . framework import test_util <nl> from tensorflow . python . layers import base as base_layers <nl> from tensorflow . python . layers import core as core_layers <nl> from tensorflow . python . ops import array_ops <nl> <nl> <nl> class BaseLayerTest ( test . TestCase ) : <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testLayerProperties ( self ) : <nl> layer = base_layers . Layer ( name = ' my_layer ' ) <nl> self . assertListEqual ( layer . variables , [ ] ) <nl> self . assertListEqual ( layer . trainable_variables , [ ] ) <nl> self . assertListEqual ( layer . non_trainable_variables , [ ] ) <nl> - self . assertListEqual ( layer . updates , [ ] ) <nl> - self . assertListEqual ( layer . losses , [ ] ) <nl> + if context . in_graph_mode ( ) : <nl> + # updates , losses only suppported in GRAPH mode <nl> + self . assertListEqual ( layer . updates , [ ] ) <nl> + self . assertListEqual ( layer . losses , [ ] ) <nl> self . assertEqual ( layer . built , False ) <nl> layer = base_layers . Layer ( name = ' my_layer ' , trainable = False ) <nl> self . assertEqual ( layer . trainable , False ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testAddWeight ( self ) : <nl> - with self . test_session ( ) : <nl> - layer = base_layers . Layer ( name = ' my_layer ' ) <nl> + layer = base_layers . Layer ( name = ' my_layer ' ) <nl> <nl> - # Test basic variable creation . <nl> - variable = layer . add_variable ( <nl> - ' my_var ' , [ 2 , 2 ] , initializer = init_ops . zeros_initializer ( ) ) <nl> - self . assertEqual ( variable . name , ' my_layer / my_var : 0 ' ) <nl> - self . assertListEqual ( layer . variables , [ variable ] ) <nl> - self . assertListEqual ( layer . trainable_variables , [ variable ] ) <nl> - self . assertListEqual ( layer . non_trainable_variables , [ ] ) <nl> - self . assertListEqual ( <nl> - layer . variables , <nl> - ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) <nl> - <nl> - # Test non - trainable variable creation . <nl> - # layer . add_variable should work even outside ` build ` and ` call ` . <nl> - variable_2 = layer . add_variable ( <nl> - ' non_trainable_var ' , [ 2 , 2 ] , <nl> - initializer = init_ops . zeros_initializer ( ) , <nl> - trainable = False ) <nl> - self . assertListEqual ( layer . variables , [ variable , variable_2 ] ) <nl> - self . assertListEqual ( layer . trainable_variables , [ variable ] ) <nl> - self . assertListEqual ( layer . non_trainable_variables , [ variable_2 ] ) <nl> - self . assertEqual ( <nl> - len ( ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) , 1 ) <nl> - <nl> - # Test with regularizer . <nl> + # Test basic variable creation . <nl> + variable = layer . add_variable ( <nl> + ' my_var ' , [ 2 , 2 ] , initializer = init_ops . zeros_initializer ( ) ) <nl> + self . assertEqual ( variable . name , ' my_layer / my_var : 0 ' ) <nl> + self . assertListEqual ( layer . variables , [ variable ] ) <nl> + self . assertListEqual ( layer . trainable_variables , [ variable ] ) <nl> + self . assertListEqual ( layer . non_trainable_variables , [ ] ) <nl> + self . assertListEqual ( layer . variables , <nl> + ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) <nl> + <nl> + # Test non - trainable variable creation . <nl> + # layer . add_variable should work even outside ` build ` and ` call ` . <nl> + variable_2 = layer . add_variable ( <nl> + ' non_trainable_var ' , [ 2 , 2 ] , <nl> + initializer = init_ops . zeros_initializer ( ) , <nl> + trainable = False ) <nl> + self . assertListEqual ( layer . variables , [ variable , variable_2 ] ) <nl> + self . assertListEqual ( layer . trainable_variables , [ variable ] ) <nl> + self . assertListEqual ( layer . non_trainable_variables , [ variable_2 ] ) <nl> + self . assertEqual ( <nl> + len ( ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) , 1 ) <nl> + <nl> + if context . in_graph_mode ( ) : <nl> + # regularizers only supported in GRAPH mode . <nl> regularizer = lambda x : math_ops . reduce_sum ( x ) * 1e - 3 <nl> variable = layer . add_variable ( <nl> ' reg_var ' , [ 2 , 2 ] , <nl> def testAddWeight ( self ) : <nl> regularizer = regularizer ) <nl> self . assertEqual ( len ( layer . losses ) , 1 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testGetVariable ( self ) : <nl> - with self . test_session ( ) : <nl> <nl> - class MyLayer ( base_layers . Layer ) : <nl> + class MyLayer ( base_layers . Layer ) : <nl> <nl> - def build ( self , input_shape ) : <nl> - self . my_var = self . add_variable ( <nl> - ' my_var ' , [ 2 , 2 ] , initializer = init_ops . zeros_initializer ( ) ) <nl> + def build ( self , input_shape ) : <nl> + self . my_var = self . add_variable ( <nl> + ' my_var ' , [ 2 , 2 ] , initializer = init_ops . zeros_initializer ( ) ) <nl> <nl> - def call ( self , inputs ) : <nl> - return inputs * 2 <nl> + def call ( self , inputs ) : <nl> + return inputs * 2 <nl> <nl> - layer = MyLayer ( name = ' my_layer ' ) <nl> - inputs = random_ops . random_uniform ( ( 5 , ) , seed = 1 ) <nl> - layer . apply ( inputs ) <nl> - layer . apply ( inputs ) <nl> - self . assertListEqual ( [ v . name for v in layer . variables ] , <nl> - [ ' my_layer / my_var : 0 ' ] ) <nl> - <nl> - # Creating a layer with no scope leads to lazy construction of <nl> - # the scope at apply ( ) time . It uses scope " < current scope > / base_name " <nl> - lazy_layer = MyLayer ( _reuse = True ) <nl> - with variable_scope . variable_scope ( ' new_scope ' ) : <nl> - # This should attempt to reuse ' my_var ' in ' new_scope ' <nl> - with self . assertRaisesRegexp ( <nl> - ValueError , r ' new_scope / my_layer / my_var does not exist ' ) : <nl> - lazy_layer . apply ( inputs ) <nl> - with variable_scope . variable_scope ( ' my_layer ' ) : <nl> - variable_scope . get_variable ( ' my_var ' , [ 2 , 2 ] ) <nl> - <nl> - # Smoke test : it runs . <nl> - lazy_layer . apply ( inputs ) <nl> - # The variables were created outside of the Layer , and <nl> - # reuse = True , so the Layer does not own them and they are not <nl> - # stored in its collection . <nl> - self . assertListEqual ( lazy_layer . variables , [ ] ) <nl> - self . assertEqual ( lazy_layer . _scope . name , ' new_scope / my_layer ' ) <nl> - <nl> - # Creating a layer with no scope leads to lazy construction of <nl> - # the scope at apply ( ) time . If ' scope ' argument is passed to <nl> - # apply ( ) , it uses that scope when accessing variables . <nl> - lazy_layer = MyLayer ( _reuse = True ) <nl> - with variable_scope . variable_scope ( ' new_scope ' ) as new_scope : <nl> - # This should attempt to reuse ' my_var ' in ' new_scope ' <nl> - with self . assertRaisesRegexp ( <nl> - ValueError , r ' new_scope / my_var does not exist ' ) : <nl> - lazy_layer . apply ( inputs , scope = new_scope ) <nl> + layer = MyLayer ( name = ' my_layer ' ) <nl> + inputs = random_ops . random_uniform ( ( 5 , ) , seed = 1 ) <nl> + layer . apply ( inputs ) <nl> + layer . apply ( inputs ) <nl> + self . assertListEqual ( [ v . name for v in layer . variables ] , <nl> + [ ' my_layer / my_var : 0 ' ] ) <nl> + <nl> + # Creating a layer with no scope leads to lazy construction of <nl> + # the scope at apply ( ) time . It uses scope " < current scope > / base_name " <nl> + lazy_layer = MyLayer ( _reuse = True ) <nl> + with variable_scope . variable_scope ( ' new_scope ' ) : <nl> + with variable_scope . variable_scope ( ' my_layer ' ) : <nl> variable_scope . get_variable ( ' my_var ' , [ 2 , 2 ] ) <nl> <nl> - # Smoke test : it runs . <nl> - lazy_layer . apply ( inputs , scope = new_scope ) <nl> - # The variables were created outside of the Layer , and <nl> - # reuse = True , so the Layer does not own them and they are not <nl> - # stored in its collection . <nl> - self . assertListEqual ( lazy_layer . variables , [ ] ) <nl> - self . assertEqual ( lazy_layer . _scope . name , ' new_scope ' ) <nl> - <nl> + # Smoke test : it runs . <nl> + lazy_layer . apply ( inputs ) <nl> + # The variables were created outside of the Layer , and <nl> + # reuse = True , so the Layer does not own them and they are not <nl> + # stored in its collection . <nl> + self . assertListEqual ( lazy_layer . variables , [ ] ) <nl> + self . assertEqual ( lazy_layer . _scope . name , ' new_scope / my_layer ' ) <nl> + <nl> + # Creating a layer with no scope leads to lazy construction of <nl> + # the scope at apply ( ) time . If ' scope ' argument is passed to <nl> + # apply ( ) , it uses that scope when accessing variables . <nl> + lazy_layer = MyLayer ( _reuse = True ) <nl> + with variable_scope . variable_scope ( ' new_scope ' ) as new_scope : <nl> + variable_scope . get_variable ( ' my_var ' , [ 2 , 2 ] ) <nl> + <nl> + # Smoke test : it runs . <nl> + lazy_layer . apply ( inputs , scope = new_scope ) <nl> + # The variables were created outside of the Layer , and <nl> + # reuse = True , so the Layer does not own them and they are not <nl> + # stored in its collection . <nl> + self . assertListEqual ( lazy_layer . variables , [ ] ) <nl> + self . assertEqual ( lazy_layer . _scope . name , ' new_scope ' ) <nl> + <nl> + if context . in_graph_mode ( ) : <nl> + # Checking for graph equality is only done in GRAPH mode . <nl> with ops . Graph ( ) . as_default ( ) : <nl> inputs_ng = random_ops . random_uniform ( ( 5 , ) , seed = 1 ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' graph are not the same ' ) : <nl> + with self . assertRaisesRegexp ( ValueError , r ' graph are not the same ' ) : <nl> layer . apply ( inputs_ng ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testCall ( self ) : <nl> <nl> class MyLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> inputs = random_ops . random_uniform ( ( 5 , ) , seed = 1 ) <nl> outputs = layer . apply ( inputs ) <nl> self . assertEqual ( layer . built , True ) <nl> - self . assertEqual ( outputs . op . name , ' my_layer / Square ' ) <nl> + if context . in_graph_mode ( ) : <nl> + # op is only supported in GRAPH mode <nl> + self . assertEqual ( outputs . op . name , ' my_layer / Square ' ) <nl> <nl> def testFirstCallCanCreateVariablesButSecondCanNotWhenBuildEmpty ( self ) : <nl> + # Note that this test is only run in Graph mode since with EAGER mode we can <nl> + # still create a new variable on second call . <nl> <nl> class MyLayer ( base_layers . Layer ) : <nl> <nl> def call ( self , inputs ) : <nl> outputs = layer . apply ( inputs ) <nl> self . assertEqual ( layer . built , True ) <nl> self . assertEqual ( outputs . op . name , ' my_layer / add ' ) <nl> - self . assertListEqual ( <nl> - [ v . name for v in layer . variables ] , [ ' my_layer / my_var : 0 ' ] ) <nl> + self . assertListEqual ( [ v . name <nl> + for v in layer . variables ] , [ ' my_layer / my_var : 0 ' ] ) <nl> with self . assertRaisesRegexp ( ValueError , <nl> ' my_layer / this_will_break_on_second_call ' ) : <nl> layer . apply ( inputs ) <nl> # The list of variables hasn ' t changed . <nl> - self . assertListEqual ( <nl> - [ v . name for v in layer . variables ] , [ ' my_layer / my_var : 0 ' ] ) <nl> + self . assertListEqual ( [ v . name <nl> + for v in layer . variables ] , [ ' my_layer / my_var : 0 ' ] ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testDeepCopy ( self ) : <nl> <nl> class MyLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> inputs = random_ops . random_uniform ( ( 5 , ) , seed = 1 ) <nl> outputs = layer . apply ( inputs ) <nl> self . assertEqual ( layer . built , True ) <nl> - self . assertEqual ( outputs . op . name , ' my_layer / Square ' ) <nl> + if context . in_graph_mode ( ) : <nl> + # op only supported in GRAPH mode . <nl> + self . assertEqual ( outputs . op . name , ' my_layer / Square ' ) <nl> <nl> layer_copy = copy . deepcopy ( layer ) <nl> self . assertEqual ( layer_copy . name , layer . name ) <nl> def call ( self , inputs ) : <nl> self . assertEqual ( layer_copy . _graph , layer . _graph ) <nl> self . assertEqual ( layer_copy . _private_tensor , layer . _private_tensor ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testScopeNaming ( self ) : <nl> <nl> class PrivateLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> my_layer_scoped1 . apply ( inputs ) <nl> self . assertEqual ( my_layer_scoped1 . _scope . name , ' var_scope / my_layer_1 ' ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecNdimCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def __init__ ( self ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> - layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' requires a defined rank ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> + if context . in_graph_mode ( ) : <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' requires a defined rank ' ) : <nl> + layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected ndim = 2 ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected ndim = 2 ' ) : <nl> + layer . apply ( constant_op . constant ( [ 1 ] ) ) <nl> <nl> + # Note that we re - create the layer since in Eager mode , input spec checks <nl> + # only happen on first call . <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ 1 ] , [ 2 ] ] ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecMinNdimCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def __init__ ( self ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> - layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' requires a defined rank ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> + if context . in_graph_mode ( ) : <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' requires a defined rank ' ) : <nl> + layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected min_ndim = 2 ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected min_ndim = 2 ' ) : <nl> + layer . apply ( constant_op . constant ( [ 1 ] ) ) <nl> <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None ) ) ) <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None , None ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ 1 ] , [ 2 ] ] ) ) <nl> + <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ [ 1 ] , [ 2 ] ] ] ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecMaxNdimCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def __init__ ( self ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> - layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' requires a defined rank ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> + if context . in_graph_mode ( ) : <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' requires a defined rank ' ) : <nl> + layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected max_ndim = 2 ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None , None ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected max_ndim = 2 ' ) : <nl> + layer . apply ( constant_op . constant ( [ [ [ 1 ] , [ 2 ] ] ] ) ) <nl> <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None ) ) ) <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ 1 ] ) ) <nl> <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ 1 ] , [ 2 ] ] ) ) <nl> + <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecDtypeCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected dtype = float32 ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected dtype = float32 ' ) : <nl> + layer . apply ( constant_op . constant ( 1 , dtype = dtypes . int32 ) ) <nl> <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' float32 ' , shape = ( None , None ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( 1 . 0 , dtype = dtypes . float32 ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecAxesCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected axis ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , 3 ) ) ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected axis ' ) : <nl> + layer . apply ( constant_op . constant ( [ 1 , 2 , 3 ] ) ) <nl> <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , None , 2 ) ) ) <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , 2 ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ 1 , 2 ] ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testInputSpecShapeCheck ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> return inputs <nl> <nl> layer = CustomerLayer ( ) <nl> - with self . assertRaisesRegexp ( ValueError , <nl> - r ' expected shape ' ) : <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , 2 ) ) ) <nl> + with self . assertRaisesRegexp ( ValueError , r ' expected shape ' ) : <nl> + layer . apply ( constant_op . constant ( [ [ 1 , 2 ] ] ) ) <nl> <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( None , 3 ) ) ) <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( 2 , 3 ) ) ) <nl> + layer = CustomerLayer ( ) <nl> + layer . apply ( constant_op . constant ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testNoInputSpec ( self ) : <nl> <nl> class CustomerLayer ( base_layers . Layer ) : <nl> def call ( self , inputs ) : <nl> <nl> layer = CustomerLayer ( ) <nl> <nl> + layer . apply ( constant_op . constant ( 1 ) ) <nl> + <nl> # Works <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> - layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( 2 , 3 ) ) ) <nl> + if context . in_graph_mode ( ) : <nl> + layer . apply ( array_ops . placeholder ( ' int32 ' ) ) <nl> + layer . apply ( array_ops . placeholder ( ' int32 ' , shape = ( 2 , 3 ) ) ) <nl> <nl> def test_get_updates_for ( self ) : <nl> a = base_layers . Input ( shape = ( 2 , ) ) <nl> def testTopologicalAttributes ( self ) : <nl> _ = new_dense . output_shape <nl> <nl> def testTopologicalAttributesMultiOutputLayer ( self ) : <nl> + <nl> class PowersLayer ( base_layers . Layer ) : <nl> <nl> def call ( self , inputs ) : <nl> - return [ inputs * * 2 , inputs * * 3 ] <nl> + return [ inputs * * 2 , inputs * * 3 ] <nl> <nl> x = base_layers . Input ( shape = ( 32 , ) ) <nl> test_layer = PowersLayer ( ) <nl> def call ( self , inputs ) : <nl> self . assertEqual ( test_layer . output_shape , [ ( None , 32 ) , ( None , 32 ) ] ) <nl> <nl> def testTopologicalAttributesMultiInputLayer ( self ) : <nl> + <nl> class AddLayer ( base_layers . Layer ) : <nl> <nl> def call ( self , inputs ) : <nl> def call ( self , inputs ) : <nl> self . assertEqual ( test_layer . input_shape , [ ( None , 32 ) , ( None , 32 ) ] ) <nl> self . assertEqual ( test_layer . output_shape , ( None , 32 ) ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def test_count_params ( self ) : <nl> dense = core_layers . Dense ( 16 ) <nl> dense . build ( ( None , 4 ) ) <nl> def testCrossDataFlows ( self ) : <nl> class PowersLayer ( base_layers . Layer ) : <nl> <nl> def call ( self , inputs ) : <nl> - return [ inputs * * 2 , inputs * * 3 ] <nl> + return [ inputs * * 2 , inputs * * 3 ] <nl> <nl> x = base_layers . Input ( shape = ( 32 , ) ) <nl> p1 , p2 = PowersLayer ( ) ( x ) # pylint : disable = not - callable <nl> def call ( self , inputs ) : <nl> <nl> def testNetworkAttributes ( self ) : <nl> x = base_layers . Input ( shape = ( 32 , ) ) <nl> - z = core_layers . Dense ( 2 , kernel_regularizer = lambda x : 0 . 01 * ( x * * 2 ) ) ( x ) <nl> + z = core_layers . Dense ( 2 , kernel_regularizer = lambda x : 0 . 01 * ( x * * 2 ) ) ( x ) <nl> dense = core_layers . Dense ( 2 , name = ' dense ' ) <nl> dense . add_update ( 1 ) <nl> y = dense ( z ) <nl> def call ( self , inputs ) : <nl> self . assertEqual ( len ( network . layers ) , 2 ) <nl> self . assertEqual ( network . layers [ 0 ] . sparse , True ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testMaskingSingleInput ( self ) : <nl> <nl> class MaskedLayer ( base_layers . Layer ) : <nl> def call ( self , inputs , mask = None ) : <nl> def compute_mask ( self , inputs , mask = None ) : <nl> return array_ops . ones_like ( inputs ) <nl> <nl> - x = base_layers . Input ( shape = ( 32 , ) ) <nl> - y = MaskedLayer ( ) ( x ) # pylint : disable = not - callable <nl> - network = base_layers . Network ( x , y ) <nl> - <nl> - # test callability on Input <nl> - x_2 = base_layers . Input ( shape = ( 32 , ) ) <nl> - y_2 = network ( x_2 ) <nl> - self . assertEqual ( y_2 . get_shape ( ) . as_list ( ) , [ None , 32 ] ) <nl> - <nl> - # test callability on regular tensor <nl> - x_2 = array_ops . placeholder ( dtype = ' float32 ' , shape = ( None , 32 ) ) <nl> - y_2 = network ( x_2 ) <nl> - self . assertEqual ( y_2 . get_shape ( ) . as_list ( ) , [ None , 32 ] ) <nl> + if context . in_graph_mode ( ) : <nl> + x = base_layers . Input ( shape = ( 32 , ) ) <nl> + y = MaskedLayer ( ) ( x ) # pylint : disable = not - callable <nl> + network = base_layers . Network ( x , y ) <nl> + <nl> + # test callability on Input <nl> + x_2 = base_layers . Input ( shape = ( 32 , ) ) <nl> + y_2 = network ( x_2 ) <nl> + self . assertEqual ( y_2 . get_shape ( ) . as_list ( ) , [ None , 32 ] ) <nl> + <nl> + # test callability on regular tensor <nl> + x_2 = array_ops . placeholder ( dtype = ' float32 ' , shape = ( None , 32 ) ) <nl> + y_2 = network ( x_2 ) <nl> + self . assertEqual ( y_2 . get_shape ( ) . as_list ( ) , [ None , 32 ] ) <nl> + else : <nl> + a = constant_op . constant ( [ 2 ] * 32 ) <nl> + mask = constant_op . constant ( [ 0 , 1 ] * 16 ) <nl> + a . _keras_mask = mask <nl> + b = MaskedLayer ( ) . apply ( a ) <nl> + self . assertTrue ( hasattr ( b , ' _keras_mask ' ) ) <nl> + self . assertAllEqual ( self . evaluate ( array_ops . ones_like ( mask ) ) , <nl> + self . evaluate ( getattr ( b , ' _keras_mask ' ) ) ) <nl> + self . assertAllEqual ( self . evaluate ( a * mask ) , self . evaluate ( b ) ) <nl> <nl> <nl> if __name__ = = ' __main__ ' : <nl> mmm a / tensorflow / python / layers / core . py <nl> ppp b / tensorflow / python / layers / core . py <nl> <nl> from six . moves import xrange # pylint : disable = redefined - builtin <nl> import numpy as np <nl> <nl> + from tensorflow . python . eager import context <nl> from tensorflow . python . framework import ops <nl> from tensorflow . python . framework import tensor_shape <nl> from tensorflow . python . ops import array_ops <nl> def build ( self , input_shape ) : <nl> def call ( self , inputs ) : <nl> inputs = ops . convert_to_tensor ( inputs , dtype = self . dtype ) <nl> shape = inputs . get_shape ( ) . as_list ( ) <nl> - output_shape = shape [ : - 1 ] + [ self . units ] <nl> - if len ( output_shape ) > 2 : <nl> + if len ( shape ) > 2 : <nl> # Broadcasting is required for the inputs . <nl> outputs = standard_ops . tensordot ( inputs , self . kernel , [ [ len ( shape ) - 1 ] , <nl> [ 0 ] ] ) <nl> # Reshape the output back to the original ndim of the input . <nl> - outputs . set_shape ( output_shape ) <nl> + if context . in_graph_mode ( ) : <nl> + output_shape = shape [ : - 1 ] + [ self . units ] <nl> + outputs . set_shape ( output_shape ) <nl> else : <nl> outputs = standard_ops . matmul ( inputs , self . kernel ) <nl> if self . use_bias : <nl> def _get_noise_shape ( self , _ ) : <nl> return self . noise_shape <nl> <nl> def call ( self , inputs , training = False ) : <nl> + <nl> def dropped_inputs ( ) : <nl> return nn . dropout ( inputs , 1 - self . rate , <nl> noise_shape = self . _get_noise_shape ( inputs ) , <nl> mmm a / tensorflow / python / layers / core_test . py <nl> ppp b / tensorflow / python / layers / core_test . py <nl> <nl> <nl> import numpy as np <nl> <nl> + from tensorflow . python . eager import context <nl> from tensorflow . python . framework import dtypes <nl> from tensorflow . python . framework import ops <nl> from tensorflow . python . framework import tensor_shape <nl> + from tensorflow . python . framework import test_util <nl> from tensorflow . python . layers import core as core_layers <nl> from tensorflow . python . ops import array_ops <nl> from tensorflow . python . ops import init_ops <nl> <nl> <nl> class DenseTest ( test . TestCase ) : <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testDenseProperties ( self ) : <nl> dense = core_layers . Dense ( 2 , activation = nn_ops . relu , name = ' my_dense ' ) <nl> self . assertEqual ( dense . units , 2 ) <nl> def testDenseProperties ( self ) : <nl> dense . apply ( random_ops . random_uniform ( ( 5 , 2 ) ) ) <nl> self . assertEqual ( dense . name , ' dense_2 ' ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testCall ( self ) : <nl> dense = core_layers . Dense ( 2 , activation = nn_ops . relu , name = ' my_dense ' ) <nl> - inputs = random_ops . random_uniform ( ( 5 , 2 ) , seed = 1 ) <nl> - _ = dense ( inputs ) <nl> + inputs = random_ops . random_uniform ( ( 5 , 4 ) , seed = 1 ) <nl> + outputs = dense ( inputs ) <nl> + self . assertListEqual ( [ 5 , 2 ] , outputs . get_shape ( ) . as_list ( ) ) <nl> self . assertListEqual ( dense . variables , [ dense . kernel , dense . bias ] ) <nl> self . assertListEqual ( dense . trainable_variables , [ dense . kernel , dense . bias ] ) <nl> self . assertListEqual ( dense . non_trainable_variables , [ ] ) <nl> def testCall ( self ) : <nl> self . assertEqual ( dense . kernel . name , ' my_dense / kernel : 0 ' ) <nl> self . assertEqual ( dense . bias . name , ' my_dense / bias : 0 ' ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> + def testCallTensorDot ( self ) : <nl> + dense = core_layers . Dense ( 2 , activation = nn_ops . relu , name = ' my_dense ' ) <nl> + inputs = random_ops . random_uniform ( ( 5 , 4 , 3 ) , seed = 1 ) <nl> + outputs = dense ( inputs ) <nl> + self . assertListEqual ( [ 5 , 4 , 2 ] , outputs . get_shape ( ) . as_list ( ) ) <nl> + <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testNoBias ( self ) : <nl> dense = core_layers . Dense ( 2 , use_bias = False , name = ' my_dense ' ) <nl> inputs = random_ops . random_uniform ( ( 5 , 2 ) , seed = 1 ) <nl> def testNoBias ( self ) : <nl> self . assertEqual ( dense . kernel . name , ' my_dense / kernel : 0 ' ) <nl> self . assertEqual ( dense . bias , None ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testNonTrainable ( self ) : <nl> dense = core_layers . Dense ( 2 , trainable = False , name = ' my_dense ' ) <nl> inputs = random_ops . random_uniform ( ( 5 , 2 ) , seed = 1 ) <nl> def testNonTrainable ( self ) : <nl> self . assertEqual ( <nl> len ( ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) , 0 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testOutputShape ( self ) : <nl> dense = core_layers . Dense ( 7 , activation = nn_ops . relu , name = ' my_dense ' ) <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> def testCallOnPlaceHolder ( self ) : <nl> dense = core_layers . Dense ( 4 , name = ' my_dense ' ) <nl> dense ( inputs ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testActivation ( self ) : <nl> dense = core_layers . Dense ( 2 , activation = nn_ops . relu , name = ' dense1 ' ) <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> outputs = dense ( inputs ) <nl> - self . assertEqual ( outputs . op . name , ' dense1 / Relu ' ) <nl> + if context . in_graph_mode ( ) : <nl> + self . assertEqual ( outputs . op . name , ' dense1 / Relu ' ) <nl> <nl> dense = core_layers . Dense ( 2 , name = ' dense2 ' ) <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> outputs = dense ( inputs ) <nl> - self . assertEqual ( outputs . op . name , ' dense2 / BiasAdd ' ) <nl> + if context . in_graph_mode ( ) : <nl> + self . assertEqual ( outputs . op . name , ' dense2 / BiasAdd ' ) <nl> <nl> def testActivityRegularizer ( self ) : <nl> regularizer = lambda x : math_ops . reduce_sum ( x ) * 1e - 3 <nl> def testBiasRegularizer ( self ) : <nl> self . assertEqual ( len ( loss_keys ) , 1 ) <nl> self . assertListEqual ( dense . losses , loss_keys ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDense ( self ) : <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> outputs = core_layers . dense ( <nl> inputs , 2 , activation = nn_ops . relu , name = ' my_dense ' ) <nl> self . assertEqual ( <nl> len ( ops . get_collection ( ops . GraphKeys . TRAINABLE_VARIABLES ) ) , 2 ) <nl> - self . assertEqual ( outputs . op . name , ' my_dense / Relu ' ) <nl> + if context . in_graph_mode ( ) : <nl> + self . assertEqual ( outputs . op . name , ' my_dense / Relu ' ) <nl> self . assertEqual ( outputs . get_shape ( ) . as_list ( ) , [ 5 , 2 ] ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseTwice ( self ) : <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> core_layers . dense ( inputs , 2 ) <nl> def testFunctionalDenseTwice ( self ) : <nl> self . assertEqual ( len ( vars1 ) , 2 ) <nl> self . assertEqual ( len ( vars2 ) , 4 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseTwiceReuse ( self ) : <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> core_layers . dense ( inputs , 2 , name = ' my_dense ' ) <nl> def testFunctionalDenseTwiceReuse ( self ) : <nl> vars2 = variables . trainable_variables ( ) <nl> self . assertEqual ( vars1 , vars2 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseTwiceReuseFromScope ( self ) : <nl> with variable_scope . variable_scope ( ' scope ' ) : <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> def testFunctionalDenseTwiceReuseFromScope ( self ) : <nl> vars2 = variables . trainable_variables ( ) <nl> self . assertEqual ( vars1 , vars2 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseInitializerFromScope ( self ) : <nl> - with self . test_session ( ) as sess : <nl> - with variable_scope . variable_scope ( <nl> - ' scope ' , initializer = init_ops . ones_initializer ( ) ) : <nl> - inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> - core_layers . dense ( inputs , 2 ) <nl> - sess . run ( variables . global_variables_initializer ( ) ) <nl> - weights = sess . run ( variables . trainable_variables ( ) ) <nl> - self . assertEqual ( len ( weights ) , 2 ) <nl> - # Check that the matrix weights got initialized to ones ( from scope ) . <nl> - self . assertAllClose ( weights [ 0 ] , np . ones ( ( 3 , 2 ) ) ) <nl> - # Check that the bias still got initialized to zeros . <nl> - self . assertAllClose ( weights [ 1 ] , np . zeros ( ( 2 ) ) ) <nl> - <nl> + with variable_scope . variable_scope ( <nl> + ' scope ' , initializer = init_ops . ones_initializer ( ) ) : <nl> + inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> + core_layers . dense ( inputs , 2 ) <nl> + if context . in_graph_mode ( ) : <nl> + self . evaluate ( variables . global_variables_initializer ( ) ) <nl> + weights = variables . trainable_variables ( ) <nl> + self . assertEqual ( len ( weights ) , 2 ) <nl> + # Check that the matrix weights got initialized to ones ( from scope ) . <nl> + self . assertAllClose ( <nl> + self . evaluate ( weights [ 0 ] . read_value ( ) ) , np . ones ( ( 3 , 2 ) ) ) <nl> + # Check that the bias still got initialized to zeros . <nl> + self . assertAllClose ( self . evaluate ( weights [ 1 ] . read_value ( ) ) , np . zeros ( ( 2 ) ) ) <nl> + <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseWithCustomGetter ( self ) : <nl> called = [ 0 ] <nl> <nl> def custom_getter ( getter , * args , * * kwargs ) : <nl> core_layers . dense ( inputs , 2 ) <nl> self . assertEqual ( called [ 0 ] , 2 ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDenseInScope ( self ) : <nl> with variable_scope . variable_scope ( ' test ' ) : <nl> inputs = random_ops . random_uniform ( ( 5 , 3 ) , seed = 1 ) <nl> def testFunctionalDenseInScope ( self ) : <nl> var = variables . trainable_variables ( ) [ 4 ] <nl> self . assertEqual ( var . name , ' test2 / dense / kernel : 0 ' ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testComputeOutputShape ( self ) : <nl> dense = core_layers . Dense ( 2 , activation = nn_ops . relu , name = ' dense1 ' ) <nl> ts = tensor_shape . TensorShape <nl> def testComputeOutputShape ( self ) : <nl> dense . _compute_output_shape ( ts ( [ None , 4 , 3 ] ) ) . as_list ( ) ) <nl> # pylint : enable = protected - access <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testConstraints ( self ) : <nl> k_constraint = lambda x : x / math_ops . reduce_sum ( x ) <nl> b_constraint = lambda x : x / math_ops . reduce_max ( x ) <nl> def testConstraints ( self ) : <nl> <nl> class DropoutTest ( test . TestCase ) : <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testDropoutProperties ( self ) : <nl> dp = core_layers . Dropout ( 0 . 5 , name = ' dropout ' ) <nl> self . assertEqual ( dp . rate , 0 . 5 ) <nl> def testDropoutProperties ( self ) : <nl> dp . apply ( array_ops . ones ( ( ) ) ) <nl> self . assertEqual ( dp . name , ' dropout ' ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testBooleanLearningPhase ( self ) : <nl> - with self . test_session ( ) as sess : <nl> - dp = core_layers . Dropout ( 0 . 5 ) <nl> - inputs = array_ops . ones ( ( 5 , 3 ) ) <nl> - dropped = dp . apply ( inputs , training = True ) <nl> - sess . run ( variables . global_variables_initializer ( ) ) <nl> - np_output = sess . run ( dropped ) <nl> - self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> - dropped = dp . apply ( inputs , training = False ) <nl> - np_output = sess . run ( dropped ) <nl> - self . assertAllClose ( np . ones ( ( 5 , 3 ) ) , np_output ) <nl> + dp = core_layers . Dropout ( 0 . 5 ) <nl> + inputs = array_ops . ones ( ( 5 , 3 ) ) <nl> + dropped = dp . apply ( inputs , training = True ) <nl> + if context . in_graph_mode ( ) : <nl> + self . evaluate ( variables . global_variables_initializer ( ) ) <nl> + np_output = self . evaluate ( dropped ) <nl> + self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> + dropped = dp . apply ( inputs , training = False ) <nl> + np_output = self . evaluate ( dropped ) <nl> + self . assertAllClose ( np . ones ( ( 5 , 3 ) ) , np_output ) <nl> <nl> def testDynamicLearningPhase ( self ) : <nl> with self . test_session ( ) as sess : <nl> def testDynamicLearningPhase ( self ) : <nl> inputs = array_ops . ones ( ( 5 , 5 ) ) <nl> training = array_ops . placeholder ( dtype = ' bool ' ) <nl> dropped = dp . apply ( inputs , training = training ) <nl> - sess . run ( variables . global_variables_initializer ( ) ) <nl> + self . evaluate ( variables . global_variables_initializer ( ) ) <nl> np_output = sess . run ( dropped , feed_dict = { training : True } ) <nl> self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> np_output = sess . run ( dropped , feed_dict = { training : False } ) <nl> self . assertAllClose ( np . ones ( ( 5 , 5 ) ) , np_output ) <nl> <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testCustomNoiseShape ( self ) : <nl> - with self . test_session ( ) as sess : <nl> - inputs = array_ops . ones ( ( 5 , 3 , 2 ) ) <nl> - noise_shape = [ 5 , 1 , 2 ] <nl> - dp = core_layers . Dropout ( 0 . 5 , noise_shape = noise_shape , seed = 1 ) <nl> - dropped = dp . apply ( inputs , training = True ) <nl> - sess . run ( variables . global_variables_initializer ( ) ) <nl> - np_output = sess . run ( dropped ) <nl> - self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> - self . assertAllClose ( np_output [ : , 0 , : ] , np_output [ : , 1 , : ] ) <nl> - <nl> + inputs = array_ops . ones ( ( 5 , 3 , 2 ) ) <nl> + noise_shape = [ 5 , 1 , 2 ] <nl> + dp = core_layers . Dropout ( 0 . 5 , noise_shape = noise_shape , seed = 1 ) <nl> + dropped = dp . apply ( inputs , training = True ) <nl> + self . evaluate ( variables . global_variables_initializer ( ) ) <nl> + np_output = self . evaluate ( dropped ) <nl> + self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> + self . assertAllClose ( np_output [ : , 0 , : ] , np_output [ : , 1 , : ] ) <nl> + <nl> + @ test_util . run_in_graph_and_eager_modes ( ) <nl> def testFunctionalDropout ( self ) : <nl> - with self . test_session ( ) as sess : <nl> - inputs = array_ops . ones ( ( 5 , 5 ) ) <nl> - training = array_ops . placeholder ( dtype = ' bool ' ) <nl> - dropped = core_layers . dropout ( inputs , 0 . 5 , training = training , seed = 1 ) <nl> - self . assertEqual ( dropped . op . name , ' dropout / cond / Merge ' ) <nl> - <nl> - sess . run ( variables . global_variables_initializer ( ) ) <nl> - np_output = sess . run ( dropped , feed_dict = { training : True } ) <nl> - self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> - np_output = sess . run ( dropped , feed_dict = { training : False } ) <nl> - self . assertAllClose ( np . ones ( ( 5 , 5 ) ) , np_output ) <nl> + inputs = array_ops . ones ( ( 5 , 5 ) ) <nl> + dropped = core_layers . dropout ( inputs , 0 . 5 , training = True , seed = 1 ) <nl> + if context . in_graph_mode ( ) : <nl> + self . evaluate ( variables . global_variables_initializer ( ) ) <nl> + np_output = self . evaluate ( dropped ) <nl> + self . assertAlmostEqual ( 0 . , np_output . min ( ) ) <nl> + dropped = core_layers . dropout ( inputs , 0 . 5 , training = False , seed = 1 ) <nl> + np_output = self . evaluate ( dropped ) <nl> + self . assertAllClose ( np . ones ( ( 5 , 5 ) ) , np_output ) <nl> <nl> def testDynamicRate ( self ) : <nl> with self . test_session ( ) as sess : <nl> mmm a / tensorflow / python / ops / nn_ops . py <nl> ppp b / tensorflow / python / ops / nn_ops . py <nl> def _flatten_outer_dims ( logits ) : <nl> output = array_ops . reshape ( logits , array_ops . concat ( [ [ - 1 ] , last_dim_size ] , 0 ) ) <nl> <nl> # Set output shape if known . <nl> - shape = logits . get_shape ( ) <nl> - if shape is not None and shape . dims is not None : <nl> - shape = shape . as_list ( ) <nl> - product = 1 <nl> - product_valid = True <nl> - for d in shape [ : - 1 ] : <nl> - if d is None : <nl> - product_valid = False <nl> - break <nl> - else : <nl> - product * = d <nl> - # Only need to set shape if in graph mode <nl> - if product_valid and context . in_graph_mode ( ) : <nl> - output_shape = [ product , shape [ - 1 ] ] <nl> - output . set_shape ( output_shape ) <nl> + if context . in_graph_mode ( ) : <nl> + shape = logits . get_shape ( ) <nl> + if shape is not None and shape . dims is not None : <nl> + shape = shape . as_list ( ) <nl> + product = 1 <nl> + product_valid = True <nl> + for d in shape [ : - 1 ] : <nl> + if d is None : <nl> + product_valid = False <nl> + break <nl> + else : <nl> + product * = d <nl> + if product_valid : <nl> + output_shape = [ product , shape [ - 1 ] ] <nl> + output . set_shape ( output_shape ) <nl> <nl> return output <nl> <nl> def _move_dim_to_end ( tensor , dim_index , rank ) : <nl> <nl> # Make shape inference work since reshape and transpose may erase its static <nl> # shape . <nl> - if shape is not None and shape . dims is not None and context . in_graph_mode ( ) : <nl> + if context . in_graph_mode ( ) and shape is not None and shape . dims is not None : <nl> shape = shape . as_list ( ) <nl> del shape [ dim ] <nl> cost . set_shape ( shape ) <nl> def dropout ( x , keep_prob , noise_shape = None , seed = None , name = None ) : # pylint : di <nl> # 0 . if [ keep_prob , 1 . 0 ) and 1 . if [ 1 . 0 , 1 . 0 + keep_prob ) <nl> binary_tensor = math_ops . floor ( random_tensor ) <nl> ret = math_ops . div ( x , keep_prob ) * binary_tensor <nl> - ret . set_shape ( x . get_shape ( ) ) <nl> + if context . in_graph_mode ( ) : <nl> + ret . set_shape ( x . get_shape ( ) ) <nl> return ret <nl> <nl> <nl>
Make core layers EAGER model friendly .
tensorflow/tensorflow
d733820a1aa02631cb108842a45f33fb2b87e72a
2017-08-30T18:14:27Z
mmm a / xbmc / cores / VideoPlayer / DVDInputStreams / DVDInputStreamBluray . cpp <nl> ppp b / xbmc / cores / VideoPlayer / DVDInputStreams / DVDInputStreamBluray . cpp <nl> void bluray_overlay_argb_cb ( void * this_gen , const struct bd_argb_overlay_s * co <nl> # endif <nl> <nl> CDVDInputStreamBluray : : CDVDInputStreamBluray ( IVideoPlayer * player , const CFileItem & fileitem ) : <nl> - CDVDInputStream ( DVDSTREAM_TYPE_BLURAY , fileitem ) , m_pstream ( nullptr ) , m_rootPath ( " " ) <nl> + CDVDInputStream ( DVDSTREAM_TYPE_BLURAY , fileitem ) , m_player ( player ) <nl> { <nl> - m_title = NULL ; <nl> - m_clip = ( uint32_t ) - 1 ; <nl> - m_angle = 0 ; <nl> - m_playlist = ( uint32_t ) - 1 ; <nl> - m_menu = false ; <nl> - m_bd = NULL ; <nl> m_content = " video / x - mpegts " ; <nl> - m_player = player ; <nl> - m_navmode = false ; <nl> - m_hold = HOLD_NONE ; <nl> - m_angle = 0 ; <nl> memset ( & m_event , 0 , sizeof ( m_event ) ) ; <nl> # ifdef HAVE_LIBBLURAY_BDJ <nl> memset ( & m_argb , 0 , sizeof ( m_argb ) ) ; <nl> BLURAY_TITLE_INFO * CDVDInputStreamBluray : : GetTitleLongest ( ) <nl> { <nl> int titles = bd_get_titles ( m_bd , TITLES_RELEVANT , 0 ) ; <nl> <nl> - BLURAY_TITLE_INFO * s = NULL ; <nl> + BLURAY_TITLE_INFO * s = nullptr ; <nl> for ( int i = 0 ; i < titles ; i + + ) <nl> { <nl> BLURAY_TITLE_INFO * t = bd_get_title_info ( m_bd , i , 0 ) ; <nl> BLURAY_TITLE_INFO * CDVDInputStreamBluray : : GetTitleFile ( const std : : string & filena <nl> if ( sscanf ( filename . c_str ( ) , " % 05u . mpls " , & playlist ) ! = 1 ) <nl> { <nl> CLog : : Log ( LOGERROR , " get_playlist_title - unsupported playlist file selected % s " , CURL : : GetRedacted ( filename ) . c_str ( ) ) ; <nl> - return NULL ; <nl> + return nullptr ; <nl> } <nl> <nl> return bd_get_playlist_info ( m_bd , playlist , 0 ) ; <nl> BLURAY_TITLE_INFO * CDVDInputStreamBluray : : GetTitleFile ( const std : : string & filena <nl> <nl> bool CDVDInputStreamBluray : : Open ( ) <nl> { <nl> - if ( m_player = = NULL ) <nl> + if ( m_player = = nullptr ) <nl> return false ; <nl> <nl> std : : string strPath ( m_item . GetPath ( ) ) ; <nl> bool CDVDInputStreamBluray : : Open ( ) <nl> } <nl> } <nl> <nl> - bd_get_event ( m_bd , NULL ) ; <nl> + bd_get_event ( m_bd , nullptr ) ; <nl> <nl> const BLURAY_DISC_INFO * disc_info = bd_get_disc_info ( m_bd ) ; <nl> <nl> bool CDVDInputStreamBluray : : Open ( ) <nl> <nl> bd_register_overlay_proc ( m_bd , this , bluray_overlay_cb ) ; <nl> # ifdef HAVE_LIBBLURAY_BDJ <nl> - bd_register_argb_overlay_proc ( m_bd , this , bluray_overlay_argb_cb , NULL ) ; <nl> + bd_register_argb_overlay_proc ( m_bd , this , bluray_overlay_argb_cb , nullptr ) ; <nl> # endif <nl> <nl> if ( bd_play ( m_bd ) < = 0 ) <nl> void CDVDInputStreamBluray : : Close ( ) <nl> bd_free_title_info ( m_title ) ; <nl> if ( m_bd ) <nl> { <nl> - bd_register_overlay_proc ( m_bd , NULL , NULL ) ; <nl> + bd_register_overlay_proc ( m_bd , nullptr , nullptr ) ; <nl> bd_close ( m_bd ) ; <nl> } <nl> - m_bd = NULL ; <nl> - m_title = NULL ; <nl> + m_bd = nullptr ; <nl> + m_title = nullptr ; <nl> m_pstream . reset ( ) ; <nl> m_rootPath . clear ( ) ; <nl> } <nl> void CDVDInputStreamBluray : : ProcessEvent ( ) { <nl> <nl> case BD_EVENT_SEEK : <nl> CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - BD_EVENT_SEEK " ) ; <nl> - / / m_player - > OnDVDNavResult ( NULL , 1 ) ; <nl> + / / m_player - > OnDVDNavResult ( nullptr , 1 ) ; <nl> / / bd_read_skip_still ( m_bd ) ; <nl> / / m_hold = HOLD_HELD ; <nl> break ; <nl> void CDVDInputStreamBluray : : ProcessEvent ( ) { <nl> / * when a title ends , playlist WILL eventually change * / <nl> if ( m_title ) <nl> bd_free_title_info ( m_title ) ; <nl> - m_title = NULL ; <nl> + m_title = nullptr ; <nl> break ; <nl> <nl> case BD_EVENT_TITLE : <nl> void CDVDInputStreamBluray : : OverlayFlush ( int64_t pts ) <nl> void CDVDInputStreamBluray : : OverlayCallback ( const BD_OVERLAY * const ov ) <nl> { <nl> # if ( BD_OVERLAY_INTERFACE_VERSION > = 2 ) <nl> - if ( ov = = NULL | | ov - > cmd = = BD_OVERLAY_CLOSE ) <nl> + if ( ov = = nullptr | | ov - > cmd = = BD_OVERLAY_CLOSE ) <nl> { <nl> OverlayClose ( ) ; <nl> return ; <nl> void CDVDInputStreamBluray : : OverlayCallback ( const BD_OVERLAY * const ov ) <nl> # ifdef HAVE_LIBBLURAY_BDJ <nl> void CDVDInputStreamBluray : : OverlayCallbackARGB ( const struct bd_argb_overlay_s * const ov ) <nl> { <nl> - if ( ov = = NULL | | ov - > cmd = = BD_ARGB_OVERLAY_CLOSE ) <nl> + if ( ov = = nullptr | | ov - > cmd = = BD_ARGB_OVERLAY_CLOSE ) <nl> { <nl> OverlayClose ( ) ; <nl> return ; <nl> void CDVDInputStreamBluray : : OverlayCallbackARGB ( const struct bd_argb_overlay_s * <nl> SOverlay overlay ( new CDVDOverlayImage ( ) , std : : ptr_fun ( CDVDOverlay : : Release ) ) ; <nl> <nl> overlay - > palette_colors = 0 ; <nl> - overlay - > palette = NULL ; <nl> + overlay - > palette = nullptr ; <nl> <nl> unsigned bytes = ov - > stride * ov - > h * 4 ; <nl> uint8_t * img = ( uint8_t * ) malloc ( bytes ) ; <nl> CDVDInputStream : : ENextStream CDVDInputStreamBluray : : NextStream ( ) <nl> <nl> void CDVDInputStreamBluray : : UserInput ( bd_vk_key_e vk ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> return ; <nl> <nl> int ret = bd_user_input ( m_bd , - 1 , vk ) ; <nl> void CDVDInputStreamBluray : : UserInput ( bd_vk_key_e vk ) <nl> <nl> bool CDVDInputStreamBluray : : MouseMove ( const CPoint & point ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> return false ; <nl> <nl> if ( bd_mouse_select ( m_bd , - 1 , ( uint16_t ) point . x , ( uint16_t ) point . y ) < 0 ) <nl> bool CDVDInputStreamBluray : : MouseMove ( const CPoint & point ) <nl> <nl> bool CDVDInputStreamBluray : : MouseClick ( const CPoint & point ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> return false ; <nl> <nl> if ( bd_mouse_select ( m_bd , - 1 , ( uint16_t ) point . x , ( uint16_t ) point . y ) < 0 ) <nl> bool CDVDInputStreamBluray : : MouseClick ( const CPoint & point ) <nl> <nl> void CDVDInputStreamBluray : : OnMenu ( ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> { <nl> CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray : : OnMenu - navigation mode not enabled " ) ; <nl> return ; <nl> void CDVDInputStreamBluray : : OnMenu ( ) <nl> <nl> bool CDVDInputStreamBluray : : IsInMenu ( ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> return false ; <nl> if ( m_menu | | ! m_planes [ BD_OVERLAY_IG ] . o . empty ( ) ) <nl> return true ; <nl> bool CDVDInputStreamBluray : : IsInMenu ( ) <nl> <nl> void CDVDInputStreamBluray : : SkipStill ( ) <nl> { <nl> - if ( m_bd = = NULL | | ! m_navmode ) <nl> + if ( m_bd = = nullptr | | ! m_navmode ) <nl> return ; <nl> <nl> if ( m_hold = = HOLD_STILL ) <nl> mmm a / xbmc / cores / VideoPlayer / DVDInputStreams / DVDInputStreamBluray . h <nl> ppp b / xbmc / cores / VideoPlayer / DVDInputStreams / DVDInputStreamBluray . h <nl> extern " C " <nl> } <nl> <nl> # define MAX_PLAYLIST_ID 99999 <nl> + # define MAX_CLIP_ID 99999 <nl> # define BD_EVENT_MENU_OVERLAY - 1 <nl> # define BD_EVENT_MENU_ERROR - 2 <nl> # define BD_EVENT_ENC_ERROR - 3 <nl> class CDVDInputStreamBluray <nl> , public CDVDInputStream : : IMenus <nl> { <nl> public : <nl> + CDVDInputStreamBluray ( ) = delete ; <nl> CDVDInputStreamBluray ( IVideoPlayer * player , const CFileItem & fileitem ) ; <nl> ~ CDVDInputStreamBluray ( ) override ; <nl> bool Open ( ) override ; <nl> class CDVDInputStreamBluray <nl> static void OverlayClear ( SPlane & plane , int x , int y , int w , int h ) ; <nl> static void OverlayInit ( SPlane & plane , int w , int h ) ; <nl> <nl> - IVideoPlayer * m_player ; <nl> - BLURAY * m_bd ; <nl> - BLURAY_TITLE_INFO * m_title ; <nl> - uint32_t m_playlist ; <nl> - uint32_t m_clip ; <nl> - uint32_t m_angle ; <nl> - bool m_menu ; <nl> - bool m_navmode ; <nl> + IVideoPlayer * m_player = nullptr ; <nl> + BLURAY * m_bd = nullptr ; <nl> + BLURAY_TITLE_INFO * m_title = nullptr ; <nl> + uint32_t m_playlist = MAX_PLAYLIST_ID + 1 ; <nl> + uint32_t m_clip = MAX_CLIP_ID + 1 ; <nl> + uint32_t m_angle = 0 ; <nl> + bool m_menu = false ; <nl> + bool m_navmode = false ; <nl> int m_dispTimeBeforeRead = 0 ; <nl> <nl> typedef std : : shared_ptr < CDVDOverlayImage > SOverlay ; <nl> class CDVDInputStreamBluray <nl> HOLD_STILL , <nl> HOLD_ERROR , <nl> HOLD_EXIT <nl> - } m_hold ; <nl> + } m_hold = HOLD_NONE ; <nl> BD_EVENT m_event ; <nl> # ifdef HAVE_LIBBLURAY_BDJ <nl> struct bd_argb_buffer_s m_argb ; <nl> class CDVDInputStreamBluray <nl> private : <nl> bool OpenStream ( CFileItem & item ) ; <nl> void SetupPlayerSettings ( ) ; <nl> - std : : unique_ptr < CDVDInputStreamFile > m_pstream ; <nl> + std : : unique_ptr < CDVDInputStreamFile > m_pstream = nullptr ; <nl> std : : string m_rootPath ; <nl> } ; <nl> mmm a / xbmc / filesystem / BlurayCallback . cpp <nl> ppp b / xbmc / filesystem / BlurayCallback . cpp <nl> struct SDirState <nl> <nl> void CBlurayCallback : : bluray_logger ( const char * msg ) <nl> { <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray : : Logger - % s " , msg ) ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback : : Logger - % s " , msg ) ; <nl> } <nl> <nl> void CBlurayCallback : : dir_close ( BD_DIR_H * dir ) <nl> { <nl> if ( dir ) <nl> { <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Closed dir ( % p ) \ n " , static_cast < void * > ( dir ) ) ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Closed dir ( % p ) \ n " , static_cast < void * > ( dir ) ) ; <nl> delete static_cast < SDirState * > ( dir - > internal ) ; <nl> delete dir ; <nl> } <nl> BD_DIR_H * CBlurayCallback : : dir_open ( void * handle , const char * rel_path ) <nl> std : : string * strBasePath = reinterpret_cast < std : : string * > ( handle ) ; <nl> if ( ! strBasePath ) <nl> { <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Error opening dir , null handle ! " ) ; <nl> - return NULL ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Error opening dir , null handle ! " ) ; <nl> + return nullptr ; <nl> } <nl> <nl> std : : string strDirname = URIUtils : : AddFileToFolder ( * strBasePath , strRelPath ) ; <nl> if ( URIUtils : : HasSlashAtEnd ( strDirname ) ) <nl> URIUtils : : RemoveSlashAtEnd ( strDirname ) ; <nl> <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Opening dir % s \ n " , CURL : : GetRedacted ( strDirname ) . c_str ( ) ) ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Opening dir % s \ n " , CURL : : GetRedacted ( strDirname ) . c_str ( ) ) ; <nl> <nl> SDirState * st = new SDirState ( ) ; <nl> if ( ! CDirectory : : GetDirectory ( strDirname , st - > list , " " , DIR_FLAG_DEFAULTS ) ) <nl> { <nl> if ( ! CFile : : Exists ( strDirname ) ) <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Error opening dir ! ( % s ) \ n " , CURL : : GetRedacted ( strDirname ) . c_str ( ) ) ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Error opening dir ! ( % s ) \ n " , CURL : : GetRedacted ( strDirname ) . c_str ( ) ) ; <nl> delete st ; <nl> - return NULL ; <nl> + return nullptr ; <nl> } <nl> <nl> BD_DIR_H * dir = new BD_DIR_H ; <nl> BD_FILE_H * CBlurayCallback : : file_open ( void * handle , const char * rel_path ) <nl> std : : string * strBasePath = reinterpret_cast < std : : string * > ( handle ) ; <nl> if ( ! strBasePath ) <nl> { <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Error opening dir , null handle ! " ) ; <nl> - return NULL ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Error opening dir , null handle ! " ) ; <nl> + return nullptr ; <nl> } <nl> <nl> std : : string strFilename = URIUtils : : AddFileToFolder ( * strBasePath , strRelPath ) ; <nl> BD_FILE_H * CBlurayCallback : : file_open ( void * handle , const char * rel_path ) <nl> return file ; <nl> } <nl> <nl> - CLog : : Log ( LOGDEBUG , " CDVDInputStreamBluray - Error opening file ! ( % s ) " , CURL : : GetRedacted ( strFilename ) . c_str ( ) ) ; <nl> + CLog : : Log ( LOGDEBUG , " CBlurayCallback - Error opening file ! ( % s ) " , CURL : : GetRedacted ( strFilename ) . c_str ( ) ) ; <nl> <nl> delete fp ; <nl> delete file ; <nl> <nl> - return NULL ; <nl> + return nullptr ; <nl> } <nl> <nl> int64_t CBlurayCallback : : file_seek ( BD_FILE_H * file , int64_t offset , int32_t origin ) <nl> mmm a / xbmc / filesystem / BlurayDirectory . cpp <nl> ppp b / xbmc / filesystem / BlurayDirectory . cpp <nl> namespace XFILE <nl> <nl> # define MAIN_TITLE_LENGTH_PERCENT 70 / * * Minimum length of main titles , based on longest title * / <nl> <nl> - CBlurayDirectory : : CBlurayDirectory ( ) <nl> - : m_bd ( NULL ) <nl> - { <nl> - } <nl> - <nl> CBlurayDirectory : : ~ CBlurayDirectory ( ) <nl> { <nl> Dispose ( ) ; <nl> void CBlurayDirectory : : Dispose ( ) <nl> if ( m_bd ) <nl> { <nl> bd_close ( m_bd ) ; <nl> - m_bd = NULL ; <nl> + m_bd = nullptr ; <nl> } <nl> } <nl> <nl> mmm a / xbmc / filesystem / BlurayDirectory . h <nl> ppp b / xbmc / filesystem / BlurayDirectory . h <nl> namespace XFILE <nl> class CBlurayDirectory : public XFILE : : IDirectory <nl> { <nl> public : <nl> - CBlurayDirectory ( ) ; <nl> + CBlurayDirectory ( ) = default ; <nl> ~ CBlurayDirectory ( ) override ; <nl> bool GetDirectory ( const CURL & url , CFileItemList & items ) override ; <nl> <nl> class CBlurayDirectory : public XFILE : : IDirectory <nl> CURL GetUnderlyingCURL ( const CURL & url ) ; <nl> std : : string HexToString ( const uint8_t * buf , int count ) ; <nl> CURL m_url ; <nl> - BLURAY * m_bd ; <nl> + BLURAY * m_bd = nullptr ; <nl> bool m_blurayInitialized = false ; <nl> } ; <nl> <nl>
Merge pull request from ace20022 / bd_log
xbmc/xbmc
732e4a921ae636fd968b24b7ffc5cd30797f90de
2018-08-11T12:18:14Z
mmm a / rpm / mongodb - enterprise . spec <nl> ppp b / rpm / mongodb - enterprise . spec <nl> <nl> Name : mongodb - enterprise <nl> - Conflicts : mongo - 10gen - enterprise , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongodb - enterprise - unstable , mongo - enterprise - unstable , mongo - 10gen - enterprise <nl> Provides : mongo - 10gen - enterprise <nl> Version : 2 . 7 . 1 - pre - <nl> This metapackage will install the mongo shell , import / export tools , other client <nl> % package server <nl> Summary : MongoDB database server ( enterprise ) <nl> Requires : cyrus - sasl , net - snmp - libs <nl> - Conflicts : mongo - 10gen - enterprise - server , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongo - 10gen - enterprise - server <nl> Provides : mongo - 10gen - enterprise - server <nl> <nl> This package contains the MongoDB server software , default configuration files , <nl> <nl> % package shell <nl> Summary : MongoDB shell client ( enterprise ) <nl> - Conflicts : mongo - 10gen - enterprise - shell , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongo - 10gen - enterprise - shell <nl> Provides : mongo - 10gen - enterprise - shell <nl> <nl> This package contains the mongo shell . <nl> <nl> % package mongos <nl> Summary : MongoDB sharded cluster query router ( enterprise ) <nl> - Conflicts : mongo - 10gen - enterprise - mongos , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongo - 10gen - enterprise - mongos <nl> Provides : mongo - 10gen - enterprise - mongos <nl> <nl> This package contains mongos , the MongoDB sharded cluster query router . <nl> <nl> % package tools <nl> Summary : MongoDB tools ( enterprise ) <nl> - Conflicts : mongo - 10gen - enterprise - tools , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongo - 10gen - enterprise - tools <nl> Provides : mongo - 10gen - enterprise - tools <nl> <nl> This package contains standard utilities for interacting with MongoDB . <nl> <nl> % package devel <nl> Summary : Headers and libraries for MongoDB development <nl> - Conflicts : mongo - 10gen - enterprise - devel , mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> + Conflicts : mongo - 10gen , mongo - 10gen - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools , mongodb - nightly , mongodb - org , mongodb - org - mongos , mongodb - org - server , mongodb - org - shell , mongodb - org - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools <nl> Obsoletes : mongo - 10gen - enterprise - devel <nl> Provides : mongo - 10gen - enterprise - devel <nl> <nl> mmm a / rpm / mongodb - org . spec <nl> ppp b / rpm / mongodb - org . spec <nl> <nl> Name : mongodb - org <nl> - Conflicts : mongo - 10gen , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen <nl> Provides : mongo - 10gen <nl> Version : 2 . 7 . 1 - pre - <nl> This metapackage will install the mongo shell , import / export tools , other client <nl> <nl> % package server <nl> Summary : MongoDB database server <nl> - Conflicts : mongo - 10gen - server , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen - server <nl> Provides : mongo - 10gen - server <nl> <nl> This package contains the MongoDB server software , default configuration files , <nl> <nl> % package shell <nl> Summary : MongoDB shell client <nl> - Conflicts : mongo - 10gen - shell , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen - shell <nl> Provides : mongo - 10gen - shell <nl> <nl> This package contains the mongo shell . <nl> <nl> % package mongos <nl> Summary : MongoDB sharded cluster query router <nl> - Conflicts : mongo - 10gen - mongos , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen - mongos <nl> Provides : mongo - 10gen - mongos <nl> <nl> This package contains mongos , the MongoDB sharded cluster query router . <nl> <nl> % package tools <nl> Summary : MongoDB tools <nl> - Conflicts : mongo - 10gen - tools , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen - tools <nl> Provides : mongo - 10gen - tools <nl> <nl> This package contains standard utilities for interacting with MongoDB . <nl> <nl> % package devel <nl> Summary : Headers and libraries for MongoDB development . <nl> - Conflicts : mongo - 10gen - devel , mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> + Conflicts : mongo - 10gen - enterprise , mongo - 10gen - enterprise - server , mongo - 10gen - unstable , mongo - 10gen - unstable - enterprise , mongo - 10gen - unstable - enterprise - mongos , mongo - 10gen - unstable - enterprise - server , mongo - 10gen - unstable - enterprise - shell , mongo - 10gen - unstable - enterprise - tools , mongo - 10gen - unstable - mongos , mongo - 10gen - unstable - server , mongo - 10gen - unstable - shell , mongo - 10gen - unstable - tools , mongo18 - 10gen , mongo18 - 10gen - server , mongo20 - 10gen , mongo20 - 10gen - server , mongodb , mongodb - server , mongodb - dev , mongodb - clients , mongodb - 10gen , mongodb - 10gen - enterprise , mongodb - 10gen - unstable , mongodb - 10gen - unstable - enterprise , mongodb - 10gen - unstable - enterprise - mongos , mongodb - 10gen - unstable - enterprise - server , mongodb - 10gen - unstable - enterprise - shell , mongodb - 10gen - unstable - enterprise - tools , mongodb - 10gen - unstable - mongos , mongodb - 10gen - unstable - server , mongodb - 10gen - unstable - shell , mongodb - 10gen - unstable - tools , mongodb - enterprise , mongodb - enterprise - mongos , mongodb - enterprise - server , mongodb - enterprise - shell , mongodb - enterprise - tools , mongodb - nightly , mongodb - org - unstable , mongodb - org - unstable - mongos , mongodb - org - unstable - server , mongodb - org - unstable - shell , mongodb - org - unstable - tools , mongodb - stable , mongodb18 - 10gen , mongodb20 - 10gen , mongodb - enterprise - unstable , mongodb - enterprise - unstable - mongos , mongodb - enterprise - unstable - server , mongodb - enterprise - unstable - shell , mongodb - enterprise - unstable - tools <nl> Obsoletes : mongo - 10gen - devel <nl> Provides : mongo - 10gen - devel <nl> <nl>
SERVER - 13862 Remove old package names from rpm Conflicts field
mongodb/mongo
bf66780fece7c58d2c1f636764b54e01e55ce2bc
2014-05-09T23:10:37Z
mmm a / src / messages . h <nl> ppp b / src / messages . h <nl> class ErrorUtils : public AllStatic { <nl> T ( InvalidStringLength , " Invalid string length " ) \ <nl> T ( InvalidTimeValue , " Invalid time value " ) \ <nl> T ( InvalidTypedArrayAlignment , " % of % should be a multiple of % " ) \ <nl> + T ( InvalidTypedArrayIndex , " Invalid typed array index " ) \ <nl> T ( InvalidTypedArrayLength , " Invalid typed array length " ) \ <nl> - T ( InvalidTypedArrayOffset , " Start offset is too large : " ) \ <nl> T ( InvalidSimdIndex , " Index out of bounds for SIMD operation " ) \ <nl> T ( InvalidSimdLaneValue , " Lane value out of bounds for SIMD operation " ) \ <nl> T ( LetInLexicalBinding , " let is disallowed as a lexically bound name " ) \ <nl> mmm a / src / objects . cc <nl> ppp b / src / objects . cc <nl> Maybe < bool > JSReceiver : : DefineOwnProperty ( Isolate * isolate , <nl> return JSProxy : : DefineOwnProperty ( isolate , Handle < JSProxy > : : cast ( object ) , <nl> key , desc , should_throw ) ; <nl> } <nl> + if ( object - > IsJSTypedArray ( ) ) { <nl> + return JSTypedArray : : DefineOwnProperty ( <nl> + isolate , Handle < JSTypedArray > : : cast ( object ) , key , desc , should_throw ) ; <nl> + } <nl> / / TODO ( neis ) : Special case for JSModuleNamespace ? <nl> <nl> / / OrdinaryDefineOwnProperty , by virtue of calling <nl> - / / DefineOwnPropertyIgnoreAttributes , can handle arguments ( ES6 9 . 4 . 4 . 2 ) <nl> - / / and IntegerIndexedExotics ( ES6 9 . 4 . 5 . 3 ) , with one exception : <nl> - / / TODO ( jkummerow ) : Setting an indexed accessor on a typed array should throw . <nl> + / / DefineOwnPropertyIgnoreAttributes , can handle arguments <nl> + / / ( ES # sec - arguments - exotic - objects - defineownproperty - p - desc ) . <nl> return OrdinaryDefineOwnProperty ( isolate , Handle < JSObject > : : cast ( object ) , key , <nl> desc , should_throw ) ; <nl> } <nl> Handle < Object > JSObject : : PrepareElementsForSort ( Handle < JSObject > object , <nl> return isolate - > factory ( ) - > NewNumberFromUint ( result ) ; <nl> } <nl> <nl> + namespace { <nl> + <nl> + bool CanonicalNumericIndexString ( Isolate * isolate , Handle < Object > s , <nl> + Handle < Object > * index ) { <nl> + DCHECK ( s - > IsString ( ) | | s - > IsSmi ( ) ) ; <nl> + <nl> + Handle < Object > result ; <nl> + if ( s - > IsSmi ( ) ) { <nl> + result = s ; <nl> + } else { <nl> + result = String : : ToNumber ( Handle < String > : : cast ( s ) ) ; <nl> + if ( ! result - > IsMinusZero ( ) ) { <nl> + Handle < String > str = Object : : ToString ( isolate , result ) . ToHandleChecked ( ) ; <nl> + / / Avoid treating strings like " 2E1 " and " 20 " as the same key . <nl> + if ( ! str - > SameValue ( * s ) ) return false ; <nl> + } <nl> + } <nl> + * index = result ; <nl> + return true ; <nl> + } <nl> + <nl> + } / / anonymous namespace <nl> + <nl> + / / ES # sec - integer - indexed - exotic - objects - defineownproperty - p - desc <nl> + / / static <nl> + Maybe < bool > JSTypedArray : : DefineOwnProperty ( Isolate * isolate , <nl> + Handle < JSTypedArray > o , <nl> + Handle < Object > key , <nl> + PropertyDescriptor * desc , <nl> + ShouldThrow should_throw ) { <nl> + / / 1 . Assert : IsPropertyKey ( P ) is true . <nl> + DCHECK ( key - > IsName ( ) | | key - > IsNumber ( ) ) ; <nl> + / / 2 . Assert : O is an Object that has a [ [ ViewedArrayBuffer ] ] internal slot . <nl> + / / 3 . If Type ( P ) is String , then <nl> + if ( key - > IsString ( ) | | key - > IsSmi ( ) ) { <nl> + / / 3a . Let numericIndex be ! CanonicalNumericIndexString ( P ) <nl> + / / 3b . If numericIndex is not undefined , then <nl> + Handle < Object > numeric_index ; <nl> + if ( CanonicalNumericIndexString ( isolate , key , & numeric_index ) ) { <nl> + / / 3b i . If IsInteger ( numericIndex ) is false , return false . <nl> + / / 3b ii . If numericIndex = - 0 , return false . <nl> + / / 3b iii . If numericIndex < 0 , return false . <nl> + / / FIXME : the standard allows up to 2 ^ 53 elements . <nl> + uint32_t index ; <nl> + if ( numeric_index - > IsMinusZero ( ) | | ! numeric_index - > ToUint32 ( & index ) ) { <nl> + RETURN_FAILURE ( isolate , should_throw , <nl> + NewTypeError ( MessageTemplate : : kInvalidTypedArrayIndex ) ) ; <nl> + } <nl> + / / 3b iv . Let length be O . [ [ ArrayLength ] ] . <nl> + uint32_t length = o - > length ( ) - > Number ( ) ; <nl> + / / 3b v . If numericIndex ≥ length , return false . <nl> + if ( index > = length ) { <nl> + RETURN_FAILURE ( isolate , should_throw , <nl> + NewTypeError ( MessageTemplate : : kInvalidTypedArrayIndex ) ) ; <nl> + } <nl> + / / 3b vi . If IsAccessorDescriptor ( Desc ) is true , return false . <nl> + if ( PropertyDescriptor : : IsAccessorDescriptor ( desc ) ) { <nl> + RETURN_FAILURE ( isolate , should_throw , <nl> + NewTypeError ( MessageTemplate : : kRedefineDisallowed , key ) ) ; <nl> + } <nl> + / / 3b vii . If Desc has a [ [ Configurable ] ] field and if <nl> + / / Desc . [ [ Configurable ] ] is true , return false . <nl> + / / 3b viii . If Desc has an [ [ Enumerable ] ] field and if Desc . [ [ Enumerable ] ] <nl> + / / is false , return false . <nl> + / / 3b ix . If Desc has a [ [ Writable ] ] field and if Desc . [ [ Writable ] ] is <nl> + / / false , return false . <nl> + if ( ( desc - > has_configurable ( ) & & desc - > configurable ( ) ) | | <nl> + ( desc - > has_enumerable ( ) & & ! desc - > enumerable ( ) ) | | <nl> + ( desc - > has_writable ( ) & & ! desc - > writable ( ) ) ) { <nl> + RETURN_FAILURE ( isolate , should_throw , <nl> + NewTypeError ( MessageTemplate : : kRedefineDisallowed , key ) ) ; <nl> + } <nl> + / / 3b x . If Desc has a [ [ Value ] ] field , then <nl> + / / 3b x 1 . Let value be Desc . [ [ Value ] ] . <nl> + / / 3b x 2 . Return ? IntegerIndexedElementSet ( O , numericIndex , value ) . <nl> + if ( desc - > has_value ( ) ) { <nl> + if ( ! desc - > has_configurable ( ) ) desc - > set_configurable ( false ) ; <nl> + if ( ! desc - > has_enumerable ( ) ) desc - > set_enumerable ( true ) ; <nl> + if ( ! desc - > has_writable ( ) ) desc - > set_writable ( true ) ; <nl> + Handle < Object > value = desc - > value ( ) ; <nl> + RETURN_ON_EXCEPTION_VALUE ( isolate , <nl> + SetOwnElementIgnoreAttributes ( <nl> + o , index , value , desc - > ToAttributes ( ) ) , <nl> + Nothing < bool > ( ) ) ; <nl> + } <nl> + / / 3b xi . Return true . <nl> + return Just ( true ) ; <nl> + } <nl> + } <nl> + / / 4 . Return ! OrdinaryDefineOwnProperty ( O , P , Desc ) . <nl> + return OrdinaryDefineOwnProperty ( isolate , o , key , desc , should_throw ) ; <nl> + } <nl> <nl> ExternalArrayType JSTypedArray : : type ( ) { <nl> switch ( elements ( ) - > map ( ) - > instance_type ( ) ) { <nl> mmm a / src / objects . h <nl> ppp b / src / objects . h <nl> class JSTypedArray : public JSArrayBufferView { <nl> DECL_ACCESSORS ( length , Object ) <nl> inline uint32_t length_value ( ) const ; <nl> <nl> + / / ES6 9 . 4 . 5 . 3 <nl> + MUST_USE_RESULT static Maybe < bool > DefineOwnProperty ( <nl> + Isolate * isolate , Handle < JSTypedArray > o , Handle < Object > key , <nl> + PropertyDescriptor * desc , ShouldThrow should_throw ) ; <nl> + <nl> DECLARE_CAST ( JSTypedArray ) <nl> <nl> ExternalArrayType type ( ) ; <nl> mmm a / test / mjsunit / element - accessor . js <nl> ppp b / test / mjsunit / element - accessor . js <nl> <nl> } ) ( ) ; <nl> <nl> ( function ( ) { <nl> - var o = new Int32Array ( ) ; <nl> - Object . defineProperty ( o , " 0 " , { get : function ( ) { } } ) ; <nl> - assertEquals ( undefined , Object . getOwnPropertyDescriptor ( o , " 0 " ) ) ; <nl> + var o = new Int32Array ( 1 ) ; <nl> + assertThrows ( <nl> + ( ) = > Object . defineProperty ( o , ' 0 ' , { get : function ( ) { } } ) , TypeError ) ; <nl> + assertEquals ( { <nl> + value : 0 , <nl> + writable : true , <nl> + enumerable : true , <nl> + configurable : false <nl> + } , Object . getOwnPropertyDescriptor ( o , " 0 " ) ) ; <nl> } ) ( ) ; <nl> <nl> ( function ( ) { <nl> mmm a / test / test262 / test262 . status <nl> ppp b / test / test262 / test262 . status <nl> <nl> ' built - ins / TypedArrays / internals / Set / key - is - out - of - bounds ' : [ FAIL ] , <nl> ' built - ins / TypedArrays / internals / Set / tonumber - value - throws ' : [ FAIL ] , <nl> <nl> - # https : / / bugs . chromium . org / p / v8 / issues / detail ? id = 5328 <nl> - ' built - ins / TypedArrays / internals / DefineOwnProperty / key - is - numericindex - desc - not - writable ' : [ FAIL ] , <nl> - ' built - ins / TypedArrays / internals / DefineOwnProperty / key - is - not - integer ' : [ FAIL ] , <nl> - ' built - ins / TypedArrays / internals / DefineOwnProperty / key - is - minus - zero ' : [ FAIL ] , <nl> - ' built - ins / TypedArrays / internals / DefineOwnProperty / key - is - lower - than - zero ' : [ FAIL ] , <nl> - ' built - ins / TypedArrays / internals / DefineOwnProperty / key - is - greater - than - last - index ' : [ FAIL ] , <nl> - <nl> # https : / / bugs . chromium . org / p / v8 / issues / detail ? id = 5329 <nl> ' built - ins / RegExp / prototype / source / value - line - terminator ' : [ FAIL ] , <nl> <nl>
Implement DefineOwnProperty for TypedArrays
v8/v8
bc1a3820c27ea869fcc7033ce4f72d9f2105992d
2016-11-29T00:07:58Z
mmm a / tensorflow / compiler / xla / service / buffer_assignment . h <nl> ppp b / tensorflow / compiler / xla / service / buffer_assignment . h <nl> class BufferAssignment { <nl> return allocations_ ; <nl> } <nl> <nl> + / / This is similar to copying Allocations ( ) , but since it ' s moved out , it <nl> + / / preserves the addresses . Since BufferAllocation : : Slice keeps a <nl> + / / BufferAllocation * , and some backends keep BufferAllocation : : Slice in <nl> + / / xla : : Executables , migrating off the use of addresses can be hard . <nl> + std : : vector < BufferAllocation > ReleaseAllocations ( ) { <nl> + return std : : move ( allocations_ ) ; <nl> + } <nl> + <nl> / / Returns the total size allocation holding all temporary buffers . <nl> int64 temp_allocation_total_size ( ) const { <nl> return temp_allocation_total_size_ ; <nl> mmm a / tensorflow / compiler / xla / service / gpu / BUILD <nl> ppp b / tensorflow / compiler / xla / service / gpu / BUILD <nl> cc_library ( <nl> " gpu_debug_info_manager . h " , <nl> ] , <nl> deps = [ <nl> - " / / tensorflow / compiler / xla / service : buffer_assignment " , <nl> " / / tensorflow / compiler / xla / service : hlo " , <nl> + " / / tensorflow / compiler / xla / service : hlo_proto_cc " , <nl> " / / tensorflow / compiler / xla / service : hlo_proto_util " , <nl> " / / tensorflow / core : lib " , <nl> " @ com_google_absl / / absl / container : flat_hash_map " , <nl> tf_cc_test ( <nl> srcs = [ " gpu_debug_info_manager_test . cc " ] , <nl> tags = tf_cuda_tests_tags ( ) , <nl> deps = [ <nl> - " : gpu_constants " , <nl> " : gpu_debug_info_manager " , <nl> - " : gpu_hlo_schedule " , <nl> - " : stream_assignment " , <nl> - " / / tensorflow / compiler / xla / service : buffer_assignment " , <nl> + " / / tensorflow / compiler / xla / service : hlo_proto_cc " , <nl> " / / tensorflow / compiler / xla / tests : hlo_test_base " , <nl> - " / / tensorflow / compiler / xla / tests : test_utils " , <nl> " / / tensorflow / compiler / xla / tests : xla_internal_test_main " , <nl> - " / / tensorflow / core : test " , <nl> ] , <nl> ) <nl> <nl> mmm a / tensorflow / compiler / xla / service / gpu / buffer_allocations . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / buffer_allocations . cc <nl> namespace gpu { <nl> <nl> Status BufferAllocations : : TearDown ( <nl> const std : : set < se : : DeviceMemoryBase > & live_addresses , <nl> - const BufferAssignment * buffer_assignment ) { <nl> + absl : : Span < const BufferAllocation > allocations ) { <nl> / / Deallocate temporary buffers , taking care to try to deallocate all of them <nl> / / even if one of the deallocations fails . <nl> Status status ; <nl> - const int64 num_buffers = buffer_assignment - > Allocations ( ) . size ( ) ; <nl> + const int64 num_buffers = allocations . size ( ) ; <nl> for ( BufferAllocation : : Index i = 0 ; i < num_buffers ; + + i ) { <nl> - const BufferAllocation & allocation = buffer_assignment - > GetAllocation ( i ) ; <nl> + const BufferAllocation & allocation = allocations [ i ] ; <nl> se : : DeviceMemoryBase buffer_address = GetDeviceAddress ( allocation . index ( ) ) ; <nl> / / Deallocate buffers marked " maybe_live_out " but aren ' t actually live out , <nl> / / and temp buffers . <nl> mmm a / tensorflow / compiler / xla / service / gpu / buffer_allocations . h <nl> ppp b / tensorflow / compiler / xla / service / gpu / buffer_allocations . h <nl> class BufferAllocations { <nl> / / Tears down all buffers allocated by this object that are not in <nl> / / ` live_addresses ` . <nl> Status TearDown ( const std : : set < se : : DeviceMemoryBase > & live_addresses , <nl> - const BufferAssignment * buffer_assignment ) ; <nl> + absl : : Span < const BufferAllocation > allocations ) ; <nl> <nl> std : : string ToString ( ) { <nl> std : : string out ; <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_compiler . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_compiler . cc <nl> StatusOr < std : : unique_ptr < Executable > > GpuCompiler : : RunBackend ( <nl> absl : : flat_hash_map < ShapeIndex , GpuExecutable : : OutputInfo > ; <nl> TF_ASSIGN_OR_RETURN ( OutputInfoMap output_info , <nl> GetOutputInfo ( * module , * buffer_assignment ) ) ; <nl> + auto buffer_assignment_proto = <nl> + std : : make_unique < BufferAssignmentProto > ( buffer_assignment - > ToProto ( ) ) ; <nl> + std : : vector < BufferAllocation > allocations = <nl> + buffer_assignment - > ReleaseAllocations ( ) ; <nl> <nl> GpuVersion gpu_version = GetGpuVersion ( stream_exec ) ; <nl> auto * gpu_executable = new GpuExecutable ( <nl> { std : : move ( backend_result . first ) , std : : move ( backend_result . second ) , <nl> gpu_version , std : : move ( thunk_schedule ) , std : : move ( constants ) , <nl> - std : : move ( output_info ) , std : : move ( module ) , std : : move ( buffer_assignment ) , <nl> - std : : move ( profile_printer ) , std : : move ( profile_index_map ) } ) ; <nl> + std : : move ( output_info ) , std : : move ( module ) , std : : move ( allocations ) , <nl> + std : : move ( buffer_assignment_proto ) , std : : move ( profile_printer ) , <nl> + std : : move ( profile_index_map ) } ) ; <nl> if ( embed_ir_in_executable ) { <nl> DCHECK_NE ( " " , ir_module_string_before_opt ) ; <nl> gpu_executable - > set_ir_module_string ( ir_module_string_before_opt ) ; <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager . cc <nl> namespace gpu { <nl> <nl> void GpuDebugInfoManager : : RegisterModule ( <nl> const ModuleIdentifier & module_id , std : : shared_ptr < HloModule > hlo_module , <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment ) { <nl> + std : : shared_ptr < const BufferAssignmentProto > buffer_assignment ) { <nl> tensorflow : : mutex_lock lock ( mutex_ ) ; <nl> if ( active_modules_ . find ( module_id ) ! = active_modules_ . end ( ) ) { <nl> active_modules_ [ module_id ] . instances . emplace_back ( hlo_module , <nl> void GpuDebugInfoManager : : RegisterModule ( <nl> / / However during tracing , we will defer the cleanup after serialization . <nl> void GpuDebugInfoManager : : UnregisterModule ( <nl> const ModuleIdentifier & module_id , std : : shared_ptr < HloModule > hlo_module , <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment ) { <nl> + std : : shared_ptr < const BufferAssignmentProto > buffer_assignment ) { <nl> tensorflow : : mutex_lock lock ( mutex_ ) ; <nl> CHECK ( active_modules_ . find ( module_id ) ! = active_modules_ . end ( ) ) ; <nl> GpuModuleEntry & active_module = active_modules_ [ module_id ] ; <nl> void GpuDebugInfoManager : : StopTracing ( <nl> / / non - nullptr . Due to the inconvenience of creation of buffer_assignment <nl> / / object in test , we set it to nullptr and guard this for it . <nl> if ( m . instances [ 0 ] . hlo_module & & m . instances [ 0 ] . buffer_assignment ) { <nl> - info . hlo_proto = absl : : make_unique < HloProto > ( MakeHloProto ( <nl> - * m . instances [ 0 ] . hlo_module , * m . instances [ 0 ] . buffer_assignment ) ) ; <nl> + info . hlo_proto = absl : : make_unique < HloProto > ( <nl> + MakeHloProto ( * m . instances [ 0 ] . hlo_module ) ) ; <nl> + * info . hlo_proto - > mutable_buffer_assignment ( ) = <nl> + * m . instances [ 0 ] . buffer_assignment ; <nl> } <nl> module_debug_info - > emplace_back ( std : : move ( info ) ) ; <nl> } <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager . h <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager . h <nl> limitations under the License . <nl> # define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_GPU_DEBUG_INFO_MANAGER_H_ <nl> <nl> # include " absl / container / flat_hash_map . h " <nl> - # include " tensorflow / compiler / xla / service / buffer_assignment . h " <nl> + # include " tensorflow / compiler / xla / service / hlo . pb . h " <nl> # include " tensorflow / compiler / xla / service / hlo_module . h " <nl> # include " tensorflow / core / lib / core / status . h " <nl> <nl> class GpuDebugInfoManager { <nl> / / Modules with same module id can be registered and tracked separately . <nl> void RegisterModule ( <nl> const ModuleIdentifier & module_id , std : : shared_ptr < HloModule > hlo_module , <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment ) ; <nl> + std : : shared_ptr < const BufferAssignmentProto > buffer_assignment ) ; <nl> <nl> / / Unregister an active module . When the last active module of the same <nl> / / module id is out of scope , we remove it from our database . <nl> / / However during tracing , we will defer the cleanup after serialization . <nl> void UnregisterModule ( <nl> const ModuleIdentifier & module_id , std : : shared_ptr < HloModule > hlo_module , <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment ) ; <nl> + std : : shared_ptr < const BufferAssignmentProto > buffer_assignment ) ; <nl> <nl> / / Register when the module start execution on certain device . <nl> / / TODO ( jiesun ) : Do we need to track which device this is ? <nl> class GpuDebugInfoManager { <nl> / / tracking , they need to be tracked separately . <nl> struct GpuModuleInstance { <nl> GpuModuleInstance ( std : : shared_ptr < HloModule > m , <nl> - std : : shared_ptr < const BufferAssignment > b ) <nl> + std : : shared_ptr < const BufferAssignmentProto > b ) <nl> : hlo_module ( std : : move ( m ) ) , buffer_assignment ( std : : move ( b ) ) { } <nl> std : : shared_ptr < HloModule > hlo_module ; <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment ; <nl> + std : : shared_ptr < const BufferAssignmentProto > buffer_assignment ; <nl> bool active = true ; <nl> } ; <nl> <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager_test . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager_test . cc <nl> limitations under the License . <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> # include " tensorflow / compiler / xla / service / gpu / gpu_debug_info_manager . h " <nl> <nl> - # include " tensorflow / compiler / xla / service / buffer_assignment . h " <nl> + # include " tensorflow / compiler / xla / service / hlo . pb . h " <nl> # include " tensorflow / compiler / xla / tests / hlo_test_base . h " <nl> <nl> namespace xla { <nl> class GpuDebugInfoManagerTest : public HloTestBase { <nl> int unique_id ; <nl> string id ; <nl> std : : shared_ptr < HloModule > module ; <nl> - std : : shared_ptr < BufferAssignment > buffer_assignment ; <nl> + std : : shared_ptr < BufferAssignmentProto > buffer_assignment ; <nl> } ; <nl> <nl> / / Return unique id of this module . <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_executable . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_executable . cc <nl> GpuExecutable : : GpuExecutable ( GpuExecutable : : Params params ) <nl> binary_ ( std : : move ( params . binary ) ) , <nl> gpu_version_ ( params . gpu_version ) , <nl> thunk_schedule_ ( std : : move ( params . thunk_schedule ) ) , <nl> - assignment_ ( std : : move ( params . assignment ) ) , <nl> + allocations_ ( std : : move ( params . allocations ) ) , <nl> + debug_buffer_assignment_ ( std : : move ( params . debug_buffer_assignment ) ) , <nl> constants_ ( std : : move ( params . constants ) ) , <nl> output_info_ ( std : : move ( params . output_info ) ) { <nl> - CHECK ( has_module ( ) & & assignment_ ) ; <nl> + CHECK ( has_module ( ) ) ; <nl> GpuDebugInfoManager : : Get ( ) - > RegisterModule ( module ( ) . name ( ) , shared_module ( ) , <nl> - assignment_ ) ; <nl> + debug_buffer_assignment_ ) ; <nl> } <nl> <nl> GpuExecutable : : ~ GpuExecutable ( ) { <nl> - CHECK ( has_module ( ) & & assignment_ ) ; <nl> + CHECK ( has_module ( ) ) ; <nl> GpuDebugInfoManager : : Get ( ) - > UnregisterModule ( module ( ) . name ( ) , shared_module ( ) , <nl> - assignment_ ) ; <nl> + debug_buffer_assignment_ ) ; <nl> <nl> { <nl> / / We could have issued host - > device mem copies in ResolveConstantGlobals . <nl> StatusOr < BufferAllocations > GpuExecutable : : GenerateBufferAllocations ( <nl> [ & ] { return std : : string ( " Build buffer allocations " ) ; } , <nl> tensorflow : : profiler : : TraceMeLevel : : kInfo ) ; <nl> <nl> - const int64 num_buffers = assignment_ - > Allocations ( ) . size ( ) ; <nl> + const int64 num_buffers = allocations_ . size ( ) ; <nl> std : : vector < se : : DeviceMemoryBase > buffers ; <nl> buffers . reserve ( num_buffers ) ; <nl> for ( int64 i = 0 ; i < num_buffers ; + + i ) { <nl> - const BufferAllocation & allocation = assignment_ - > GetAllocation ( i ) ; <nl> + const BufferAllocation & allocation = allocations_ [ i ] ; <nl> TF_ASSIGN_OR_RETURN ( <nl> se : : DeviceMemoryBase buffer , <nl> BufferForAllocation ( arguments , globals , allocation , memory_allocator , <nl> StatusOr < ExecutionOutput > GpuExecutable : : ExecuteAsyncOnStream ( <nl> <nl> / / Free all temporary allocations . <nl> TF_RETURN_IF_ERROR ( <nl> - buffer_allocations . TearDown ( buffers_in_result , assignment_ . get ( ) ) ) ; <nl> + buffer_allocations . TearDown ( buffers_in_result , allocations_ ) ) ; <nl> <nl> / / Free allocations for arguments . <nl> MarkToBeReleasedArguments ( absl : : MakeSpan ( arguments ) , result ) ; <nl> int64 GpuExecutable : : SizeOfGeneratedCodeInBytes ( ) const { <nl> return - 1 ; <nl> } <nl> int64 size = binary ( ) . size ( ) ; <nl> - for ( BufferAllocation : : Index i = 0 ; i < assignment_ - > Allocations ( ) . size ( ) ; <nl> - + + i ) { <nl> - const BufferAllocation & allocation = assignment_ - > GetAllocation ( i ) ; <nl> + for ( BufferAllocation : : Index i = 0 ; i < allocations_ . size ( ) ; + + i ) { <nl> + const BufferAllocation & allocation = allocations_ [ i ] ; <nl> if ( allocation . is_constant ( ) ) { <nl> size + = allocation . size ( ) ; <nl> } <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_executable . h <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_executable . h <nl> class GpuExecutable : public Executable { <nl> std : : vector < ConstantInfo > constants ; <nl> absl : : flat_hash_map < ShapeIndex , OutputInfo > output_info ; <nl> std : : unique_ptr < HloModule > hlo_module ; <nl> - std : : unique_ptr < const BufferAssignment > assignment ; <nl> + std : : vector < BufferAllocation > allocations ; <nl> + std : : unique_ptr < BufferAssignmentProto > debug_buffer_assignment ; <nl> std : : unique_ptr < HloProfilePrinterData > hlo_profile_printer_data = nullptr ; <nl> std : : unique_ptr < HloProfileIndexMap > hlo_profile_index_map = nullptr ; <nl> } ; <nl> class GpuExecutable : public Executable { <nl> std : : vector < ExecutionInput > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) override ; <nl> <nl> - std : : shared_ptr < const BufferAssignment > GetBufferAssignment ( ) const { <nl> - return assignment_ ; <nl> + absl : : Span < const BufferAllocation > GetAllocations ( ) const { <nl> + return allocations_ ; <nl> } <nl> <nl> private : <nl> class GpuExecutable : public Executable { <nl> <nl> / / Owns the buffer data at runtime . It provides information to allocate <nl> / / memory for every output / temp buffers . <nl> - const std : : shared_ptr < const BufferAssignment > assignment_ ; <nl> + const std : : vector < BufferAllocation > allocations_ ; <nl> + <nl> + std : : shared_ptr < BufferAssignmentProto > debug_buffer_assignment_ ; <nl> <nl> / / Cache of module handles and constant buffer allocation maps used by <nl> / / ` ResolveConstantGlobals ` . <nl> mmm a / tensorflow / compiler / xla / service / gpu / tests / gemm_rewrite_test . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / tests / gemm_rewrite_test . cc <nl> class GemmRewriteTest : public GpuCodegenTest { <nl> backend ( ) . default_stream_executor ( ) - > GetAllocator ( ) ) ) ; <nl> GpuExecutable * gpu_executable = <nl> static_cast < GpuExecutable * > ( executable . get ( ) ) ; <nl> - std : : shared_ptr < const BufferAssignment > buffer_assignment = <nl> - gpu_executable - > GetBufferAssignment ( ) ; <nl> - CHECK_EQ ( buffer_assignment - > Allocations ( ) . size ( ) , <nl> - expected_number_of_allocations ) <nl> - < < " Unexpected buffer assignment . Was : \ n " <nl> - < < buffer_assignment - > ToString ( ) ; <nl> + absl : : Span < const BufferAllocation > allocations = <nl> + gpu_executable - > GetAllocations ( ) ; <nl> + CHECK_EQ ( allocations . size ( ) , expected_number_of_allocations ) ; <nl> } <nl> } ; <nl> <nl> mmm a / tensorflow / compiler / xla / service / mlir_gpu / mlir_compiler_impl . cc <nl> ppp b / tensorflow / compiler / xla / service / mlir_gpu / mlir_compiler_impl . cc <nl> StatusOr < std : : unique_ptr < Executable > > MlirCompilerImpl : : RunBackend ( <nl> <nl> TF_ASSIGN_OR_RETURN ( auto output_info , <nl> xla : : gpu : : GetOutputInfo ( * module , * buffer_assignment ) ) ; <nl> + std : : vector < BufferAllocation > allocations = <nl> + buffer_assignment - > ReleaseAllocations ( ) ; <nl> <nl> / / TODO ( b / 137624192 ) : Add profiling support . <nl> return { absl : : make_unique < GpuExecutable > ( GpuExecutable : : Params { <nl> std : : move ( ptx ) , std : : move ( cubin ) , GetGpuVersion ( stream_exec ) , <nl> std : : move ( thunk_schedule ) , std : : vector < GpuExecutable : : ConstantInfo > ( ) , <nl> - std : : move ( output_info ) , std : : move ( module ) , <nl> - std : : move ( buffer_assignment ) } ) } ; <nl> + std : : move ( output_info ) , std : : move ( module ) , std : : move ( allocations ) } ) } ; <nl> } <nl> <nl> StatusOr < std : : vector < std : : unique_ptr < Executable > > > MlirCompilerImpl : : Compile ( <nl>
[ XLA / GPU ] Remove uses of BufferAssignment in GpuExecutable .
tensorflow/tensorflow
63b8cdcb820c140fa694acd03551da2caa125142
2020-12-21T23:52:53Z
new file mode 100644 <nl> index 00000000000 . . 3cca29801dd <nl> mmm / dev / null <nl> ppp b / docs / en / sql - reference / statements / explain . md <nl> <nl> + mmm <nl> + toc_priority : 39 <nl> + toc_title : EXPLAIN <nl> + mmm <nl> + <nl> + # EXPLAIN Statement { # explain } <nl> + <nl> + Show the execution plan of a statement . <nl> + <nl> + Syntax : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN [ AST | SYNTAX | PLAN | PIPELINE ] [ setting = value , . . . ] SELECT . . . [ FORMAT . . . ] <nl> + ` ` ` <nl> + <nl> + Example : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN SELECT sum ( number ) FROM numbers ( 10 ) UNION ALL SELECT sum ( number ) FROM numbers ( 10 ) ORDER BY sum ( number ) ASC FORMAT TSV ; <nl> + ` ` ` <nl> + <nl> + ` ` ` sql <nl> + Union <nl> + Expression ( Projection ) <nl> + Expression ( Before ORDER BY and SELECT ) <nl> + Aggregating <nl> + Expression ( Before GROUP BY ) <nl> + SettingQuotaAndLimits ( Set limits and quota after reading from storage ) <nl> + ReadFromStorage ( SystemNumbers ) <nl> + Expression ( Projection ) <nl> + MergingSorted ( Merge sorted streams for ORDER BY ) <nl> + MergeSorting ( Merge sorted blocks for ORDER BY ) <nl> + PartialSorting ( Sort each block for ORDER BY ) <nl> + Expression ( Before ORDER BY and SELECT ) <nl> + Aggregating <nl> + Expression ( Before GROUP BY ) <nl> + SettingQuotaAndLimits ( Set limits and quota after reading from storage ) <nl> + ReadFromStorage ( SystemNumbers ) <nl> + ` ` ` <nl> + <nl> + # # EXPLAIN Types { # explain - types } <nl> + <nl> + - ` AST ` — Abstract syntax tree . <nl> + - ` SYNTAX ` — Query text after AST - level optimizations . <nl> + - ` PLAN ` — Query execution plan . <nl> + - ` PIPELINE ` — Query execution pipeline . <nl> + <nl> + # # # EXPLAIN AST { # explain - ast } <nl> + <nl> + Dump query AST . <nl> + <nl> + Example : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN AST SELECT 1 ; <nl> + ` ` ` <nl> + <nl> + ` ` ` sql <nl> + SelectWithUnionQuery ( children 1 ) <nl> + ExpressionList ( children 1 ) <nl> + SelectQuery ( children 1 ) <nl> + ExpressionList ( children 1 ) <nl> + Literal UInt64_1 <nl> + ` ` ` <nl> + <nl> + # # # EXPLAIN SYNTAX { # explain - syntax } <nl> + <nl> + Return query after syntax optimizations . <nl> + <nl> + Example : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN SYNTAX SELECT * FROM system . numbers AS a , system . numbers AS b , system . numbers AS c ; <nl> + ` ` ` <nl> + <nl> + ` ` ` sql <nl> + SELECT <nl> + ` - - a . number ` AS ` a . number ` , <nl> + ` - - b . number ` AS ` b . number ` , <nl> + number AS ` c . number ` <nl> + FROM <nl> + ( <nl> + SELECT <nl> + number AS ` - - a . number ` , <nl> + b . number AS ` - - b . number ` <nl> + FROM system . numbers AS a <nl> + CROSS JOIN system . numbers AS b <nl> + ) AS ` - - . s ` <nl> + CROSS JOIN system . numbers AS c <nl> + ` ` ` <nl> + # # # EXPLAIN PLAN { # explain - plan } <nl> + <nl> + Dump query plan steps . <nl> + <nl> + Settings : <nl> + <nl> + - ` header ` — Print output header for step . Default : 0 . <nl> + - ` description ` — Print step description . Default : 1 . <nl> + - ` actions ` — Print detailed information about step actions . Default : 0 . <nl> + <nl> + Example : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN SELECT sum ( number ) FROM numbers ( 10 ) GROUP BY number % 4 ; <nl> + ` ` ` <nl> + <nl> + ` ` ` sql <nl> + Union <nl> + Expression ( Projection ) <nl> + Expression ( Before ORDER BY and SELECT ) <nl> + Aggregating <nl> + Expression ( Before GROUP BY ) <nl> + SettingQuotaAndLimits ( Set limits and quota after reading from storage ) <nl> + ReadFromStorage ( SystemNumbers ) <nl> + ` ` ` <nl> + <nl> + ! ! ! note " Note " <nl> + Step and query cost estimation is not supported . <nl> + <nl> + # # # EXPLAIN PIPELINE { # explain - pipeline } <nl> + <nl> + Settings : <nl> + <nl> + - ` header ` — Print header for each output port . Default : 0 . <nl> + - ` graph ` — Use DOT graph description language . Default : 0 . <nl> + - ` compact ` — Print graph in compact mode if graph is enabled . Default : 1 . <nl> + <nl> + Example : <nl> + <nl> + ` ` ` sql <nl> + EXPLAIN PIPELINE SELECT sum ( number ) FROM numbers_mt ( 100000 ) GROUP BY number % 4 ; <nl> + ` ` ` <nl> + <nl> + ` ` ` sql <nl> + ( Union ) <nl> + ( Expression ) <nl> + ExpressionTransform <nl> + ( Expression ) <nl> + ExpressionTransform <nl> + ( Aggregating ) <nl> + Resize 2 → 1 <nl> + AggregatingTransform × 2 <nl> + ( Expression ) <nl> + ExpressionTransform × 2 <nl> + ( SettingQuotaAndLimits ) <nl> + ( ReadFromStorage ) <nl> + NumbersMt × 2 0 → 1 <nl> + ` ` ` <nl> + <nl> + [ Оriginal article ] ( https : / / clickhouse . tech / docs / en / sql - reference / statements / explain / ) < ! - - hide - - > <nl> mmm a / docs / en / sql - reference / statements / index . md <nl> ppp b / docs / en / sql - reference / statements / index . md <nl> Statements represent various kinds of action you can perform using SQL queries . <nl> - [ SET ROLE ] ( . . / . . / sql - reference / statements / set - role . md ) <nl> - [ TRUNCATE ] ( . . / . . / sql - reference / statements / truncate . md ) <nl> - [ USE ] ( . . / . . / sql - reference / statements / use . md ) <nl> + - [ EXPLAIN ] ( . . / . . / sql - reference / statements / explain . md ) <nl>
DOCSUP - 4193 : Document the EXPLAIN statement ( )
ClickHouse/ClickHouse
ac0ebd515eaaf70111a11c00562edf6466dbfb85
2020-12-04T18:24:05Z
mmm a / src / wallet . cpp <nl> ppp b / src / wallet . cpp <nl> bool CWallet : : LoadWallet ( bool & fFirstRunRet ) <nl> return false ; <nl> fFirstRunRet = vchDefaultKey . empty ( ) ; <nl> <nl> - if ( mapKeys . count ( vchDefaultKey ) ) <nl> + if ( ! mapKeys . count ( vchDefaultKey ) ) <nl> { <nl> - / / Set keyUser <nl> - keyUser . SetPubKey ( vchDefaultKey ) ; <nl> - keyUser . SetPrivKey ( mapKeys [ vchDefaultKey ] ) ; <nl> - } <nl> - else <nl> - { <nl> - / / Create new keyUser and set as default key <nl> + / / Create new default key <nl> RandAddSeedPerfmon ( ) ; <nl> <nl> vchDefaultKey = GetKeyFromKeyPool ( ) ; <nl> if ( ! SetAddressBookName ( PubKeyToAddress ( vchDefaultKey ) , " " ) ) <nl> return false ; <nl> - CWalletDB ( strWalletFile ) . WriteDefaultKey ( keyUser . GetPubKey ( ) ) ; <nl> + CWalletDB ( strWalletFile ) . WriteDefaultKey ( vchDefaultKey ) ; <nl> } <nl> <nl> CreateThread ( ThreadFlushWalletDB , & strWalletFile ) ; <nl> mmm a / src / wallet . h <nl> ppp b / src / wallet . h <nl> class CWallet : public CKeyStore <nl> mutable CCriticalSection cs_mapAddressBook ; <nl> <nl> std : : vector < unsigned char > vchDefaultKey ; <nl> - CKey keyUser ; <nl> <nl> bool AddKey ( const CKey & key ) ; <nl> bool AddToWallet ( const CWalletTx & wtxIn ) ; <nl>
Merge pull request from sipa / delkeyuser
bitcoin/bitcoin
d0d80170a2ca73004e08fb85007fe055cbf4e411
2011-06-26T10:04:39Z
mmm a / modules / ts / include / opencv2 / ts / ts_gtest . h <nl> ppp b / modules / ts / include / opencv2 / ts / ts_gtest . h <nl> <nl> # define GTEST_OS_AIX 1 <nl> # endif / / __CYGWIN__ <nl> <nl> - # if GTEST_OS_CYGWIN | | GTEST_OS_LINUX | | GTEST_OS_MAC | | GTEST_OS_SYMBIAN | | \ <nl> - GTEST_OS_SOLARIS | | GTEST_OS_AIX <nl> + # if ( GTEST_OS_CYGWIN | | GTEST_OS_LINUX | | GTEST_OS_MAC | | GTEST_OS_SYMBIAN | | \ <nl> + GTEST_OS_SOLARIS | | GTEST_OS_AIX ) & & ! defined ( ANDROID ) <nl> <nl> / / On some platforms , < regex . h > needs someone to define size_t , and <nl> / / won ' t compile otherwise . We can # include it here as we already <nl>
Android compatibility fix : avoid regex . h include to be able to build OpenCV for platform android - 5
opencv/opencv
16044d1ad59ca03399a6948c60b15aa7958b2576
2011-04-21T12:54:16Z
mmm a / folly / Random - inl . h <nl> ppp b / folly / Random - inl . h <nl> constexpr size_t <nl> StateSize < std : : mersenne_twister_engine < UIntType , w , n , m , r , <nl> a , u , d , s , b , t , c , l , f > > : : value ; <nl> <nl> - # if FOLLY_USE_SIMD_PRNG <nl> + # if FOLLY_HAVE_EXTRANDOM_SFMT19937 <nl> <nl> template < class UIntType , size_t m , size_t pos1 , size_t sl1 , size_t sl2 , <nl> size_t sr1 , size_t sr2 , uint32_t msk1 , uint32_t msk2 , uint32_t msk3 , <nl> mmm a / folly / Random . h <nl> ppp b / folly / Random . h <nl> <nl> # include < stdint . h > <nl> # include < folly / ThreadLocal . h > <nl> <nl> - # if __GNUC_PREREQ ( 4 , 8 ) & & ! defined ( ANDROID ) <nl> + # if FOLLY_HAVE_EXTRANDOM_SFMT19937 <nl> # include < ext / random > <nl> - # define FOLLY_USE_SIMD_PRNG 1 <nl> # endif <nl> <nl> namespace folly { <nl> class Random { <nl> <nl> public : <nl> / / Default generator type . <nl> - # if FOLLY_USE_SIMD_PRNG <nl> + # if FOLLY_HAVE_EXTRANDOM_SFMT19937 <nl> typedef __gnu_cxx : : sfmt19937 DefaultGenerator ; <nl> # else <nl> typedef std : : mt19937 DefaultGenerator ; <nl> mmm a / folly / configure . ac <nl> ppp b / folly / configure . ac <nl> AC_CACHE_CHECK ( <nl> [ folly_cv_prog_cc_xsi_strerror_r = yes ] , <nl> [ folly_cv_prog_cc_xsi_strerror_r = no ] ) ] ) <nl> <nl> + AC_CACHE_CHECK ( <nl> + [ for ext / random and __gnu_cxx : : sfmt19937 ] , <nl> + [ folly_cv_prog_cc_have_extrandom_sfmt19937 ] , <nl> + [ AC_COMPILE_IFELSE ( <nl> + [ AC_LANG_SOURCE [ <nl> + # include < ext / random > <nl> + int main ( int argc , char * * argv ) { <nl> + __gnu_cxx : : sfmt19937 rng ; <nl> + return 0 ; <nl> + } <nl> + ] ] , <nl> + [ folly_cv_prog_cc_have_extrandom_sfmt19937 = yes ] , <nl> + [ folly_cv_prog_cc_have_extrandom_sfmt19937 = no ] ) ] ) <nl> + <nl> if test " $ folly_cv_prog_cc_xsi_strerror_r " = " yes " ; then <nl> AC_DEFINE ( [ HAVE_XSI_STRERROR_R ] , [ 1 ] , [ Define to 1 if the runtime supports XSI - style strerror_r ] ) <nl> fi <nl> AM_CONDITIONAL ( [ HAVE_LINUX ] , [ test " $ build_os " = = " linux - gnu " ] ) <nl> AM_CONDITIONAL ( [ HAVE_WEAK_SYMBOLS ] , <nl> [ test " $ folly_cv_prog_cc_weak_symbols " = " yes " ] ) <nl> AM_CONDITIONAL ( [ HAVE_BITS_FUNCTEXCEPT ] , [ test " $ ac_cv_header_bits_functexcept_h " = " yes " ] ) <nl> + AM_CONDITIONAL ( [ HAVE_EXTRANDOM_SFMT19937 ] , <nl> + [ test " $ folly_cv_prog_cc_have_extrandom_sfmt19937 " = " yes " ] ) <nl> <nl> # Output <nl> AC_CONFIG_FILES ( [ Makefile <nl> mmm a / folly / test / RandomTest . cpp <nl> ppp b / folly / test / RandomTest . cpp <nl> TEST ( Random , StateSize ) { <nl> EXPECT_EQ ( sizeof ( uint_fast32_t ) / 4 + 3 , <nl> StateSize < std : : minstd_rand0 > : : value ) ; <nl> EXPECT_EQ ( 624 , StateSize < std : : mt19937 > : : value ) ; <nl> - # if FOLLY_USE_SIMD_PRNG <nl> + # if FOLLY_HAVE_EXTRANDOM_SFMT19937 <nl> EXPECT_EQ ( 624 , StateSize < __gnu_cxx : : sfmt19937 > : : value ) ; <nl> # endif <nl> EXPECT_EQ ( 24 , StateSize < std : : ranlux24_base > : : value ) ; <nl>
Lift the test for ext / random and sfmt19937
facebook/folly
e2c2baadf630b96b9a52debcd4ba1888af82be8e
2015-09-14T20:20:17Z
mmm a / lib / SILGen / FormalEvaluation . h <nl> ppp b / lib / SILGen / FormalEvaluation . h <nl> class LogicalPathComponent ; <nl> <nl> class FormalAccess { <nl> public : <nl> - enum Kind { Shared , Exclusive , Owned } ; <nl> + enum Kind { Shared , Exclusive , Owned , Unenforced } ; <nl> <nl> private : <nl> unsigned allocatedSize ; <nl> mmm a / lib / SILGen / LValue . h <nl> ppp b / lib / SILGen / LValue . h <nl> struct LLVM_LIBRARY_VISIBILITY ExclusiveBorrowFormalAccess : FormalAccess { <nl> } <nl> } ; <nl> <nl> + struct LLVM_LIBRARY_VISIBILITY UnenforcedAccess { <nl> + / / Make sure someone called ` endAccess ` before destroying this . <nl> + struct DeleterCheck { <nl> + void operator ( ) ( BeginAccessInst * ) { <nl> + llvm_unreachable ( " access scope must be ended " ) ; <nl> + } <nl> + } ; <nl> + typedef std : : unique_ptr < BeginAccessInst , DeleterCheck > BeginAccessPtr ; <nl> + BeginAccessPtr beginAccessPtr ; <nl> + <nl> + UnenforcedAccess ( ) = default ; <nl> + UnenforcedAccess ( const UnenforcedAccess & other ) = delete ; <nl> + UnenforcedAccess ( UnenforcedAccess & & other ) = default ; <nl> + <nl> + UnenforcedAccess & operator = ( const UnenforcedAccess & ) = delete ; <nl> + UnenforcedAccess & operator = ( UnenforcedAccess & & other ) = default ; <nl> + <nl> + / / Return the a new begin_access if it was required , otherwise return the <nl> + / / given ` address ` . <nl> + SILValue beginAccess ( SILGenFunction & SGF , SILLocation loc , SILValue address , <nl> + SILAccessKind kind ) ; <nl> + <nl> + / / End the access and release beginAccessPtr . <nl> + void endAccess ( SILGenFunction & SGF ) ; <nl> + <nl> + / / Emit the end_access ( on a branch ) without marking this access as ended . <nl> + void emitEndAccess ( SILGenFunction & SGF ) ; <nl> + } ; <nl> + <nl> + / / / Pseudo - formal access that emits access markers but does not actually <nl> + / / / require enforcement . It may be used for access to formal memory that is <nl> + / / / exempt from exclusivity checking , such as initialization , or it may be used <nl> + / / / for accesses to local memory that are indistinguishable from formal access <nl> + / / / at the SIL level . Adding the access markers in these cases gives SIL address <nl> + / / / users a structural property that allows for exhaustive verification . <nl> + struct LLVM_LIBRARY_VISIBILITY UnenforcedFormalAccess : FormalAccess { <nl> + <nl> + static SILValue enter ( SILGenFunction & SGF , SILLocation loc , SILValue address , <nl> + SILAccessKind kind ) ; <nl> + <nl> + / / access . beginAccessPtr is either the begin_access or null if no access was <nl> + / / required . <nl> + UnenforcedAccess access ; <nl> + <nl> + UnenforcedFormalAccess ( SILLocation loc , UnenforcedAccess & & access , <nl> + CleanupHandle cleanup ) <nl> + : FormalAccess ( sizeof ( * this ) , FormalAccess : : Unenforced , loc , cleanup ) , <nl> + access ( std : : move ( access ) ) { } <nl> + <nl> + / / Emit the end_access ( on a branch ) without marking this access as ended . <nl> + void emitEndAccess ( SILGenFunction & SGF ) ; <nl> + <nl> + / / Only called at the end formal evaluation scope . End this access . <nl> + void finishImpl ( SILGenFunction & SGF ) override ; <nl> + } ; <nl> + <nl> } / / namespace Lowering <nl> } / / namespace swift <nl> <nl> mmm a / lib / SILGen / SILGenDecl . cpp <nl> ppp b / lib / SILGen / SILGenDecl . cpp <nl> <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> # include " Initialization . h " <nl> + # include " LValue . h " <nl> # include " RValue . h " <nl> # include " SILGen . h " <nl> # include " SILGenDynamicCast . h " <nl> void SingleBufferInitialization : : <nl> copyOrInitValueIntoSingleBuffer ( SILGenFunction & SGF , SILLocation loc , <nl> ManagedValue value , bool isInit , <nl> SILValue destAddr ) { <nl> + / / Emit an unchecked access around initialization of the local buffer to <nl> + / / silence access marker verification . <nl> + / / <nl> + / / FIXME : This is not a good place for FormalEvaluationScope + <nl> + / / UnenforcedFormalAccess . However , there ' s no way to identify the buffer <nl> + / / initialization sequence after SILGen , and no easy way to wrap the <nl> + / / Initialization in an access during top - level expression evaluation . <nl> + FormalEvaluationScope scope ( SGF ) ; <nl> if ( ! isInit ) { <nl> assert ( value . getValue ( ) ! = destAddr & & " copying in place ? ! " ) ; <nl> - value . copyInto ( SGF , destAddr , loc ) ; <nl> + SILValue accessAddr = <nl> + UnenforcedFormalAccess : : enter ( SGF , loc , destAddr , SILAccessKind : : Modify ) ; <nl> + value . copyInto ( SGF , accessAddr , loc ) ; <nl> return ; <nl> } <nl> <nl> / / If we didn ' t evaluate into the initialization buffer , do so now . <nl> if ( value . getValue ( ) ! = destAddr ) { <nl> - value . forwardInto ( SGF , loc , destAddr ) ; <nl> + SILValue accessAddr = <nl> + UnenforcedFormalAccess : : enter ( SGF , loc , destAddr , SILAccessKind : : Modify ) ; <nl> + value . forwardInto ( SGF , loc , accessAddr ) ; <nl> } else { <nl> / / If we did evaluate into the initialization buffer , disable the <nl> / / cleanup . <nl> void EnumElementPatternInitialization : : emitEnumMatch ( <nl> SILValue boxedValue = SGF . B . createProjectBox ( loc , mv . getValue ( ) , 0 ) ; <nl> auto & boxedTL = SGF . getTypeLowering ( boxedValue - > getType ( ) ) ; <nl> / / SEMANTIC ARC TODO : Revisit this when the verifier is enabled . <nl> - if ( boxedTL . isLoadable ( ) | | ! SGF . silConv . useLoweredAddresses ( ) ) <nl> - boxedValue = boxedTL . emitLoad ( SGF . B , loc , boxedValue , <nl> + if ( boxedTL . isLoadable ( ) | | ! SGF . silConv . useLoweredAddresses ( ) ) { <nl> + UnenforcedAccess access ; <nl> + SILValue accessAddress = <nl> + access . beginAccess ( SGF , loc , boxedValue , SILAccessKind : : Read ) ; <nl> + boxedValue = boxedTL . emitLoad ( SGF . B , loc , accessAddress , <nl> LoadOwnershipQualifier : : Take ) ; <nl> - <nl> + access . endAccess ( SGF ) ; <nl> + } <nl> / / We must treat the boxed value as + 0 since it may be shared . Copy it <nl> / / if nontrivial . <nl> / / <nl> mmm a / lib / SILGen / SILGenExpr . cpp <nl> ppp b / lib / SILGen / SILGenExpr . cpp <nl> emitRValueForDecl ( SILLocation loc , ConcreteDeclRef declRef , Type ncRefType , <nl> if ( var - > isLet ( ) ) <nl> guaranteedValid = true ; <nl> <nl> + / / Protect the lvalue read with access markers . The ! is < LValueType > assert <nl> + / / above ensures that the " LValue " is actually immutable , so we use an <nl> + / / unenforced access marker . <nl> + SILValue destAddr = result . getLValueAddress ( ) ; <nl> + SILValue accessAddr = UnenforcedFormalAccess : : enter ( * this , loc , destAddr , <nl> + SILAccessKind : : Read ) ; <nl> + auto propagateRValuePastAccess = [ & ] ( RValue & & rvalue ) { <nl> + / / Check if a new begin_access was emitted and returned as the <nl> + / / RValue . This means that the load did not actually load . If so , then <nl> + / / fix the rvalue to begin_access operand . The end_access cleanup <nl> + / / doesn ' t change . FIXME : this can ' t happen with sil - opaque - values . <nl> + if ( accessAddr ! = destAddr & & rvalue . isComplete ( ) <nl> + & & rvalue . isPlusZero ( * this ) & & ! isa < TupleType > ( rvalue . getType ( ) ) ) { <nl> + auto mv = std : : move ( rvalue ) . getScalarValue ( ) ; <nl> + if ( mv . getValue ( ) = = accessAddr ) <nl> + mv = std : : move ( mv ) . transform ( <nl> + cast < BeginAccessInst > ( accessAddr ) - > getOperand ( ) ) ; <nl> + return RValue ( * this , loc , refType , mv ) ; <nl> + } <nl> + return std : : move ( rvalue ) ; <nl> + } ; <nl> / / If we have self , see if we are in an ' init ' delegation sequence . If so , <nl> / / call out to the special delegation init routine . Otherwise , use the <nl> / / normal RValue emission logic . <nl> if ( var - > getName ( ) = = getASTContext ( ) . Id_self & & <nl> SelfInitDelegationState ! = NormalSelf ) { <nl> - return emitRValueForSelfInDelegationInit ( loc , refType , <nl> - result . getLValueAddress ( ) , C ) ; <nl> + auto rvalue = <nl> + emitRValueForSelfInDelegationInit ( loc , refType , accessAddr , C ) ; <nl> + return propagateRValuePastAccess ( std : : move ( rvalue ) ) ; <nl> } <nl> <nl> / / Avoid computing an abstraction pattern for local variables . <nl> / / This is a slight compile - time optimization , but more importantly <nl> / / it avoids problems where locals don ' t always have interface types . <nl> if ( var - > getDeclContext ( ) - > isLocalContext ( ) ) { <nl> - return RValue ( * this , loc , refType , <nl> - emitLoad ( loc , result . getLValueAddress ( ) , <nl> - getTypeLowering ( refType ) , C , shouldTake , <nl> - guaranteedValid ) ) ; <nl> + auto rvalue = RValue ( * this , loc , refType , <nl> + emitLoad ( loc , accessAddr , getTypeLowering ( refType ) , <nl> + C , shouldTake , guaranteedValid ) ) ; <nl> + <nl> + return propagateRValuePastAccess ( std : : move ( rvalue ) ) ; <nl> } <nl> <nl> / / Otherwise , do the full thing where we potentially bridge and <nl> / / reabstract the declaration . <nl> auto origFormalType = SGM . Types . getAbstractionPattern ( var ) ; <nl> - return RValue ( * this , loc , refType , <nl> - emitLoad ( loc , result . getLValueAddress ( ) , <nl> - origFormalType , refType , <nl> - getTypeLowering ( refType ) , C , shouldTake , <nl> - guaranteedValid ) ) ; <nl> + auto rvalue = RValue ( * this , loc , refType , <nl> + emitLoad ( loc , accessAddr , origFormalType , refType , <nl> + getTypeLowering ( refType ) , C , shouldTake , <nl> + guaranteedValid ) ) ; <nl> + return propagateRValuePastAccess ( std : : move ( rvalue ) ) ; <nl> } <nl> <nl> / / For local decls , use the address we allocated or the value if we have it . <nl> RValue SILGenFunction : : emitRValueForStorageLoad ( <nl> result = result . copyUnmanaged ( * this , loc ) ; <nl> } <nl> } else { <nl> + / / Create a tiny unenforced access scope around a load from local memory . No <nl> + / / cleanup is necessary since we directly emit the load here . This will <nl> + / / probably go away with opaque values . <nl> + UnenforcedAccess access ; <nl> + SILValue accessAddress = <nl> + access . beginAccess ( * this , loc , base . getValue ( ) , SILAccessKind : : Read ) ; <nl> + <nl> / / For address - only sequences , the base is in memory . Emit a <nl> / / struct_element_addr to get to the field , and then load the element as an <nl> / / rvalue . <nl> - SILValue ElementPtr = <nl> - B . createStructElementAddr ( loc , base . getValue ( ) , field ) ; <nl> + SILValue ElementPtr = B . createStructElementAddr ( loc , accessAddress , field ) ; <nl> <nl> result = emitLoad ( loc , ElementPtr , abstractedTL , <nl> hasAbstractionChange ? SGFContext ( ) : C , IsNotTake ) ; <nl> + access . endAccess ( * this ) ; <nl> } <nl> <nl> / / If we ' re accessing this member with an abstraction change , perform that <nl> mmm a / lib / SILGen / SILGenLValue . cpp <nl> ppp b / lib / SILGen / SILGenLValue . cpp <nl> <nl> # include " swift / AST / DiagnosticsSIL . h " <nl> # include " swift / AST / DiagnosticsCommon . h " <nl> # include " swift / AST / GenericEnvironment . h " <nl> + # include " swift / SIL / InstructionUtils . h " <nl> # include " swift / SIL / PrettyStackTrace . h " <nl> # include " swift / SIL / SILArgument . h " <nl> # include " swift / SIL / SILUndef . h " <nl> struct LValueWritebackCleanup : Cleanup { <nl> void dump ( SILGenFunction & ) const override { <nl> # ifndef NDEBUG <nl> llvm : : errs ( ) < < " LValueWritebackCleanup \ n " <nl> - < < " State : " < < getState ( ) < < " Depth : " < < Depth . getDepth ( ) <nl> + < < " State : " < < getState ( ) < < " Depth : " < < Depth . getDepth ( ) <nl> < < " \ n " ; <nl> # endif <nl> } <nl> ManagedValue LogicalPathComponent : : getMaterialized ( SILGenFunction & SGF , <nl> <nl> ManagedValue temp = std : : move ( * this ) . materializeIntoTemporary ( SGF , loc , base ) ; <nl> <nl> + if ( SGF . getOptions ( ) . VerifyExclusivity ) { <nl> + / / Begin an access of the temporary . It is unenforced because enforcement <nl> + / / isn ' t required for RValues . <nl> + SILValue accessAddress = UnenforcedFormalAccess : : enter ( <nl> + SGF , loc , temp . getValue ( ) , SILAccessKind : : Modify ) ; <nl> + temp = std : : move ( temp ) . transform ( accessAddress ) ; <nl> + } <nl> / / Push a writeback for the temporary . <nl> pushWriteback ( SGF , loc , std : : move ( clonedComponent ) , base , <nl> MaterializedLValue ( temp ) ) ; <nl> static SILValue enterAccessScope ( SILGenFunction & SGF , SILLocation loc , <nl> return addr ; <nl> } <nl> <nl> + / / Find the base of the formal access at ` address ` . If the base requires an <nl> + / / access marker , then create a begin_access on ` address ` . Return the <nl> + / / address to be used for the access . <nl> + / / <nl> + / / FIXME : In order to generate more consistent and verifiable SIL patterns , or <nl> + / / subobject projections , create the access on the base address and recreate the <nl> + / / projection . <nl> + SILValue UnenforcedAccess : : beginAccess ( SILGenFunction & SGF , SILLocation loc , <nl> + SILValue address , SILAccessKind kind ) { <nl> + if ( ! SGF . getOptions ( ) . VerifyExclusivity ) <nl> + return address ; <nl> + <nl> + SILValue base = findAccessedAddressBase ( address ) ; <nl> + if ( ! base | | ! isPossibleFormalAccessBase ( base ) ) <nl> + return address ; <nl> + <nl> + auto BAI = <nl> + SGF . B . createBeginAccess ( loc , address , kind , SILAccessEnforcement : : Unsafe ) ; <nl> + beginAccessPtr = BeginAccessPtr ( BAI , DeleterCheck ( ) ) ; <nl> + <nl> + return BAI ; <nl> + } <nl> + <nl> + void UnenforcedAccess : : endAccess ( SILGenFunction & SGF ) { <nl> + emitEndAccess ( SGF ) ; <nl> + beginAccessPtr . release ( ) ; <nl> + } <nl> + <nl> + void UnenforcedAccess : : emitEndAccess ( SILGenFunction & SGF ) { <nl> + if ( ! beginAccessPtr ) <nl> + return ; <nl> + <nl> + SGF . B . createEndAccess ( beginAccessPtr - > getLoc ( ) , beginAccessPtr . get ( ) , <nl> + / * abort * / false ) ; <nl> + } <nl> + <nl> + / / Emit an end_access marker when executing a cleanup ( on a side branch ) . <nl> + void UnenforcedFormalAccess : : emitEndAccess ( SILGenFunction & SGF ) { <nl> + access . emitEndAccess ( SGF ) ; <nl> + } <nl> + <nl> + / / End the access when existing the FormalEvaluationScope . <nl> + void UnenforcedFormalAccess : : finishImpl ( SILGenFunction & SGF ) { <nl> + access . endAccess ( SGF ) ; <nl> + } <nl> + <nl> + namespace { <nl> + struct UnenforcedAccessCleanup : Cleanup { <nl> + FormalEvaluationContext : : stable_iterator Depth ; <nl> + <nl> + UnenforcedAccessCleanup ( ) : Depth ( ) { } <nl> + <nl> + void emit ( SILGenFunction & SGF , CleanupLocation loc ) override { <nl> + auto & evaluation = * SGF . FormalEvalContext . find ( Depth ) ; <nl> + assert ( evaluation . getKind ( ) = = FormalAccess : : Unenforced ) ; <nl> + auto & formalAccess = static_cast < UnenforcedFormalAccess & > ( evaluation ) ; <nl> + formalAccess . emitEndAccess ( SGF ) ; <nl> + } <nl> + <nl> + void dump ( SILGenFunction & ) const override { <nl> + # ifndef NDEBUG <nl> + llvm : : errs ( ) < < " UnenforcedAccessCleanup \ n " <nl> + < < " State : " < < getState ( ) < < " Depth : " < < Depth . getDepth ( ) <nl> + < < " \ n " ; <nl> + # endif <nl> + } <nl> + } ; <nl> + } / / end anonymous namespace <nl> + <nl> + SILValue UnenforcedFormalAccess : : enter ( SILGenFunction & SGF , SILLocation loc , <nl> + SILValue address , SILAccessKind kind ) { <nl> + assert ( SGF . InFormalEvaluationScope ) ; <nl> + <nl> + UnenforcedAccess access ; <nl> + SILValue accessAddress = access . beginAccess ( SGF , loc , address , kind ) ; <nl> + if ( ! access . beginAccessPtr ) <nl> + return address ; <nl> + <nl> + auto & cleanup = SGF . Cleanups . pushCleanup < UnenforcedAccessCleanup > ( ) ; <nl> + CleanupHandle handle = SGF . Cleanups . getTopCleanup ( ) ; <nl> + auto & context = SGF . FormalEvalContext ; <nl> + context . push < UnenforcedFormalAccess > ( loc , std : : move ( access ) , handle ) ; <nl> + cleanup . Depth = context . stable_begin ( ) ; <nl> + <nl> + return accessAddress ; <nl> + } <nl> + <nl> namespace { <nl> class RefElementComponent : public PhysicalPathComponent { <nl> VarDecl * Field ; <nl> namespace { <nl> / / indirectly . <nl> SILValue baseAddress ; <nl> SILValue baseMetatype ; <nl> + UnenforcedAccess baseAccess ; <nl> if ( base ) { <nl> if ( base . getType ( ) . isAddress ( ) ) { <nl> baseAddress = base . getValue ( ) ; <nl> namespace { <nl> baseFormalType ) ; <nl> <nl> baseAddress = SGF . emitTemporaryAllocation ( loc , base . getType ( ) ) ; <nl> + / / Create an unenforced formal access for the temporary base , which <nl> + / / is passed @ inout to the callback . <nl> + baseAddress = baseAccess . beginAccess ( SGF , loc , baseAddress , <nl> + SILAccessKind : : Modify ) ; <nl> if ( base . getOwnershipKind ( ) = = ValueOwnershipKind : : Guaranteed ) { <nl> SGF . B . createStoreBorrow ( loc , base . getValue ( ) , baseAddress ) ; <nl> } else { <nl> namespace { <nl> baseAddress , <nl> baseMetatype <nl> } , false ) ; <nl> + <nl> + if ( baseAccess . beginAccessPtr ) <nl> + baseAccess . endAccess ( SGF ) ; <nl> } <nl> <nl> / / Continue . <nl> mmm a / lib / SILGen / SILGenPattern . cpp <nl> ppp b / lib / SILGen / SILGenPattern . cpp <nl> <nl> # include " Cleanup . h " <nl> # include " ExitableFullExpr . h " <nl> # include " Initialization . h " <nl> + # include " LValue . h " <nl> # include " RValue . h " <nl> # include " SILGen . h " <nl> # include " Scope . h " <nl> void PatternMatchEmission : : emitEnumElementDispatch ( <nl> SILValue boxedValue = SGF . B . createProjectBox ( loc , origCMV . getValue ( ) , 0 ) ; <nl> eltTL = & SGF . getTypeLowering ( boxedValue - > getType ( ) ) ; <nl> if ( eltTL - > isLoadable ( ) ) { <nl> + UnenforcedAccess access ; <nl> + SILValue accessAddress = <nl> + access . beginAccess ( SGF , loc , boxedValue , SILAccessKind : : Read ) ; <nl> ManagedValue newLoadedBoxValue = SGF . B . createLoadBorrow ( <nl> - loc , ManagedValue : : forUnmanaged ( boxedValue ) ) ; <nl> + loc , ManagedValue : : forUnmanaged ( accessAddress ) ) ; <nl> boxedValue = newLoadedBoxValue . getUnmanagedValue ( ) ; <nl> + access . endAccess ( SGF ) ; <nl> } <nl> <nl> / / The boxed value may be shared , so we always have to copy it . <nl>
Emit unenforced access markers in SILGen for accesses to local temporaries .
apple/swift
00b5a9db79d765ed551d79c92ad43c7fdf74911c
2018-02-15T19:26:54Z
mmm a / src / wallet / wallet . cpp <nl> ppp b / src / wallet / wallet . cpp <nl> bool CWallet : : CreateTransaction ( const vector < CRecipient > & vecSend , CWalletTx & wt <nl> return false ; <nl> } <nl> <nl> - if ( nFeeRet > = nFeeNeeded ) <nl> + if ( nFeeRet > = nFeeNeeded ) { <nl> + / / Reduce fee to only the needed amount if we have change <nl> + / / output to increase . This prevents potential overpayment <nl> + / / in fees if the coins selected to meet nFeeNeeded result <nl> + / / in a transaction that requires less fee than the prior <nl> + / / iteration . <nl> + / / TODO : The case where nSubtractFeeFromAmount > 0 remains <nl> + / / to be addressed because it requires returning the fee to <nl> + / / the payees and not the change output . <nl> + / / TODO : The case where there is no change output remains <nl> + / / to be addressed so we avoid creating too small an output . <nl> + if ( nFeeRet > nFeeNeeded & & nChangePosInOut ! = - 1 & & nSubtractFeeFromAmount = = 0 ) { <nl> + CAmount extraFeePaid = nFeeRet - nFeeNeeded ; <nl> + vector < CTxOut > : : iterator change_position = txNew . vout . begin ( ) + nChangePosInOut ; <nl> + change_position - > nValue + = extraFeePaid ; <nl> + nFeeRet - = extraFeePaid ; <nl> + } <nl> break ; / / Done , enough fee included . <nl> + } <nl> <nl> / / Try to reduce change to include necessary fee <nl> if ( nChangePosInOut ! = - 1 & & nSubtractFeeFromAmount = = 0 ) { <nl>
Don ' t overpay fee if we have selected new coins that result in a smaller transaction .
bitcoin/bitcoin
20449ef09edf8f4f51a3e531d947dd89973c2a31
2017-01-06T15:18:56Z
mmm a / src / mongo / SConscript <nl> ppp b / src / mongo / SConscript <nl> env . StaticLibrary ( " coredb " , [ <nl> ' $ BUILD_DIR / mongo / foundation ' ] ) <nl> <nl> coreServerFiles = [ " db / client_basic . cpp " , <nl> - " db / common . cpp " , <nl> " util / net / miniwebserver . cpp " , <nl> " db / indexkey . cpp " , <nl> " db / stats / counters . cpp " , <nl> serverOnlyFiles = [ " db / curop . cpp " , <nl> " db / repl / master_slave . cpp " , <nl> " db / repl / finding_start_cursor . cpp " , <nl> " db / repl / sync . cpp " , <nl> + " db / repl / optime . cpp " , <nl> " db / oplog . cpp " , <nl> " db / prefetch . cpp " , <nl> " db / repl_block . cpp " , <nl> mmm a / src / mongo / bson / bson_db . h <nl> ppp b / src / mongo / bson / bson_db . h <nl> <nl> <nl> # pragma once <nl> <nl> - # include " . . / util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " . . / util / time_support . h " <nl> <nl> namespace mongo { <nl> mmm a / src / mongo / db / common . cpp <nl> ppp b / src / mongo / db / common . cpp <nl> <nl> / * * <nl> * this just has globals <nl> * / <nl> - namespace mongo { <nl> - <nl> - NOINLINE_DECL OpTime OpTime : : skewed ( ) { <nl> - bool toLog = false ; <nl> - ONCE toLog = true ; <nl> - RARELY toLog = true ; <nl> - last . i + + ; <nl> - if ( last . i & 0x80000000 ) <nl> - toLog = true ; <nl> - if ( toLog ) { <nl> - log ( ) < < " clock skew detected prev : " < < last . secs < < " now : " < < ( unsigned ) time ( 0 ) < < endl ; <nl> - } <nl> - if ( last . i & 0x80000000 ) { <nl> - log ( ) < < " error large clock skew detected , shutting down " < < endl ; <nl> - throw ClockSkewException ( ) ; <nl> - } <nl> - return last ; <nl> - } <nl> - <nl> - } <nl> mmm a / src / mongo / db / instance . cpp <nl> ppp b / src / mongo / db / instance . cpp <nl> namespace mongo { <nl> <nl> MONGO_FP_DECLARE ( rsStopGetMore ) ; <nl> <nl> - / * static * / OpTime OpTime : : _now ( ) { <nl> - OpTime result ; <nl> - unsigned t = ( unsigned ) time ( 0 ) ; <nl> - if ( last . secs = = t ) { <nl> - last . i + + ; <nl> - result = last ; <nl> - } <nl> - else if ( t < last . secs ) { <nl> - result = skewed ( ) ; / / separate function to keep out of the hot code path <nl> - } <nl> - else { <nl> - last = OpTime ( t , 1 ) ; <nl> - result = last ; <nl> - } <nl> - notifier . notify_all ( ) ; <nl> - return last ; <nl> - } <nl> - OpTime OpTime : : now ( const mongo : : mutex : : scoped_lock & ) { <nl> - return _now ( ) ; <nl> - } <nl> - OpTime OpTime : : getLast ( const mongo : : mutex : : scoped_lock & ) { <nl> - return last ; <nl> - } <nl> - boost : : condition OpTime : : notifier ; <nl> - mongo : : mutex OpTime : : m ( " optime " ) ; <nl> - <nl> - / / OpTime : : now ( ) uses mutex , thus it is in this file not in the cpp files used by drivers and such <nl> void BSONElementManipulator : : initTimestamp ( ) { <nl> massert ( 10332 , " Expected CurrentTime type " , _element . type ( ) = = Timestamp ) ; <nl> unsigned long long & timestamp = * ( reinterpret_cast < unsigned long long * > ( value ( ) ) ) ; <nl> namespace mongo { <nl> <nl> QueryResult * emptyMoreResult ( long long ) ; <nl> <nl> - void OpTime : : waitForDifferent ( unsigned millis ) { <nl> - mutex : : scoped_lock lk ( m ) ; <nl> - while ( * this = = last ) { <nl> - if ( ! notifier . timed_wait ( lk . boost ( ) , boost : : posix_time : : milliseconds ( millis ) ) ) <nl> - return ; / / timed out <nl> - } <nl> - } <nl> - <nl> bool receivedGetMore ( DbResponse & dbresponse , Message & m , CurOp & curop ) { <nl> bool ok = true ; <nl> <nl> mmm a / src / mongo / db / jsobj . cpp <nl> ppp b / src / mongo / db / jsobj . cpp <nl> <nl> # include " mongo / util / embedded_builder . h " <nl> # include " mongo / util / md5 . hpp " <nl> # include " mongo / util / mongoutils / str . h " <nl> - # include " mongo / util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " mongo / util / startup_test . h " <nl> # include " mongo / util / stringutils . h " <nl> <nl> mmm a / src / mongo / db / jsobj . h <nl> ppp b / src / mongo / db / jsobj . h <nl> <nl> <nl> # include " mongo / pch . h " <nl> # include " . . / bson / util / builder . h " <nl> - # include " . . / util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " . . / bson / bsontypes . h " <nl> # include " . . / bson / oid . h " <nl> # include " . . / bson / bsonelement . h " <nl> mmm a / src / mongo / db / oplog . h <nl> ppp b / src / mongo / db / oplog . h <nl> <nl> # include " db . h " <nl> # include " dbhelpers . h " <nl> # include " clientcursor . h " <nl> - # include " . . / util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " . . / util / timer . h " <nl> <nl> namespace mongo { <nl> namespace mongo { <nl> <nl> void _logOpObjRS ( const BSONObj & op ) ; <nl> <nl> + const char rsoplog [ ] = " local . oplog . rs " ; <nl> + <nl> / * * Write operation to the log ( local . oplog . $ main ) <nl> <nl> @ param opstr <nl> mmm a / src / mongo / db / pipeline / value_internal . h <nl> ppp b / src / mongo / db / pipeline / value_internal . h <nl> <nl> # include " bson / bsonmisc . h " <nl> # include " bson / oid . h " <nl> # include " util / intrusive_counter . h " <nl> - # include " util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> <nl> <nl> namespace mongo { <nl> mmm a / src / mongo / db / repl . h <nl> ppp b / src / mongo / db / repl . h <nl> <nl> # include " pdfile . h " <nl> # include " db . h " <nl> # include " dbhelpers . h " <nl> - # include " . . / util / optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " oplog . h " <nl> # include " . . / util / concurrency / thread_pool . h " <nl> # include " oplogreader . h " <nl> mmm a / src / mongo / db / repl / optime . cpp <nl> ppp b / src / mongo / db / repl / optime . cpp <nl> <nl> <nl> namespace mongo { <nl> <nl> + OpTime OpTime : : last ( 0 , 0 ) ; <nl> + boost : : condition OpTime : : notifier ; <nl> + mongo : : mutex OpTime : : m ( " optime " ) ; <nl> + <nl> NOINLINE_DECL OpTime OpTime : : skewed ( ) { <nl> bool toLog = false ; <nl> ONCE toLog = true ; <nl> namespace mongo { <nl> if ( last . i & 0x80000000 ) <nl> toLog = true ; <nl> if ( toLog ) { <nl> - log ( ) < < " clock skew detected prev : " < < last . secs < < " now : " < < ( unsigned ) time ( 0 ) < < endl ; <nl> + log ( ) < < " clock skew detected prev : " < < last . secs < < " now : " < < ( unsigned ) time ( 0 ) <nl> + < < std : : endl ; <nl> } <nl> if ( last . i & 0x80000000 ) { <nl> - log ( ) < < " error large clock skew detected , shutting down " < < endl ; <nl> + log ( ) < < " error large clock skew detected , shutting down " < < std : : endl ; <nl> throw ClockSkewException ( ) ; <nl> } <nl> return last ; <nl> mmm a / src / mongo / db / repl / optime . h <nl> ppp b / src / mongo / db / repl / optime . h <nl> <nl> - / / optime . h - OpTime class <nl> - <nl> / * Copyright 2009 10gen Inc . <nl> * <nl> * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> <nl> # pragma once <nl> <nl> # include < boost / thread / condition . hpp > <nl> + # include < iostream > <nl> + # include < sstream > <nl> + <nl> + # include " mongo / bson / util / misc . h " / / time_t_to_String <nl> + # include " mongo / util / assert_util . h " <nl> + # include " mongo / util / concurrency / mutex . h " <nl> <nl> namespace mongo { <nl> <nl> namespace mongo { <nl> string toStringLong ( ) const { <nl> char buf [ 64 ] ; <nl> time_t_to_String ( secs , buf ) ; <nl> - stringstream ss ; <nl> + std : : stringstream ss ; <nl> ss < < time_t_to_String_short ( secs ) < < ' ' ; <nl> - ss < < hex < < secs < < ' : ' < < i ; <nl> + ss < < std : : hex < < secs < < ' : ' < < i ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> string toStringPretty ( ) const { <nl> - stringstream ss ; <nl> - ss < < time_t_to_String_short ( secs ) < < ' : ' < < hex < < i ; <nl> + std : : stringstream ss ; <nl> + ss < < time_t_to_String_short ( secs ) < < ' : ' < < std : : hex < < i ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> string toString ( ) const { <nl> - stringstream ss ; <nl> - ss < < hex < < secs < < ' : ' < < i ; <nl> + std : : stringstream ss ; <nl> + ss < < std : : hex < < secs < < ' : ' < < i ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> mmm a / src / mongo / db / repl / rs . h <nl> ppp b / src / mongo / db / repl / rs . h <nl> <nl> # include " mongo / db / repl / rs_config . h " <nl> # include " mongo / db / repl / rs_exception . h " <nl> # include " mongo / db / repl / rs_member . h " <nl> - # include " mongo / db / repl / rs_optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " mongo / db / repl / rs_sync . h " <nl> # include " mongo / util / concurrency / list . h " <nl> # include " mongo / util / concurrency / msg . h " <nl> mmm a / src / mongo / db / repl / rs_initialsync . cpp <nl> ppp b / src / mongo / db / repl / rs_initialsync . cpp <nl> <nl> # include " mongo / db / oplogreader . h " <nl> # include " mongo / db / repl . h " <nl> # include " mongo / db / repl / bgsync . h " <nl> - # include " mongo / db / repl / rs_optime . h " <nl> + # include " mongo / db / repl / optime . h " <nl> # include " mongo / db / repl / rs_sync . h " <nl> # include " mongo / util / mongoutils / str . h " <nl> <nl> mmm a / src / mongo / util / util . cpp <nl> ppp b / src / mongo / util / util . cpp <nl> <nl> # include " mongo / util / stacktrace . h " <nl> # include " mongo / util / startup_test . h " <nl> # include " file_allocator . h " <nl> - # include " optime . h " <nl> # include " time_support . h " <nl> # include " mongoutils / str . h " <nl> # include " timer . h " <nl> namespace mongo { <nl> } <nl> } utilTest ; <nl> <nl> - OpTime OpTime : : last ( 0 , 0 ) ; <nl> - <nl> ostream & operator < < ( ostream & s , const ThreadSafeString & o ) { <nl> s < < o . toString ( ) ; <nl> return s ; <nl>
SERVER - 7772 move all of optime into optime . cpp / . h
mongodb/mongo
a8c05c5fd10f1aa9a57b7edbe0589d4a0b17f5b0
2013-03-11T15:15:02Z
mmm a / README . md <nl> ppp b / README . md <nl> Supported Cars <nl> | Honda | Pilot 2016 - 18 | Honda Sensing | openpilot | 25mph < sup > 1 < / sup > | 12mph | <nl> | Honda | Pilot 2019 | All | openpilot | 25mph < sup > 1 < / sup > | 12mph | <nl> | Honda | Ridgeline 2017 - 20 | Honda Sensing | openpilot | 25mph < sup > 1 < / sup > | 12mph | <nl> + | Hyundai | Palisade 2020 | All | Stock | 0mph | 0mph | <nl> | Hyundai | Sonata 2020 | All | Stock | 0mph | 0mph | <nl> | Lexus | CT Hybrid 2017 - 18 | All | Stock < sup > 3 < / sup > | 0mph | 0mph | <nl> | Lexus | ES 2019 | All | openpilot | 0mph | 0mph | <nl> Community Maintained Cars and Features <nl> | Hyundai | Ioniq Electric Limited 2019 | SCC + LKAS | Stock | 0mph | 32mph | <nl> | Hyundai | Kona 2020 | SCC + LKAS | Stock | 0mph | 0mph | <nl> | Hyundai | Kona EV 2019 | SCC + LKAS | Stock | 0mph | 0mph | <nl> - | Hyundai | Palisade 2020 | All | Stock | 0mph | 0mph | <nl> | Hyundai | Santa Fe 2019 | All | Stock | 0mph | 0mph | <nl> | Hyundai | Sonata 2019 | All | Stock | 0mph | 0mph | <nl> | Hyundai | Veloster 2019 | SCC + LKAS | Stock | 5mph | 0mph | <nl> mmm a / selfdrive / car / hyundai / interface . py <nl> ppp b / selfdrive / car / hyundai / interface . py <nl> def get_params ( candidate , fingerprint = gen_empty_fingerprint ( ) , has_relay = False , <nl> ret . radarOffCan = True <nl> <nl> # Most Hyundai car ports are community features for now <nl> - ret . communityFeature = candidate not in [ CAR . SONATA ] <nl> + ret . communityFeature = candidate not in [ CAR . SONATA , CAR . PALISADE ] <nl> <nl> ret . steerActuatorDelay = 0 . 1 # Default delay <nl> ret . steerRateCost = 0 . 5 <nl>
promote hyundai palisade to offically supported ( )
commaai/openpilot
b5466002ad33ba5f6ccde64713c4ae2daf282332
2020-09-18T04:35:30Z
new file mode 100644 <nl> index 00000000000 . . 093032b860b <nl> mmm / dev / null <nl> ppp b / tests / cases / selectadd . ll <nl> <nl> + <nl> + ; ModuleID = ' tests / hello_world . bc ' <nl> + target datalayout = " e - p : 32 : 32 : 32 - i1 : 8 : 8 - i8 : 8 : 8 - i16 : 16 : 16 - i32 : 32 : 32 - i64 : 32 : 64 - f32 : 32 : 32 - f64 : 32 : 64 - v64 : 64 : 64 - v128 : 128 : 128 - a0 : 0 : 64 - f80 : 32 : 32 - n8 : 16 : 32 - S128 " <nl> + target triple = " i386 - pc - linux - gnu " <nl> + <nl> + @ . str = private unnamed_addr constant [ 15 x i8 ] c " hello , world ! \ 0A \ 00 " , align 1 ; [ # uses = 1 type = [ 15 x i8 ] * ] <nl> + <nl> + ; [ # uses = 0 ] <nl> + define i32 @ main ( ) { <nl> + entry : <nl> + br label % zero <nl> + <nl> + zero : <nl> + % . 3 . ph . i757 = phi i8 * [ getelementptr ( [ 15 x i8 ] * @ . str , i32 0 , i32 add ( i32 xor ( i32 ptrtoint ( i8 * getelementptr ( [ 15 x i8 ] * @ . str , i32 0 , i32 select ( i1 icmp ugt ( i32 sub ( i32 0 , i32 add ( i32 ptrtoint ( [ 15 x i8 ] * @ . str to i32 ) , i32 25 ) ) , i32 xor ( i32 ptrtoint ( [ 15 x i8 ] * @ . str to i32 ) , i32 - 1 ) ) , i32 sub ( i32 0 , i32 add ( i32 ptrtoint ( [ 15 x i8 ] * @ . str to i32 ) , i32 25 ) ) , i32 xor ( i32 ptrtoint ( [ 15 x i8 ] * @ . str to i32 ) , i32 - 1 ) ) ) to i32 ) , i32 - 1 ) , i32 25 ) ) , % entry ] , [ getelementptr ( [ 15 x i8 ] * @ . str , i32 0 , i32 ptrtoint ( i8 * getelementptr ( [ 15 x i8 ] * @ . str , i32 0 , i32 add ( i32 sub ( i32 0 , i32 ptrtoint ( [ 15 x i8 ] * @ . str to i32 ) ) , i32 25 ) ) to i32 ) ) , % other ] <nl> + <nl> + % retval = alloca i32 , align 4 ; [ # uses = 1 type = i32 * ] <nl> + store i32 0 , i32 * % retval <nl> + % call = call i32 ( i8 * , . . . ) * @ printf ( i8 * getelementptr inbounds ( [ 15 x i8 ] * @ . str , i32 0 , i32 0 ) ) ; [ # uses = 0 type = i32 ] <nl> + br label % other <nl> + <nl> + other : <nl> + br i1 0 , label % zero , label % last <nl> + <nl> + last : <nl> + ret i32 1 <nl> + } <nl> + <nl> + declare i32 @ printf ( i8 * , . . . ) <nl> + <nl>
add testcase for select fix
emscripten-core/emscripten
71ea2d712934c28b866a19041d3d9459398d9528
2013-11-04T22:54:38Z
mmm a / include / envoy / stats / histogram . h <nl> ppp b / include / envoy / stats / histogram . h <nl> class HistogramStatistics { <nl> * class ( Sinks , in particular ) will need to explicitly differentiate between histograms <nl> * representing durations and histograms representing other types of data . <nl> * / <nl> - class Histogram : public virtual Metric , public RefcountHelper { <nl> + class Histogram : public Metric { <nl> public : <nl> ~ Histogram ( ) override = default ; <nl> <nl> using HistogramSharedPtr = RefcountPtr < Histogram > ; <nl> / * * <nl> * A histogram that is stored in main thread and provides summary view of the histogram . <nl> * / <nl> - class ParentHistogram : public virtual Histogram { <nl> + class ParentHistogram : public Histogram { <nl> public : <nl> ~ ParentHistogram ( ) override = default ; <nl> <nl> mmm a / include / envoy / stats / stats . h <nl> ppp b / include / envoy / stats / stats . h <nl> struct Tag ; <nl> / * * <nl> * General interface for all stats objects . <nl> * / <nl> - class Metric { <nl> + class Metric : public RefcountInterface { <nl> public : <nl> virtual ~ Metric ( ) = default ; <nl> / * * <nl> class Metric { <nl> * / <nl> virtual std : : vector < Tag > tags ( ) const PURE ; <nl> <nl> + / * * <nl> + * See a more detailed description in tagExtractedStatName ( ) , which is the <nl> + * preferred API to use when feasible . This API needs to compose the <nl> + * std : : string on the fly , and return it by value . <nl> + * <nl> + * @ return The stat name with all tag values extracted , as a std : : string . <nl> + * / <nl> + virtual std : : string tagExtractedName ( ) const PURE ; <nl> + <nl> / * * <nl> * Returns the name of the Metric with the portions designated as tags removed <nl> * as a string . For example , The stat name " vhost . foo . vcluster . bar . c1 " would <nl> class Metric { <nl> * value of tag " vcluster " . Thus the tagExtractedName is simply <nl> * " vhost . vcluster . c1 " . <nl> * <nl> - * @ return The stat name with all tag values extracted . <nl> - * / <nl> - virtual std : : string tagExtractedName ( ) const PURE ; <nl> - <nl> - / * * <nl> - * Returns the name of the Metric with the portions designated as tags <nl> - * removed as a StatName <nl> + * @ return the name of the Metric with the portions designated as tags <nl> + * removed . <nl> * / <nl> virtual StatName tagExtractedStatName ( ) const PURE ; <nl> <nl> class Metric { <nl> * global counter as well as periodic counter . Calling latch ( ) returns the periodic counter and <nl> * clears it . <nl> * / <nl> - class Counter : public virtual Metric , public RefcountInterface { <nl> + class Counter : public Metric { <nl> public : <nl> ~ Counter ( ) override = default ; <nl> <nl> using CounterSharedPtr = RefcountPtr < Counter > ; <nl> / * * <nl> * A gauge that can both increment and decrement . <nl> * / <nl> - class Gauge : public virtual Metric , public RefcountInterface { <nl> + class Gauge : public Metric { <nl> public : <nl> enum class ImportMode { <nl> Uninitialized , / / Gauge was discovered during hot - restart transfer . <nl> mmm a / source / common / stats / heap_stat_data . cc <nl> ppp b / source / common / stats / heap_stat_data . cc <nl> HeapStatDataAllocator : : ~ HeapStatDataAllocator ( ) { <nl> ASSERT ( gauges_ . empty ( ) ) ; <nl> } <nl> <nl> - HeapStatData * HeapStatData : : alloc ( StatName stat_name , SymbolTable & symbol_table ) { <nl> - symbol_table . incRefCount ( stat_name ) ; <nl> - return new ( stat_name . size ( ) ) HeapStatData ( stat_name ) ; <nl> - } <nl> - <nl> - void HeapStatData : : free ( SymbolTable & symbol_table ) { <nl> - ASSERT ( ref_count_ = = 0 ) ; <nl> - symbol_table . free ( statName ( ) ) ; <nl> - delete this ; <nl> - } <nl> - <nl> void HeapStatDataAllocator : : removeCounterFromSet ( Counter * counter ) { <nl> Thread : : LockGuard lock ( mutex_ ) ; <nl> const size_t count = counters_ . erase ( counter - > statName ( ) ) ; <nl> void HeapStatDataAllocator : : debugPrint ( ) { <nl> } <nl> # endif <nl> <nl> - class CounterImpl : public Counter , public MetricImpl { <nl> + / / Counter and Gauge both inherit from from RefcountInterface and <nl> + / / Metric . MetricImpl takes care of most of the Metric API , but we need to cover <nl> + / / symbolTable ( ) here , which we don ' t store directly , but get it via the alloc , <nl> + / / which we need in order to clean up the counter and gauge maps in that class <nl> + / / when they are destroyed . <nl> + / / <nl> + / / We implement the RefcountInterface API , using 16 bits that would otherwise be <nl> + / / wasted in the alignment padding next to flags_ . <nl> + template < class BaseClass > class StatsSharedImpl : public MetricImpl < BaseClass > { <nl> public : <nl> - CounterImpl ( HeapStatData & data , HeapStatDataAllocator & alloc , <nl> - absl : : string_view tag_extracted_name , const std : : vector < Tag > & tags ) <nl> - : MetricImpl ( tag_extracted_name , tags , alloc . symbolTable ( ) ) , data_ ( data ) , alloc_ ( alloc ) { } <nl> + StatsSharedImpl ( StatName name , HeapStatDataAllocator & alloc , absl : : string_view tag_extracted_name , <nl> + const std : : vector < Tag > & tags ) <nl> + : MetricImpl < BaseClass > ( name , tag_extracted_name , tags , alloc . symbolTable ( ) ) , alloc_ ( alloc ) { } <nl> <nl> - ~ CounterImpl ( ) override { <nl> + ~ StatsSharedImpl ( ) override { <nl> / / MetricImpl must be explicitly cleared ( ) before destruction , otherwise it <nl> / / will not be able to access the SymbolTable & to free the symbols . An RAII <nl> / / alternative would be to store the SymbolTable reference in the <nl> / / MetricImpl , costing 8 bytes per stat . <nl> - MetricImpl : : clear ( ) ; <nl> - alloc_ . removeCounterFromSet ( this ) ; <nl> - data_ . free ( symbolTable ( ) ) ; <nl> - } <nl> - <nl> - / / Stats : : Counter <nl> - void add ( uint64_t amount ) override { <nl> - data_ . value_ + = amount ; <nl> - data_ . pending_increment_ + = amount ; <nl> - data_ . flags_ | = Flags : : Used ; <nl> + this - > clear ( symbolTable ( ) ) ; <nl> } <nl> - void inc ( ) override { add ( 1 ) ; } <nl> - uint64_t latch ( ) override { return data_ . pending_increment_ . exchange ( 0 ) ; } <nl> - void reset ( ) override { data_ . value_ = 0 ; } <nl> - bool used ( ) const override { return data_ . flags_ & Flags : : Used ; } <nl> - uint64_t value ( ) const override { return data_ . value_ ; } <nl> <nl> + / / Metric <nl> SymbolTable & symbolTable ( ) override { return alloc_ . symbolTable ( ) ; } <nl> - StatName statName ( ) const override { return data_ . statName ( ) ; } <nl> + bool used ( ) const override { return flags_ & Metric : : Flags : : Used ; } <nl> <nl> / / RefcountInterface <nl> - void incRefCount ( ) override { + + data_ . ref_count_ ; } <nl> + void incRefCount ( ) override { + + ref_count_ ; } <nl> bool decRefCount ( ) override { <nl> - ASSERT ( data_ . ref_count_ > = 1 ) ; <nl> - return - - data_ . ref_count_ = = 0 ; <nl> + ASSERT ( ref_count_ > = 1 ) ; <nl> + return - - ref_count_ = = 0 ; <nl> } <nl> - uint32_t use_count ( ) const override { return data_ . ref_count_ ; } <nl> + uint32_t use_count ( ) const override { return ref_count_ ; } <nl> <nl> - private : <nl> - HeapStatData & data_ ; <nl> + protected : <nl> HeapStatDataAllocator & alloc_ ; <nl> + <nl> + / / Holds backing store for both CounterImpl and GaugeImpl . This provides a level <nl> + / / of indirection needed to enable stats created with the same name from <nl> + / / different scopes to share the same value . <nl> + std : : atomic < uint64_t > value_ { 0 } ; <nl> + std : : atomic < uint64_t > pending_increment_ { 0 } ; <nl> + std : : atomic < uint16_t > flags_ { 0 } ; <nl> + std : : atomic < uint16_t > ref_count_ { 0 } ; <nl> + } ; <nl> + <nl> + class CounterImpl : public StatsSharedImpl < Counter > { <nl> + public : <nl> + CounterImpl ( StatName name , HeapStatDataAllocator & alloc , absl : : string_view tag_extracted_name , <nl> + const std : : vector < Tag > & tags ) <nl> + : StatsSharedImpl ( name , alloc , tag_extracted_name , tags ) { } <nl> + ~ CounterImpl ( ) override { alloc_ . removeCounterFromSet ( this ) ; } <nl> + <nl> + / / Stats : : Counter <nl> + void add ( uint64_t amount ) override { <nl> + / / Note that a reader may see a new value but an old pending_increment_ or <nl> + / / used ( ) . From a system perspective this should be eventually consistent . <nl> + value_ + = amount ; <nl> + pending_increment_ + = amount ; <nl> + flags_ | = Flags : : Used ; <nl> + } <nl> + void inc ( ) override { add ( 1 ) ; } <nl> + uint64_t latch ( ) override { return pending_increment_ . exchange ( 0 ) ; } <nl> + void reset ( ) override { value_ = 0 ; } <nl> + bool used ( ) const override { return flags_ & Flags : : Used ; } <nl> + uint64_t value ( ) const override { return value_ ; } <nl> } ; <nl> <nl> - class GaugeImpl : public Gauge , public MetricImpl { <nl> + class GaugeImpl : public StatsSharedImpl < Gauge > { <nl> public : <nl> - GaugeImpl ( HeapStatData & data , HeapStatDataAllocator & alloc , absl : : string_view tag_extracted_name , <nl> + GaugeImpl ( StatName name , HeapStatDataAllocator & alloc , absl : : string_view tag_extracted_name , <nl> const std : : vector < Tag > & tags , ImportMode import_mode ) <nl> - : MetricImpl ( tag_extracted_name , tags , alloc . symbolTable ( ) ) , data_ ( data ) , alloc_ ( alloc ) { <nl> + : StatsSharedImpl ( name , alloc , tag_extracted_name , tags ) { <nl> switch ( import_mode ) { <nl> case ImportMode : : Accumulate : <nl> - data_ . flags_ | = Flags : : LogicAccumulate ; <nl> + flags_ | = Flags : : LogicAccumulate ; <nl> break ; <nl> case ImportMode : : NeverImport : <nl> - data_ . flags_ | = Flags : : NeverImport ; <nl> + flags_ | = Flags : : NeverImport ; <nl> break ; <nl> case ImportMode : : Uninitialized : <nl> / / Note that we don ' t clear any flag bits for import_mode = = Uninitialized , <nl> class GaugeImpl : public Gauge , public MetricImpl { <nl> break ; <nl> } <nl> } <nl> - <nl> - ~ GaugeImpl ( ) override { <nl> - / / MetricImpl must be explicitly cleared ( ) before destruction , otherwise it <nl> - / / will not be able to access the SymbolTable & to free the symbols . An RAII <nl> - / / alternative would be to store the SymbolTable reference in the <nl> - / / MetricImpl , costing 8 bytes per stat . <nl> - MetricImpl : : clear ( ) ; <nl> - alloc_ . removeGaugeFromSet ( this ) ; <nl> - data_ . free ( symbolTable ( ) ) ; <nl> - } <nl> + ~ GaugeImpl ( ) override { alloc_ . removeGaugeFromSet ( this ) ; } <nl> <nl> / / Stats : : Gauge <nl> void add ( uint64_t amount ) override { <nl> - data_ . value_ + = amount ; <nl> - data_ . flags_ | = Flags : : Used ; <nl> + value_ + = amount ; <nl> + flags_ | = Flags : : Used ; <nl> } <nl> void dec ( ) override { sub ( 1 ) ; } <nl> void inc ( ) override { add ( 1 ) ; } <nl> void set ( uint64_t value ) override { <nl> - data_ . value_ = value ; <nl> - data_ . flags_ | = Flags : : Used ; <nl> + value_ = value ; <nl> + flags_ | = Flags : : Used ; <nl> } <nl> void sub ( uint64_t amount ) override { <nl> - ASSERT ( data_ . value_ > = amount ) ; <nl> + ASSERT ( value_ > = amount ) ; <nl> ASSERT ( used ( ) | | amount = = 0 ) ; <nl> - data_ . value_ - = amount ; <nl> + value_ - = amount ; <nl> } <nl> - uint64_t value ( ) const override { return data_ . value_ ; } <nl> - bool used ( ) const override { return data_ . flags_ & Flags : : Used ; } <nl> + uint64_t value ( ) const override { return value_ ; } <nl> <nl> ImportMode importMode ( ) const override { <nl> - if ( data_ . flags_ & Flags : : NeverImport ) { <nl> + if ( flags_ & Flags : : NeverImport ) { <nl> return ImportMode : : NeverImport ; <nl> - } else if ( data_ . flags_ & Flags : : LogicAccumulate ) { <nl> + } else if ( flags_ & Flags : : LogicAccumulate ) { <nl> return ImportMode : : Accumulate ; <nl> } <nl> return ImportMode : : Uninitialized ; <nl> class GaugeImpl : public Gauge , public MetricImpl { <nl> break ; <nl> case ImportMode : : Accumulate : <nl> ASSERT ( current = = ImportMode : : Uninitialized ) ; <nl> - data_ . flags_ | = Flags : : LogicAccumulate ; <nl> + flags_ | = Flags : : LogicAccumulate ; <nl> break ; <nl> case ImportMode : : NeverImport : <nl> ASSERT ( current = = ImportMode : : Uninitialized ) ; <nl> / / A previous revision of Envoy may have transferred a gauge that it <nl> / / thought was Accumulate . But the new version thinks it ' s NeverImport , so <nl> / / we clear the accumulated value . <nl> - data_ . value_ = 0 ; <nl> - data_ . flags_ & = ~ Flags : : Used ; <nl> - data_ . flags_ | = Flags : : NeverImport ; <nl> + value_ = 0 ; <nl> + flags_ & = ~ Flags : : Used ; <nl> + flags_ | = Flags : : NeverImport ; <nl> break ; <nl> } <nl> } <nl> - <nl> - SymbolTable & symbolTable ( ) override { return alloc_ . symbolTable ( ) ; } <nl> - StatName statName ( ) const override { return data_ . statName ( ) ; } <nl> - <nl> - / / RefcountInterface <nl> - void incRefCount ( ) override { + + data_ . ref_count_ ; } <nl> - bool decRefCount ( ) override { <nl> - ASSERT ( data_ . ref_count_ > = 1 ) ; <nl> - return - - data_ . ref_count_ = = 0 ; <nl> - } <nl> - uint32_t use_count ( ) const override { return data_ . ref_count_ ; } <nl> - <nl> - private : <nl> - HeapStatData & data_ ; <nl> - HeapStatDataAllocator & alloc_ ; <nl> } ; <nl> <nl> CounterSharedPtr HeapStatDataAllocator : : makeCounter ( StatName name , <nl> absl : : string_view tag_extracted_name , <nl> const std : : vector < Tag > & tags ) { <nl> Thread : : LockGuard lock ( mutex_ ) ; <nl> + ASSERT ( gauges_ . find ( name ) = = gauges_ . end ( ) ) ; <nl> auto iter = counters_ . find ( name ) ; <nl> if ( iter ! = counters_ . end ( ) ) { <nl> return CounterSharedPtr ( * iter ) ; <nl> } <nl> - auto counter = CounterSharedPtr ( <nl> - new CounterImpl ( * HeapStatData : : alloc ( name , symbolTable ( ) ) , * this , tag_extracted_name , tags ) ) ; <nl> + auto counter = CounterSharedPtr ( new CounterImpl ( name , * this , tag_extracted_name , tags ) ) ; <nl> counters_ . insert ( counter . get ( ) ) ; <nl> return counter ; <nl> } <nl> GaugeSharedPtr HeapStatDataAllocator : : makeGauge ( StatName name , absl : : string_view <nl> const std : : vector < Tag > & tags , <nl> Gauge : : ImportMode import_mode ) { <nl> Thread : : LockGuard lock ( mutex_ ) ; <nl> + ASSERT ( counters_ . find ( name ) = = counters_ . end ( ) ) ; <nl> auto iter = gauges_ . find ( name ) ; <nl> if ( iter ! = gauges_ . end ( ) ) { <nl> return GaugeSharedPtr ( * iter ) ; <nl> } <nl> - auto gauge = GaugeSharedPtr ( new GaugeImpl ( * HeapStatData : : alloc ( name , symbolTable ( ) ) , * this , <nl> - tag_extracted_name , tags , import_mode ) ) ; <nl> + auto gauge = GaugeSharedPtr ( new GaugeImpl ( name , * this , tag_extracted_name , tags , import_mode ) ) ; <nl> gauges_ . insert ( gauge . get ( ) ) ; <nl> return gauge ; <nl> } <nl> mmm a / source / common / stats / heap_stat_data . h <nl> ppp b / source / common / stats / heap_stat_data . h <nl> <nl> namespace Envoy { <nl> namespace Stats { <nl> <nl> - / * * <nl> - * Holds backing store for both CounterImpl and GaugeImpl . This provides a level <nl> - * of indirection needed to enable stats created with the same name from <nl> - * different scopes to share the same value . <nl> - * / <nl> - struct HeapStatData : public InlineStorage { <nl> - private : <nl> - explicit HeapStatData ( StatName stat_name ) { stat_name . copyToStorage ( symbol_storage_ ) ; } <nl> - <nl> - public : <nl> - static HeapStatData * alloc ( StatName stat_name , SymbolTable & symbol_table ) ; <nl> - <nl> - void free ( SymbolTable & symbol_table ) ; <nl> - StatName statName ( ) const { return StatName ( symbol_storage_ ) ; } <nl> - <nl> - bool operator = = ( const HeapStatData & rhs ) const { return statName ( ) = = rhs . statName ( ) ; } <nl> - uint64_t hash ( ) const { return statName ( ) . hash ( ) ; } <nl> - <nl> - std : : atomic < uint64_t > value_ { 0 } ; <nl> - std : : atomic < uint64_t > pending_increment_ { 0 } ; <nl> - std : : atomic < uint16_t > flags_ { 0 } ; <nl> - std : : atomic < uint16_t > ref_count_ { 0 } ; <nl> - SymbolTable : : Storage symbol_storage_ ; / / This is a ' using ' nickname for uint8_t [ ] . <nl> - } ; <nl> - <nl> class HeapStatDataAllocator : public StatDataAllocator { <nl> public : <nl> HeapStatDataAllocator ( SymbolTable & symbol_table ) : symbol_table_ ( symbol_table ) { } <nl> ~ HeapStatDataAllocator ( ) override ; <nl> <nl> - HeapStatData & alloc ( StatName name ) ; <nl> void removeCounterFromSet ( Counter * counter ) ; <nl> void removeGaugeFromSet ( Gauge * gauge ) ; <nl> <nl> mmm a / source / common / stats / histogram_impl . h <nl> ppp b / source / common / stats / histogram_impl . h <nl> class HistogramStatisticsImpl : public HistogramStatistics , NonCopyable { <nl> double sample_sum_ ; <nl> } ; <nl> <nl> + class HistogramImplHelper : public MetricImpl < Histogram > { <nl> + public : <nl> + HistogramImplHelper ( StatName name , const std : : string & tag_extracted_name , <nl> + const std : : vector < Tag > & tags , SymbolTable & symbol_table ) <nl> + : MetricImpl < Histogram > ( name , tag_extracted_name , tags , symbol_table ) { } <nl> + HistogramImplHelper ( SymbolTable & symbol_table ) : MetricImpl < Histogram > ( symbol_table ) { } <nl> + <nl> + / / RefcountInterface <nl> + void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> + bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> + uint32_t use_count ( ) const override { return refcount_helper_ . use_count ( ) ; } <nl> + <nl> + private : <nl> + RefcountHelper refcount_helper_ ; <nl> + } ; <nl> + <nl> / * * <nl> * Histogram implementation for the heap . <nl> * / <nl> - class HistogramImpl : public Histogram , public MetricImpl { <nl> + class HistogramImpl : public HistogramImplHelper { <nl> public : <nl> HistogramImpl ( StatName name , Store & parent , const std : : string & tag_extracted_name , <nl> const std : : vector < Tag > & tags ) <nl> - : MetricImpl ( tag_extracted_name , tags , parent . symbolTable ( ) ) , <nl> - name_ ( name , parent . symbolTable ( ) ) , parent_ ( parent ) { } <nl> + : HistogramImplHelper ( name , tag_extracted_name , tags , parent . symbolTable ( ) ) , parent_ ( parent ) { <nl> + } <nl> ~ HistogramImpl ( ) { <nl> - / / We must explicitly free the StatName here using the SymbolTable reference <nl> - / / we access via parent_ . A pure RAII alternative would be to use <nl> - / / StatNameManagedStorage rather than StatNameStorage , which will cost a total <nl> - / / of 16 bytes per stat , counting the extra SymbolTable & reference here , <nl> - / / plus the extra SymbolTable & reference in MetricImpl . <nl> - name_ . free ( symbolTable ( ) ) ; <nl> - <nl> / / We must explicitly free the StatName here in order to supply the <nl> / / SymbolTable reference . An RAII alternative would be to store a <nl> / / reference to the SymbolTable in MetricImpl , which would cost 8 bytes <nl> / / per stat . <nl> - MetricImpl : : clear ( ) ; <nl> + MetricImpl : : clear ( symbolTable ( ) ) ; <nl> } <nl> <nl> / / Stats : : Histogram <nl> void recordValue ( uint64_t value ) override { parent_ . deliverHistogramToSinks ( * this , value ) ; } <nl> <nl> bool used ( ) const override { return true ; } <nl> - StatName statName ( ) const override { return name_ . statName ( ) ; } <nl> SymbolTable & symbolTable ( ) override { return parent_ . symbolTable ( ) ; } <nl> <nl> private : <nl> - StatNameStorage name_ ; <nl> - <nl> / / This is used for delivering the histogram data to sinks . <nl> Store & parent_ ; <nl> } ; <nl> class HistogramImpl : public Histogram , public MetricImpl { <nl> * Null histogram implementation . <nl> * No - ops on all calls and requires no underlying metric or data . <nl> * / <nl> - class NullHistogramImpl : public Histogram , NullMetricImpl { <nl> + class NullHistogramImpl : public HistogramImplHelper { <nl> public : <nl> - explicit NullHistogramImpl ( SymbolTable & symbol_table ) : NullMetricImpl ( symbol_table ) { } <nl> - ~ NullHistogramImpl ( ) override { <nl> - / / MetricImpl must be explicitly cleared ( ) before destruction , otherwise it <nl> - / / will not be able to access the SymbolTable & to free the symbols . An RAII <nl> - / / alternative would be to store the SymbolTable reference in the <nl> - / / MetricImpl , costing 8 bytes per stat . <nl> - MetricImpl : : clear ( ) ; <nl> - } <nl> + explicit NullHistogramImpl ( SymbolTable & symbol_table ) <nl> + : HistogramImplHelper ( symbol_table ) , symbol_table_ ( symbol_table ) { } <nl> + ~ NullHistogramImpl ( ) { MetricImpl : : clear ( symbol_table_ ) ; } <nl> + <nl> + bool used ( ) const override { return false ; } <nl> + SymbolTable & symbolTable ( ) override { return symbol_table_ ; } <nl> <nl> void recordValue ( uint64_t ) override { } <nl> + <nl> + private : <nl> + SymbolTable & symbol_table_ ; <nl> } ; <nl> <nl> } / / namespace Stats <nl> mmm a / source / common / stats / metric_impl . cc <nl> ppp b / source / common / stats / metric_impl . cc <nl> <nl> namespace Envoy { <nl> namespace Stats { <nl> <nl> - MetricImpl : : ~ MetricImpl ( ) { <nl> - / / The storage must be cleaned by a subclass of MetricImpl in its <nl> + MetricHelper : : ~ MetricHelper ( ) { <nl> + / / The storage must be cleaned by a subclass of MetricHelper in its <nl> / / destructor , because the symbol - table is owned by the subclass . <nl> - / / Simply call MetricImpl : : clear ( ) in the subclass dtor . <nl> + / / Simply call MetricHelper : : clear ( ) in the subclass dtor . <nl> ASSERT ( ! stat_names_ . populated ( ) ) ; <nl> } <nl> <nl> - MetricImpl : : MetricImpl ( absl : : string_view tag_extracted_name , const std : : vector < Tag > & tags , <nl> - SymbolTable & symbol_table ) { <nl> + MetricHelper : : MetricHelper ( absl : : string_view name , absl : : string_view tag_extracted_name , <nl> + const std : : vector < Tag > & tags , SymbolTable & symbol_table ) { <nl> / / Encode all the names and tags into transient storage so we can count the <nl> - / / required bytes . 1 is added to account for the tag_extracted_name , and we <nl> - / / multiply the number of tags by 2 to account for the name and value of each <nl> - / / tag . <nl> - const uint32_t num_names = 1 + 2 * tags . size ( ) ; <nl> + / / required bytes . 2 is added to account for the name and tag_extracted_name , <nl> + / / and we multiply the number of tags by 2 to account for the name and value <nl> + / / of each tag . <nl> + const uint32_t num_names = 2 + 2 * tags . size ( ) ; <nl> STACK_ARRAY ( names , absl : : string_view , num_names ) ; <nl> - names [ 0 ] = tag_extracted_name ; <nl> - int index = 0 ; <nl> + names [ 0 ] = name ; <nl> + names [ 1 ] = tag_extracted_name ; <nl> + int index = 1 ; <nl> for ( auto & tag : tags ) { <nl> names [ + + index ] = tag . name_ ; <nl> names [ + + index ] = tag . value_ ; <nl> MetricImpl : : MetricImpl ( absl : : string_view tag_extracted_name , const std : : vector < T <nl> symbol_table . populateList ( names . begin ( ) , num_names , stat_names_ ) ; <nl> } <nl> <nl> - void MetricImpl : : clear ( ) { stat_names_ . clear ( symbolTable ( ) ) ; } <nl> - <nl> - std : : string MetricImpl : : tagExtractedName ( ) const { <nl> - return constSymbolTable ( ) . toString ( tagExtractedStatName ( ) ) ; <nl> - } <nl> - <nl> - StatName MetricImpl : : tagExtractedStatName ( ) const { <nl> + StatName MetricHelper : : statName ( ) const { <nl> StatName stat_name ; <nl> stat_names_ . iterate ( [ & stat_name ] ( StatName s ) - > bool { <nl> stat_name = s ; <nl> StatName MetricImpl : : tagExtractedStatName ( ) const { <nl> return stat_name ; <nl> } <nl> <nl> - void MetricImpl : : iterateTagStatNames ( const TagStatNameIterFn & fn ) const { <nl> - enum { TagExtractedName , TagName , TagValue } state = TagExtractedName ; <nl> + StatName MetricHelper : : tagExtractedStatName ( ) const { <nl> + / / The name is the first element in stat_names_ . The second is the <nl> + / / tag - extracted - name . We don ' t have random access in that format , <nl> + / / so we iterate through them , skipping the first element ( name ) , <nl> + / / and terminating the iteration after capturing the tag - extracted <nl> + / / name by returning false from the lambda . <nl> + StatName tag_extracted_stat_name ; <nl> + bool skip = true ; <nl> + stat_names_ . iterate ( [ & tag_extracted_stat_name , & skip ] ( StatName s ) - > bool { <nl> + if ( skip ) { <nl> + skip = false ; <nl> + return true ; <nl> + } <nl> + tag_extracted_stat_name = s ; <nl> + return false ; / / Returning ' false ' stops the iteration . <nl> + } ) ; <nl> + return tag_extracted_stat_name ; <nl> + } <nl> + <nl> + void MetricHelper : : iterateTagStatNames ( const Metric : : TagStatNameIterFn & fn ) const { <nl> + enum { Name , TagExtractedName , TagName , TagValue } state = Name ; <nl> StatName tag_name ; <nl> <nl> / / StatNameList maintains a linear ordered collection of StatNames , and we <nl> void MetricImpl : : iterateTagStatNames ( const TagStatNameIterFn & fn ) const { <nl> / / as we iterate through the stat_names_ . <nl> stat_names_ . iterate ( [ & state , & tag_name , & fn ] ( StatName stat_name ) - > bool { <nl> switch ( state ) { <nl> + case Name : <nl> + state = TagExtractedName ; <nl> + break ; <nl> case TagExtractedName : <nl> state = TagName ; <nl> break ; <nl> void MetricImpl : : iterateTagStatNames ( const TagStatNameIterFn & fn ) const { <nl> ASSERT ( state ! = TagValue ) ; <nl> } <nl> <nl> - void MetricImpl : : iterateTags ( const TagIterFn & fn ) const { <nl> - const SymbolTable & symbol_table = constSymbolTable ( ) ; <nl> + void MetricHelper : : iterateTags ( const SymbolTable & symbol_table , const Metric : : TagIterFn & fn ) const { <nl> iterateTagStatNames ( [ & fn , & symbol_table ] ( StatName name , StatName value ) - > bool { <nl> return fn ( Tag { symbol_table . toString ( name ) , symbol_table . toString ( value ) } ) ; <nl> } ) ; <nl> } <nl> <nl> - std : : vector < Tag > MetricImpl : : tags ( ) const { <nl> + std : : vector < Tag > MetricHelper : : tags ( const SymbolTable & symbol_table ) const { <nl> std : : vector < Tag > tags ; <nl> - iterateTags ( [ & tags ] ( const Tag & tag ) - > bool { <nl> + iterateTags ( symbol_table , [ & tags ] ( const Tag & tag ) - > bool { <nl> tags . emplace_back ( tag ) ; <nl> return true ; <nl> } ) ; <nl> mmm a / source / common / stats / metric_impl . h <nl> ppp b / source / common / stats / metric_impl . h <nl> namespace Envoy { <nl> namespace Stats { <nl> <nl> / * * <nl> - * Implementation of the Metric interface . Virtual inheritance is used because the interfaces that <nl> - * will inherit from Metric will have other base classes that will also inherit from Metric . <nl> + * Helper class for implementing Metrics . This does not participate in any <nl> + * inheritance chains , but can be instantiated by classes that do . It just <nl> + * implements the mechanics of representing the name , tag - extracted - name , <nl> + * and all tags as a StatNameList . <nl> + * / <nl> + class MetricHelper { <nl> + public : <nl> + MetricHelper ( absl : : string_view name , absl : : string_view tag_extracted_name , <nl> + const std : : vector < Tag > & tags , SymbolTable & symbol_table ) ; <nl> + ~ MetricHelper ( ) ; <nl> + <nl> + StatName statName ( ) const ; <nl> + std : : string name ( const SymbolTable & symbol_table ) const ; <nl> + std : : vector < Tag > tags ( const SymbolTable & symbol_table ) const ; <nl> + StatName tagExtractedStatName ( ) const ; <nl> + void iterateTagStatNames ( const Metric : : TagStatNameIterFn & fn ) const ; <nl> + void iterateTags ( const SymbolTable & symbol_table , const Metric : : TagIterFn & fn ) const ; <nl> + void clear ( SymbolTable & symbol_table ) { stat_names_ . clear ( symbol_table ) ; } <nl> + <nl> + private : <nl> + StatNameList stat_names_ ; <nl> + } ; <nl> + <nl> + / * * <nl> + * Partial implementation of the Metric interface on behalf of Counters , Gauges , <nl> + * and Histograms . It leaves symbolTable ( ) unimplemented so that implementations <nl> + * of stats managed by an allocator , specifically Counters and Gauges , can keep <nl> + * a reference to the allocator instead , and derive the symbolTable ( ) from that . <nl> * <nl> - * MetricImpl is not meant to be instantiated as - is . For performance reasons we keep name ( ) virtual <nl> - * and expect child classes to implement it . <nl> + * We templatize on the base class ( Counter , Gauge , or Histogram ) , rather than <nl> + * using multiple virtual inheritance , as this avoids the overhead of an extra <nl> + * vptr per instance . This is important for stats because there can be many <nl> + * stats in systems with large numbers of clusters and hosts , and a few 8 - byte <nl> + * pointers per - stat here and there can add up to significant amounts of memory . <nl> + * <nl> + * Note the delegation of the implementation to a helper class , which is neither <nl> + * templatized nor virtual . This avoids having the compiler elaborate complete <nl> + * copies of the underlying implementation for each base class during template <nl> + * expansion . <nl> * / <nl> - class MetricImpl : public virtual Metric { <nl> + template < class BaseClass > class MetricImpl : public BaseClass { <nl> public : <nl> - MetricImpl ( absl : : string_view tag_extracted_name , const std : : vector < Tag > & tags , <nl> - SymbolTable & symbol_table ) ; <nl> - ~ MetricImpl ( ) ; <nl> + MetricImpl ( absl : : string_view name , absl : : string_view tag_extracted_name , <nl> + const std : : vector < Tag > & tags , SymbolTable & symbol_table ) <nl> + : helper_ ( name , tag_extracted_name , tags , symbol_table ) { } <nl> + <nl> + / / Alternate API to take the name as a StatName , which is needed at most call - sites . <nl> + / / TODO ( jmarantz ) : refactor impl to either be able to pass string_view at call - sites <nl> + / / always , or to make it more efficient to populate a StatNameList with a mixture of <nl> + / / StatName and string_view . <nl> + MetricImpl ( StatName name , absl : : string_view tag_extracted_name , const std : : vector < Tag > & tags , <nl> + SymbolTable & symbol_table ) <nl> + : MetricImpl ( symbol_table . toString ( name ) , tag_extracted_name , tags , symbol_table ) { } <nl> <nl> - std : : string name ( ) const override { return constSymbolTable ( ) . toString ( statName ( ) ) ; } <nl> - std : : string tagExtractedName ( ) const override ; <nl> - std : : vector < Tag > tags ( ) const override ; <nl> - StatName tagExtractedStatName ( ) const override ; <nl> - void iterateTagStatNames ( const TagStatNameIterFn & fn ) const override ; <nl> - void iterateTags ( const TagIterFn & fn ) const override ; <nl> + explicit MetricImpl ( SymbolTable & symbol_table ) <nl> + : MetricImpl ( " " , " " , std : : vector < Tag > ( ) , symbol_table ) { } <nl> + <nl> + std : : vector < Tag > tags ( ) const override { return helper_ . tags ( constSymbolTable ( ) ) ; } <nl> + StatName statName ( ) const override { return helper_ . statName ( ) ; } <nl> + StatName tagExtractedStatName ( ) const override { return helper_ . tagExtractedStatName ( ) ; } <nl> + void iterateTagStatNames ( const Metric : : TagStatNameIterFn & fn ) const override { <nl> + helper_ . iterateTagStatNames ( fn ) ; <nl> + } <nl> + void iterateTags ( const Metric : : TagIterFn & fn ) const override { <nl> + helper_ . iterateTags ( constSymbolTable ( ) , fn ) ; <nl> + } <nl> <nl> - / / Metric implementations must each implement Metric : : symbolTable ( ) . However , <nl> - / / they can inherit the const version of that accessor from MetricImpl . <nl> const SymbolTable & constSymbolTable ( ) const override { <nl> / / Cast our ' this ' , which is of type ` const MetricImpl * ` to a non - const <nl> / / pointer , so we can use it to call the subclass implementation of <nl> class MetricImpl : public virtual Metric { <nl> / / provide const and non - const variants of a method . <nl> return const_cast < MetricImpl * > ( this ) - > symbolTable ( ) ; <nl> } <nl> + std : : string name ( ) const override { return constSymbolTable ( ) . toString ( this - > statName ( ) ) ; } <nl> + std : : string tagExtractedName ( ) const override { <nl> + return constSymbolTable ( ) . toString ( this - > tagExtractedStatName ( ) ) ; <nl> + } <nl> <nl> protected : <nl> - void clear ( ) ; <nl> - <nl> - private : <nl> - StatNameList stat_names_ ; <nl> - } ; <nl> - <nl> - class NullMetricImpl : public MetricImpl { <nl> - public : <nl> - explicit NullMetricImpl ( SymbolTable & symbol_table ) <nl> - : MetricImpl ( " " , std : : vector < Tag > ( ) , symbol_table ) , stat_name_storage_ ( " " , symbol_table ) { } <nl> - <nl> - SymbolTable & symbolTable ( ) override { return stat_name_storage_ . symbolTable ( ) ; } <nl> - bool used ( ) const override { return false ; } <nl> - StatName statName ( ) const override { return stat_name_storage_ . statName ( ) ; } <nl> + void clear ( SymbolTable & symbol_table ) { helper_ . clear ( symbol_table ) ; } <nl> <nl> private : <nl> - StatNameManagedStorage stat_name_storage_ ; <nl> + MetricHelper helper_ ; <nl> } ; <nl> <nl> } / / namespace Stats <nl> mmm a / source / common / stats / null_counter . h <nl> ppp b / source / common / stats / null_counter . h <nl> namespace Stats { <nl> * Null counter implementation . <nl> * No - ops on all calls and requires no underlying metric or data . <nl> * / <nl> - class NullCounterImpl : public Counter , NullMetricImpl { <nl> + class NullCounterImpl : public MetricImpl < Counter > { <nl> public : <nl> - explicit NullCounterImpl ( SymbolTable & symbol_table ) : NullMetricImpl ( symbol_table ) { } <nl> + explicit NullCounterImpl ( SymbolTable & symbol_table ) <nl> + : MetricImpl < Counter > ( symbol_table ) , symbol_table_ ( symbol_table ) { } <nl> ~ NullCounterImpl ( ) override { <nl> / / MetricImpl must be explicitly cleared ( ) before destruction , otherwise it <nl> / / will not be able to access the SymbolTable & to free the symbols . An RAII <nl> / / alternative would be to store the SymbolTable reference in the <nl> / / MetricImpl , costing 8 bytes per stat . <nl> - MetricImpl : : clear ( ) ; <nl> + MetricImpl : : clear ( symbolTable ( ) ) ; <nl> } <nl> <nl> void add ( uint64_t ) override { } <nl> class NullCounterImpl : public Counter , NullMetricImpl { <nl> void reset ( ) override { } <nl> uint64_t value ( ) const override { return 0 ; } <nl> <nl> + / / Metric <nl> + bool used ( ) const override { return false ; } <nl> + SymbolTable & symbolTable ( ) override { return symbol_table_ ; } <nl> + <nl> / / RefcountInterface <nl> void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> class NullCounterImpl : public Counter , NullMetricImpl { <nl> <nl> private : <nl> RefcountHelper refcount_helper_ ; <nl> + SymbolTable & symbol_table_ ; <nl> } ; <nl> <nl> } / / namespace Stats <nl> mmm a / source / common / stats / null_gauge . h <nl> ppp b / source / common / stats / null_gauge . h <nl> namespace Stats { <nl> * Null gauge implementation . <nl> * No - ops on all calls and requires no underlying metric or data . <nl> * / <nl> - class NullGaugeImpl : public Gauge , NullMetricImpl { <nl> + class NullGaugeImpl : public MetricImpl < Gauge > { <nl> public : <nl> - explicit NullGaugeImpl ( SymbolTable & symbol_table ) : NullMetricImpl ( symbol_table ) { } <nl> + explicit NullGaugeImpl ( SymbolTable & symbol_table ) <nl> + : MetricImpl < Gauge > ( symbol_table ) , symbol_table_ ( symbol_table ) { } <nl> ~ NullGaugeImpl ( ) override { <nl> / / MetricImpl must be explicitly cleared ( ) before destruction , otherwise it <nl> / / will not be able to access the SymbolTable & to free the symbols . An RAII <nl> / / alternative would be to store the SymbolTable reference in the <nl> / / MetricImpl , costing 8 bytes per stat . <nl> - MetricImpl : : clear ( ) ; <nl> + MetricImpl : : clear ( symbolTable ( ) ) ; <nl> } <nl> <nl> void add ( uint64_t ) override { } <nl> class NullGaugeImpl : public Gauge , NullMetricImpl { <nl> ImportMode importMode ( ) const override { return ImportMode : : NeverImport ; } <nl> void mergeImportMode ( ImportMode / * import_mode * / ) override { } <nl> <nl> + / / Metric <nl> + bool used ( ) const override { return false ; } <nl> + SymbolTable & symbolTable ( ) override { return symbol_table_ ; } <nl> + <nl> / / RefcountInterface <nl> void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> class NullGaugeImpl : public Gauge , NullMetricImpl { <nl> <nl> private : <nl> RefcountHelper refcount_helper_ ; <nl> + SymbolTable & symbol_table_ ; <nl> } ; <nl> <nl> } / / namespace Stats <nl> mmm a / source / common / stats / thread_local_store . cc <nl> ppp b / source / common / stats / thread_local_store . cc <nl> Histogram & ThreadLocalStoreImpl : : ScopeImpl : : tlsHistogram ( StatName name , <nl> } <nl> <nl> ThreadLocalHistogramImpl : : ThreadLocalHistogramImpl ( StatName name , <nl> - absl : : string_view tag_extracted_name , <nl> + const std : : string & tag_extracted_name , <nl> const std : : vector < Tag > & tags , <nl> SymbolTable & symbol_table ) <nl> - : MetricImpl ( tag_extracted_name , tags , symbol_table ) , current_active_ ( 0 ) , used_ ( false ) , <nl> - created_thread_id_ ( std : : this_thread : : get_id ( ) ) , name_ ( name , symbol_table ) , <nl> - symbol_table_ ( symbol_table ) { <nl> + : HistogramImplHelper ( name , tag_extracted_name , tags , symbol_table ) , current_active_ ( 0 ) , <nl> + used_ ( false ) , created_thread_id_ ( std : : this_thread : : get_id ( ) ) , symbol_table_ ( symbol_table ) { <nl> histograms_ [ 0 ] = hist_alloc ( ) ; <nl> histograms_ [ 1 ] = hist_alloc ( ) ; <nl> } <nl> <nl> ThreadLocalHistogramImpl : : ~ ThreadLocalHistogramImpl ( ) { <nl> - MetricImpl : : clear ( ) ; <nl> - name_ . free ( symbolTable ( ) ) ; <nl> + MetricImpl : : clear ( symbolTable ( ) ) ; <nl> hist_free ( histograms_ [ 0 ] ) ; <nl> hist_free ( histograms_ [ 1 ] ) ; <nl> } <nl> void ThreadLocalHistogramImpl : : merge ( histogram_t * target ) { <nl> ParentHistogramImpl : : ParentHistogramImpl ( StatName name , Store & parent , TlsScope & tls_scope , <nl> absl : : string_view tag_extracted_name , <nl> const std : : vector < Tag > & tags ) <nl> - : MetricImpl ( tag_extracted_name , tags , parent . symbolTable ( ) ) , parent_ ( parent ) , <nl> + : MetricImpl ( name , tag_extracted_name , tags , parent . symbolTable ( ) ) , parent_ ( parent ) , <nl> tls_scope_ ( tls_scope ) , interval_histogram_ ( hist_alloc ( ) ) , cumulative_histogram_ ( hist_alloc ( ) ) , <nl> interval_statistics_ ( interval_histogram_ ) , cumulative_statistics_ ( cumulative_histogram_ ) , <nl> - merged_ ( false ) , name_ ( name , parent . symbolTable ( ) ) { } <nl> + merged_ ( false ) { } <nl> <nl> ParentHistogramImpl : : ~ ParentHistogramImpl ( ) { <nl> - MetricImpl : : clear ( ) ; <nl> - name_ . free ( symbolTable ( ) ) ; <nl> + MetricImpl : : clear ( symbolTable ( ) ) ; <nl> hist_free ( interval_histogram_ ) ; <nl> hist_free ( cumulative_histogram_ ) ; <nl> } <nl> mmm a / source / common / stats / thread_local_store . h <nl> ppp b / source / common / stats / thread_local_store . h <nl> namespace Stats { <nl> * histograms , one to collect the values and other as backup that is used for merge process . The <nl> * swap happens during the merge process . <nl> * / <nl> - class ThreadLocalHistogramImpl : public Histogram , public MetricImpl { <nl> + class ThreadLocalHistogramImpl : public HistogramImplHelper { <nl> public : <nl> - ThreadLocalHistogramImpl ( StatName name , absl : : string_view tag_extracted_name , <nl> + ThreadLocalHistogramImpl ( StatName name , const std : : string & tag_extracted_name , <nl> const std : : vector < Tag > & tags , SymbolTable & symbol_table ) ; <nl> ~ ThreadLocalHistogramImpl ( ) override ; <nl> <nl> class ThreadLocalHistogramImpl : public Histogram , public MetricImpl { <nl> bool used ( ) const override { return used_ ; } <nl> <nl> / / Stats : : Metric <nl> - StatName statName ( ) const override { return name_ . statName ( ) ; } <nl> SymbolTable & symbolTable ( ) override { return symbol_table_ ; } <nl> <nl> private : <nl> class ThreadLocalHistogramImpl : public Histogram , public MetricImpl { <nl> histogram_t * histograms_ [ 2 ] ; <nl> std : : atomic < bool > used_ ; <nl> std : : thread : : id created_thread_id_ ; <nl> - StatNameStorage name_ ; <nl> SymbolTable & symbol_table_ ; <nl> } ; <nl> <nl> class TlsScope ; <nl> / * * <nl> * Log Linear Histogram implementation that is stored in the main thread . <nl> * / <nl> - class ParentHistogramImpl : public ParentHistogram , public MetricImpl { <nl> + class ParentHistogramImpl : public MetricImpl < ParentHistogram > { <nl> public : <nl> ParentHistogramImpl ( StatName name , Store & parent , TlsScope & tlsScope , <nl> absl : : string_view tag_extracted_name , const std : : vector < Tag > & tags ) ; <nl> ~ ParentHistogramImpl ( ) override ; <nl> <nl> void addTlsHistogram ( const TlsHistogramSharedPtr & hist_ptr ) ; <nl> - bool used ( ) const override ; <nl> void recordValue ( uint64_t value ) override ; <nl> <nl> / * * <nl> class ParentHistogramImpl : public ParentHistogram , public MetricImpl { <nl> const std : : string bucketSummary ( ) const override ; <nl> <nl> / / Stats : : Metric <nl> - StatName statName ( ) const override { return name_ . statName ( ) ; } <nl> SymbolTable & symbolTable ( ) override { return parent_ . symbolTable ( ) ; } <nl> + bool used ( ) const override ; <nl> + <nl> + / / RefcountInterface <nl> + void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> + bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> + uint32_t use_count ( ) const override { return refcount_helper_ . use_count ( ) ; } <nl> <nl> private : <nl> bool usedLockHeld ( ) const EXCLUSIVE_LOCKS_REQUIRED ( merge_lock_ ) ; <nl> class ParentHistogramImpl : public ParentHistogram , public MetricImpl { <nl> mutable Thread : : MutexBasicLockable merge_lock_ ; <nl> std : : list < TlsHistogramSharedPtr > tls_histograms_ GUARDED_BY ( merge_lock_ ) ; <nl> bool merged_ ; <nl> - StatNameStorage name_ ; <nl> + RefcountHelper refcount_helper_ ; <nl> } ; <nl> <nl> using ParentHistogramImplSharedPtr = RefcountPtr < ParentHistogramImpl > ; <nl> mmm a / test / common / stats / BUILD <nl> ppp b / test / common / stats / BUILD <nl> load ( <nl> envoy_package ( ) <nl> <nl> envoy_cc_test ( <nl> - name = " heap_stat_data_test " , <nl> - srcs = [ " heap_stat_data_test . cc " ] , <nl> + name = " heap_allocator_test " , <nl> + srcs = [ " heap_allocator_test . cc " ] , <nl> deps = [ <nl> " / / source / common / stats : fake_symbol_table_lib " , <nl> " / / source / common / stats : heap_stat_data_lib " , <nl> new file mode 100644 <nl> index 00000000000 . . 770257332d9 <nl> mmm / dev / null <nl> ppp b / test / common / stats / heap_allocator_test . cc <nl> <nl> + # include < string > <nl> + <nl> + # include " common / stats / fake_symbol_table_impl . h " <nl> + # include " common / stats / heap_stat_data . h " <nl> + <nl> + # include " test / test_common / logging . h " <nl> + <nl> + # include " gtest / gtest . h " <nl> + <nl> + namespace Envoy { <nl> + namespace Stats { <nl> + namespace { <nl> + <nl> + class HeapAllocatorTest : public testing : : Test { <nl> + protected : <nl> + HeapAllocatorTest ( ) : alloc_ ( symbol_table_ ) , pool_ ( symbol_table_ ) { } <nl> + ~ HeapAllocatorTest ( ) { clearStorage ( ) ; } <nl> + <nl> + StatNameStorage makeStatStorage ( absl : : string_view name ) { <nl> + return StatNameStorage ( name , symbol_table_ ) ; <nl> + } <nl> + <nl> + StatName makeStat ( absl : : string_view name ) { return pool_ . add ( name ) ; } <nl> + <nl> + void clearStorage ( ) { <nl> + pool_ . clear ( ) ; <nl> + EXPECT_EQ ( 0 , symbol_table_ . numSymbols ( ) ) ; <nl> + } <nl> + <nl> + FakeSymbolTableImpl symbol_table_ ; <nl> + HeapStatDataAllocator alloc_ ; <nl> + StatNamePool pool_ ; <nl> + } ; <nl> + <nl> + / / Allocate 2 counters of the same name , and you ' ll get the same object . <nl> + TEST_F ( HeapAllocatorTest , CountersWithSameName ) { <nl> + StatName counter_name = makeStat ( " counter . name " ) ; <nl> + CounterSharedPtr c1 = alloc_ . makeCounter ( counter_name , " " , std : : vector < Tag > ( ) ) ; <nl> + EXPECT_EQ ( 1 , c1 - > use_count ( ) ) ; <nl> + CounterSharedPtr c2 = alloc_ . makeCounter ( counter_name , " " , std : : vector < Tag > ( ) ) ; <nl> + EXPECT_EQ ( 2 , c1 - > use_count ( ) ) ; <nl> + EXPECT_EQ ( 2 , c2 - > use_count ( ) ) ; <nl> + EXPECT_EQ ( c1 . get ( ) , c2 . get ( ) ) ; <nl> + EXPECT_FALSE ( c1 - > used ( ) ) ; <nl> + EXPECT_FALSE ( c2 - > used ( ) ) ; <nl> + c1 - > inc ( ) ; <nl> + EXPECT_TRUE ( c1 - > used ( ) ) ; <nl> + EXPECT_TRUE ( c2 - > used ( ) ) ; <nl> + c2 - > inc ( ) ; <nl> + EXPECT_EQ ( 2 , c1 - > value ( ) ) ; <nl> + EXPECT_EQ ( 2 , c2 - > value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( HeapAllocatorTest , GaugesWithSameName ) { <nl> + StatName gauge_name = makeStat ( " gauges . name " ) ; <nl> + GaugeSharedPtr g1 = <nl> + alloc_ . makeGauge ( gauge_name , " " , std : : vector < Tag > ( ) , Gauge : : ImportMode : : Accumulate ) ; <nl> + EXPECT_EQ ( 1 , g1 - > use_count ( ) ) ; <nl> + GaugeSharedPtr g2 = <nl> + alloc_ . makeGauge ( gauge_name , " " , std : : vector < Tag > ( ) , Gauge : : ImportMode : : Accumulate ) ; <nl> + EXPECT_EQ ( 2 , g1 - > use_count ( ) ) ; <nl> + EXPECT_EQ ( 2 , g2 - > use_count ( ) ) ; <nl> + EXPECT_EQ ( g1 . get ( ) , g2 . get ( ) ) ; <nl> + EXPECT_FALSE ( g1 - > used ( ) ) ; <nl> + EXPECT_FALSE ( g2 - > used ( ) ) ; <nl> + g1 - > inc ( ) ; <nl> + EXPECT_TRUE ( g1 - > used ( ) ) ; <nl> + EXPECT_TRUE ( g2 - > used ( ) ) ; <nl> + EXPECT_EQ ( 1 , g1 - > value ( ) ) ; <nl> + EXPECT_EQ ( 1 , g2 - > value ( ) ) ; <nl> + g2 - > dec ( ) ; <nl> + EXPECT_EQ ( 0 , g1 - > value ( ) ) ; <nl> + EXPECT_EQ ( 0 , g2 - > value ( ) ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + } / / namespace Stats <nl> + } / / namespace Envoy <nl> deleted file mode 100644 <nl> index 315c6b685c3 . . 00000000000 <nl> mmm a / test / common / stats / heap_stat_data_test . cc <nl> ppp / dev / null <nl> <nl> - # include < string > <nl> - <nl> - # include " common / stats / fake_symbol_table_impl . h " <nl> - # include " common / stats / heap_stat_data . h " <nl> - <nl> - # include " test / test_common / logging . h " <nl> - <nl> - # include " gtest / gtest . h " <nl> - <nl> - namespace Envoy { <nl> - namespace Stats { <nl> - namespace { <nl> - <nl> - class HeapStatDataTest : public testing : : Test { <nl> - protected : <nl> - HeapStatDataTest ( ) : alloc_ ( symbol_table_ ) , pool_ ( symbol_table_ ) { } <nl> - ~ HeapStatDataTest ( ) { clearStorage ( ) ; } <nl> - <nl> - StatNameStorage makeStatStorage ( absl : : string_view name ) { <nl> - return StatNameStorage ( name , symbol_table_ ) ; <nl> - } <nl> - <nl> - StatName makeStat ( absl : : string_view name ) { return pool_ . add ( name ) ; } <nl> - <nl> - void clearStorage ( ) { <nl> - pool_ . clear ( ) ; <nl> - EXPECT_EQ ( 0 , symbol_table_ . numSymbols ( ) ) ; <nl> - } <nl> - <nl> - FakeSymbolTableImpl symbol_table_ ; <nl> - HeapStatDataAllocator alloc_ ; <nl> - StatNamePool pool_ ; <nl> - } ; <nl> - <nl> - / / No truncation occurs in the implementation of HeapStatData . <nl> - TEST_F ( HeapStatDataTest , HeapNoTruncate ) { <nl> - const std : : string long_string ( 128 , ' A ' ) ; <nl> - StatName stat_name = makeStat ( long_string ) ; <nl> - HeapStatData * stat { } ; <nl> - EXPECT_NO_LOGS ( stat = HeapStatData : : alloc ( stat_name , symbol_table_ ) ) ; <nl> - EXPECT_EQ ( stat - > statName ( ) , stat_name ) ; <nl> - stat - > free ( symbol_table_ ) ; <nl> - } ; <nl> - <nl> - TEST_F ( HeapStatDataTest , HeapAlloc ) { <nl> - HeapStatData * stat_1 = HeapStatData : : alloc ( makeStat ( " ref_name " ) , symbol_table_ ) ; <nl> - ASSERT_NE ( stat_1 , nullptr ) ; <nl> - HeapStatData * stat_2 = HeapStatData : : alloc ( makeStat ( " ref_name " ) , symbol_table_ ) ; <nl> - ASSERT_NE ( stat_2 , nullptr ) ; <nl> - HeapStatData * stat_3 = HeapStatData : : alloc ( makeStat ( " not_ref_name " ) , symbol_table_ ) ; <nl> - ASSERT_NE ( stat_3 , nullptr ) ; <nl> - EXPECT_NE ( stat_1 , stat_2 ) ; <nl> - EXPECT_NE ( stat_1 , stat_3 ) ; <nl> - EXPECT_NE ( stat_2 , stat_3 ) ; <nl> - stat_1 - > free ( symbol_table_ ) ; <nl> - stat_2 - > free ( symbol_table_ ) ; <nl> - stat_3 - > free ( symbol_table_ ) ; <nl> - } <nl> - <nl> - } / / namespace <nl> - } / / namespace Stats <nl> - } / / namespace Envoy <nl> mmm a / test / common / stats / metric_impl_test . cc <nl> ppp b / test / common / stats / metric_impl_test . cc <nl> TEST_F ( MetricImplTest , OneTag ) { <nl> ASSERT_EQ ( 1 , tags . size ( ) ) ; <nl> EXPECT_EQ ( " name " , tags [ 0 ] . name_ ) ; <nl> EXPECT_EQ ( " value " , tags [ 0 ] . value_ ) ; <nl> + EXPECT_EQ ( " counter . name . value " , counter - > name ( ) ) ; <nl> EXPECT_EQ ( " counter " , counter - > tagExtractedName ( ) ) ; <nl> EXPECT_EQ ( makeStat ( " counter " ) , counter - > tagExtractedStatName ( ) ) ; <nl> } <nl> mmm a / test / common / stats / thread_local_store_test . cc <nl> ppp b / test / common / stats / thread_local_store_test . cc <nl> TEST ( StatsThreadLocalStoreTestNoFixture , MemoryWithoutTls ) { <nl> TestUtil : : forEachSampleStat ( <nl> 1000 , [ & store ] ( absl : : string_view name ) { store . counter ( std : : string ( name ) ) ; } ) ; <nl> const size_t million = 1000 * 1000 ; <nl> - EXPECT_MEMORY_EQ ( memory_test . consumedBytes ( ) , 17432336 ) ; / / June 29 , 2019 <nl> - EXPECT_MEMORY_LE ( memory_test . consumedBytes ( ) , 18 * million ) ; <nl> + EXPECT_MEMORY_EQ ( memory_test . consumedBytes ( ) , 15268336 ) ; / / June 30 , 2019 <nl> + EXPECT_MEMORY_LE ( memory_test . consumedBytes ( ) , 16 * million ) ; <nl> } <nl> <nl> TEST ( StatsThreadLocalStoreTestNoFixture , MemoryWithTls ) { <nl> TEST ( StatsThreadLocalStoreTestNoFixture , MemoryWithTls ) { <nl> TestUtil : : forEachSampleStat ( <nl> 1000 , [ & store ] ( absl : : string_view name ) { store . counter ( std : : string ( name ) ) ; } ) ; <nl> const size_t million = 1000 * 1000 ; <nl> - EXPECT_MEMORY_EQ ( memory_test . consumedBytes ( ) , 19660848 ) ; / / June 29 , 2019 <nl> - EXPECT_MEMORY_LE ( memory_test . consumedBytes ( ) , 20 * million ) ; <nl> + EXPECT_MEMORY_EQ ( memory_test . consumedBytes ( ) , 17496848 ) ; / / June 30 , 2019 <nl> + EXPECT_MEMORY_LE ( memory_test . consumedBytes ( ) , 18 * million ) ; <nl> store . shutdownThreading ( ) ; <nl> tls . shutdownThread ( ) ; <nl> } <nl> mmm a / test / integration / stats_integration_test . cc <nl> ppp b / test / integration / stats_integration_test . cc <nl> TEST_P ( ClusterMemoryTestRunner , MemoryLargeClusterSizeWithStats ) { <nl> / / 2019 / 06 / 06 7208 49650 make memory targets approximate <nl> / / 2019 / 06 / 17 7243 49412 49700 macros for exact / upper - bound memory checks <nl> / / 2019 / 06 / 29 7364 45685 46000 combine 2 levels of stat ref - counting into 1 <nl> + / / 2019 / 06 / 30 7428 42742 43000 remove stats multiple inheritance , inline HeapStatData <nl> <nl> / / Note : when adjusting this value : EXPECT_MEMORY_EQ is active only in CI <nl> / / ' release ' builds , where we control the platform and tool - chain . So you <nl> TEST_P ( ClusterMemoryTestRunner , MemoryLargeClusterSizeWithStats ) { <nl> / / On a local clang8 / libstdc + + / linux flow , the memory usage was observed in <nl> / / June 2019 to be 64 bytes higher than it is in CI / release . Your mileage may <nl> / / vary . <nl> - EXPECT_MEMORY_EQ ( m_per_cluster , 45685 ) ; <nl> - EXPECT_MEMORY_LE ( m_per_cluster , 46000 ) ; <nl> + EXPECT_MEMORY_EQ ( m_per_cluster , 42742 ) ; <nl> + EXPECT_MEMORY_LE ( m_per_cluster , 43000 ) ; <nl> } <nl> <nl> } / / namespace <nl> mmm a / test / mocks / stats / mocks . cc <nl> ppp b / test / mocks / stats / mocks . cc <nl> using testing : : ReturnRef ; <nl> namespace Envoy { <nl> namespace Stats { <nl> <nl> - MockMetric : : MockMetric ( ) : name_ ( * this ) , tag_pool_ ( * symbol_table_ ) { } <nl> - MockMetric : : ~ MockMetric ( ) = default ; <nl> - <nl> - MockMetric : : MetricName : : ~ MetricName ( ) { <nl> - if ( stat_name_storage_ ! = nullptr ) { <nl> - stat_name_storage_ - > free ( * mock_metric_ . symbol_table_ ) ; <nl> - } <nl> - } <nl> - <nl> - void MockMetric : : setTagExtractedName ( absl : : string_view name ) { <nl> - tag_extracted_name_ = std : : string ( name ) ; <nl> - tag_extracted_stat_name_ = <nl> - std : : make_unique < StatNameManagedStorage > ( tagExtractedName ( ) , * symbol_table_ ) ; <nl> - } <nl> - <nl> - void MockMetric : : setTags ( const std : : vector < Tag > & tags ) { <nl> - tag_pool_ . clear ( ) ; <nl> - tags_ = tags ; <nl> - for ( const Tag & tag : tags ) { <nl> - tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . name_ ) ) ; <nl> - tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . value_ ) ) ; <nl> - } <nl> - } <nl> - void MockMetric : : addTag ( const Tag & tag ) { <nl> - tags_ . emplace_back ( tag ) ; <nl> - tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . name_ ) ) ; <nl> - tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . value_ ) ) ; <nl> - } <nl> - <nl> - void MockMetric : : iterateTags ( const TagIterFn & fn ) const { <nl> - for ( const Tag & tag : tags_ ) { <nl> - if ( ! fn ( tag ) ) { <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - void MockMetric : : iterateTagStatNames ( const TagStatNameIterFn & fn ) const { <nl> - ASSERT ( ( tag_names_and_values_ . size ( ) % 2 ) = = 0 ) ; <nl> - for ( size_t i = 0 ; i < tag_names_and_values_ . size ( ) ; i + = 2 ) { <nl> - if ( ! fn ( tag_names_and_values_ [ i ] , tag_names_and_values_ [ i + 1 ] ) ) { <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - void MockMetric : : MetricName : : MetricName : : operator = ( absl : : string_view name ) { <nl> - name_ = std : : string ( name ) ; <nl> - stat_name_storage_ = std : : make_unique < StatNameStorage > ( name , mock_metric_ . symbolTable ( ) ) ; <nl> - } <nl> - <nl> MockCounter : : MockCounter ( ) { <nl> ON_CALL ( * this , used ( ) ) . WillByDefault ( ReturnPointee ( & used_ ) ) ; <nl> ON_CALL ( * this , value ( ) ) . WillByDefault ( ReturnPointee ( & value_ ) ) ; <nl> mmm a / test / mocks / stats / mocks . h <nl> ppp b / test / mocks / stats / mocks . h <nl> <nl> namespace Envoy { <nl> namespace Stats { <nl> <nl> - class MockMetric : public virtual Metric { <nl> + template < class BaseClass > class MockMetric : public BaseClass { <nl> public : <nl> - MockMetric ( ) ; <nl> - ~ MockMetric ( ) override ; <nl> + MockMetric ( ) : name_ ( * this ) , tag_pool_ ( * symbol_table_ ) { } <nl> + ~ MockMetric ( ) override = default ; <nl> <nl> / / This bit of C + + subterfuge allows us to support the wealth of tests that <nl> / / do metric - > name_ = " foo " even though names are more complex now . Note <nl> class MockMetric : public virtual Metric { <nl> class MetricName { <nl> public : <nl> explicit MetricName ( MockMetric & mock_metric ) : mock_metric_ ( mock_metric ) { } <nl> - ~ MetricName ( ) ; <nl> + ~ MetricName ( ) { <nl> + if ( stat_name_storage_ ! = nullptr ) { <nl> + stat_name_storage_ - > free ( * mock_metric_ . symbol_table_ ) ; <nl> + } <nl> + } <nl> <nl> - void operator = ( absl : : string_view str ) ; <nl> + void operator = ( absl : : string_view str ) { <nl> + name_ = std : : string ( str ) ; <nl> + stat_name_storage_ = std : : make_unique < StatNameStorage > ( str , mock_metric_ . symbolTable ( ) ) ; <nl> + } <nl> <nl> std : : string name ( ) const { return name_ ; } <nl> StatName statName ( ) const { return stat_name_storage_ - > statName ( ) ; } <nl> class MockMetric : public virtual Metric { <nl> std : : string name ( ) const override { return name_ . name ( ) ; } <nl> StatName statName ( ) const override { return name_ . statName ( ) ; } <nl> std : : vector < Tag > tags ( ) const override { return tags_ ; } <nl> - void setTagExtractedName ( absl : : string_view name ) ; <nl> + void setTagExtractedName ( absl : : string_view name ) { <nl> + tag_extracted_name_ = std : : string ( name ) ; <nl> + tag_extracted_stat_name_ = <nl> + std : : make_unique < StatNameManagedStorage > ( tagExtractedName ( ) , * symbol_table_ ) ; <nl> + } <nl> std : : string tagExtractedName ( ) const override { <nl> return tag_extracted_name_ . empty ( ) ? name ( ) : tag_extracted_name_ ; <nl> } <nl> StatName tagExtractedStatName ( ) const override { return tag_extracted_stat_name_ - > statName ( ) ; } <nl> - void iterateTagStatNames ( const TagStatNameIterFn & fn ) const override ; <nl> - void iterateTags ( const TagIterFn & fn ) const override ; <nl> + void iterateTagStatNames ( const Metric : : TagStatNameIterFn & fn ) const override { <nl> + ASSERT ( ( tag_names_and_values_ . size ( ) % 2 ) = = 0 ) ; <nl> + for ( size_t i = 0 ; i < tag_names_and_values_ . size ( ) ; i + = 2 ) { <nl> + if ( ! fn ( tag_names_and_values_ [ i ] , tag_names_and_values_ [ i + 1 ] ) ) { <nl> + return ; <nl> + } <nl> + } <nl> + } <nl> + void iterateTags ( const Metric : : TagIterFn & fn ) const override { <nl> + for ( const Tag & tag : tags_ ) { <nl> + if ( ! fn ( tag ) ) { <nl> + return ; <nl> + } <nl> + } <nl> + } <nl> <nl> Test : : Global < FakeSymbolTableImpl > symbol_table_ ; / / Must outlive name_ . <nl> MetricName name_ ; <nl> <nl> - void setTags ( const std : : vector < Tag > & tags ) ; <nl> - void addTag ( const Tag & tag ) ; <nl> + void setTags ( const std : : vector < Tag > & tags ) { <nl> + tag_pool_ . clear ( ) ; <nl> + tags_ = tags ; <nl> + for ( const Tag & tag : tags ) { <nl> + tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . name_ ) ) ; <nl> + tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . value_ ) ) ; <nl> + } <nl> + } <nl> + void addTag ( const Tag & tag ) { <nl> + tags_ . emplace_back ( tag ) ; <nl> + tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . name_ ) ) ; <nl> + tag_names_and_values_ . push_back ( tag_pool_ . add ( tag . value_ ) ) ; <nl> + } <nl> <nl> private : <nl> std : : vector < Tag > tags_ ; <nl> class MockMetric : public virtual Metric { <nl> std : : unique_ptr < StatNameManagedStorage > tag_extracted_stat_name_ ; <nl> } ; <nl> <nl> - class MockCounter : public Counter , public MockMetric { <nl> + template < class BaseClass > class MockStatWithRefcount : public MockMetric < BaseClass > { <nl> + public : <nl> + / / RefcountInterface <nl> + void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> + bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> + uint32_t use_count ( ) const override { return refcount_helper_ . use_count ( ) ; } <nl> + <nl> + RefcountHelper refcount_helper_ ; <nl> + } ; <nl> + <nl> + class MockCounter : public MockStatWithRefcount < Counter > { <nl> public : <nl> MockCounter ( ) ; <nl> ~ MockCounter ( ) override ; <nl> class MockCounter : public Counter , public MockMetric { <nl> RefcountHelper refcount_helper_ ; <nl> } ; <nl> <nl> - class MockGauge : public Gauge , public MockMetric , public RefcountHelper { <nl> + class MockGauge : public MockStatWithRefcount < Gauge > { <nl> public : <nl> MockGauge ( ) ; <nl> ~ MockGauge ( ) override ; <nl> class MockGauge : public Gauge , public MockMetric , public RefcountHelper { <nl> RefcountHelper refcount_helper_ ; <nl> } ; <nl> <nl> - class MockHistogram : public Histogram , public MockMetric { <nl> + class MockHistogram : public MockMetric < Histogram > { <nl> public : <nl> MockHistogram ( ) ; <nl> ~ MockHistogram ( ) override ; <nl> class MockHistogram : public Histogram , public MockMetric { <nl> MOCK_METHOD1 ( recordValue , void ( uint64_t value ) ) ; <nl> MOCK_CONST_METHOD0 ( used , bool ( ) ) ; <nl> <nl> + / / RefcountInterface <nl> + void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> + bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> + uint32_t use_count ( ) const override { return refcount_helper_ . use_count ( ) ; } <nl> + <nl> Store * store_ ; <nl> + <nl> + private : <nl> + RefcountHelper refcount_helper_ ; <nl> } ; <nl> <nl> - class MockParentHistogram : public ParentHistogram , public MockMetric { <nl> + class MockParentHistogram : public MockMetric < ParentHistogram > { <nl> public : <nl> MockParentHistogram ( ) ; <nl> ~ MockParentHistogram ( ) override ; <nl> class MockParentHistogram : public ParentHistogram , public MockMetric { <nl> MOCK_CONST_METHOD0 ( cumulativeStatistics , const HistogramStatistics & ( ) ) ; <nl> MOCK_CONST_METHOD0 ( intervalStatistics , const HistogramStatistics & ( ) ) ; <nl> <nl> + / / RefcountInterface <nl> + void incRefCount ( ) override { refcount_helper_ . incRefCount ( ) ; } <nl> + bool decRefCount ( ) override { return refcount_helper_ . decRefCount ( ) ; } <nl> + uint32_t use_count ( ) const override { return refcount_helper_ . use_count ( ) ; } <nl> + <nl> bool used_ ; <nl> Store * store_ ; <nl> std : : shared_ptr < HistogramStatistics > histogram_stats_ = <nl> std : : make_shared < HistogramStatisticsImpl > ( ) ; <nl> + <nl> + private : <nl> + RefcountHelper refcount_helper_ ; <nl> } ; <nl> <nl> class MockMetricSnapshot : public MetricSnapshot { <nl>
stats : remove virtual and multiple inheritance from stats , inline HeapStatData into counters and gauges ( )
envoyproxy/envoy
fa2b8194c47d492e720563c39ed80d4c85ce0230
2019-07-03T17:28:03Z
mmm a / android / sdk / src / main / java / com / taobao / weex / utils / BoxShadowUtil . java <nl> ppp b / android / sdk / src / main / java / com / taobao / weex / utils / BoxShadowUtil . java <nl> <nl> import android . graphics . Paint ; <nl> import android . graphics . Path ; <nl> import android . graphics . PixelFormat ; <nl> + import android . graphics . Point ; <nl> import android . graphics . PointF ; <nl> import android . graphics . Rect ; <nl> import android . graphics . RectF ; <nl> <nl> import android . graphics . Shader ; <nl> import android . graphics . drawable . BitmapDrawable ; <nl> import android . graphics . drawable . Drawable ; <nl> + import android . graphics . drawable . LayerDrawable ; <nl> import android . os . Build ; <nl> import android . support . annotation . IntRange ; <nl> import android . support . annotation . Nullable ; <nl> <nl> import java . util . ArrayList ; <nl> import java . util . Arrays ; <nl> import java . util . List ; <nl> + import java . util . regex . Matcher ; <nl> + import java . util . regex . Pattern ; <nl> <nl> / * * <nl> * Created by moxun on 2017 / 9 / 4 . <nl> <nl> private static final String TAG = " BoxShadowUtil " ; <nl> private static boolean sBoxShadowEnabled = true ; <nl> <nl> + private static Pattern sColorPattern ; <nl> + <nl> public static void setBoxShadowEnabled ( boolean enabled ) { <nl> sBoxShadowEnabled = enabled ; <nl> WXLogUtils . w ( TAG , " Switch box - shadow status : " + enabled ) ; <nl> public static boolean isBoxShadowEnabled ( ) { <nl> return sBoxShadowEnabled ; <nl> } <nl> <nl> - public static void setBoxShadow ( final View target , String style , float [ ] radii , int viewPort , final float quality ) { <nl> + public static void setBoxShadow ( final View target , String style , final float [ ] radii , int viewPort , final float quality ) { <nl> if ( ! sBoxShadowEnabled ) { <nl> WXLogUtils . w ( TAG , " box - shadow was disabled by config " ) ; <nl> return ; <nl> } <nl> <nl> - final BoxShadowOptions options = parseBoxShadow ( style , viewPort ) ; <nl> - if ( options = = null ) { <nl> - WXLogUtils . w ( TAG , " Failed to parse box - shadow : " + style ) ; <nl> - return ; <nl> - } <nl> - <nl> if ( target = = null ) { <nl> WXLogUtils . w ( TAG , " Target view is null ! " ) ; <nl> return ; <nl> } <nl> <nl> - if ( options . isClear & & Build . VERSION . SDK_INT > = Build . VERSION_CODES . JELLY_BEAN_MR2 ) { <nl> + if ( TextUtils . isEmpty ( style ) & & Build . VERSION . SDK_INT > = Build . VERSION_CODES . JELLY_BEAN_MR2 ) { <nl> target . getOverlay ( ) . clear ( ) ; <nl> - WXLogUtils . d ( TAG , " Remove box - shadow " ) ; <nl> + WXLogUtils . d ( TAG , " Remove all box - shadow " ) ; <nl> + return ; <nl> + } <nl> + <nl> + final BoxShadowOptions [ ] shadows = parseBoxShadows ( style , viewPort ) ; <nl> + if ( shadows = = null | | shadows . length = = 0 ) { <nl> + WXLogUtils . w ( TAG , " Failed to parse box - shadow : " + style ) ; <nl> return ; <nl> } <nl> <nl> + final List < BoxShadowOptions > normalShadows = new ArrayList < > ( ) , insetShadows = new ArrayList < > ( ) ; <nl> + for ( BoxShadowOptions shadow : shadows ) { <nl> + if ( shadow ! = null ) { <nl> + if ( shadow . isInset ) { <nl> + insetShadows . add ( 0 , shadow ) ; <nl> + } else { <nl> + normalShadows . add ( 0 , shadow ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> if ( radii ! = null ) { <nl> if ( radii . length ! = 8 ) { <nl> WXLogUtils . w ( TAG , " Length of radii must be 8 " ) ; <nl> public static void setBoxShadow ( final View target , String style , float [ ] radii , <nl> float realRadius = WXViewUtils . getRealSubPxByWidth ( radii [ i ] , viewPort ) ; <nl> radii [ i ] = realRadius ; <nl> } <nl> - options . radii = radii ; <nl> } <nl> } <nl> <nl> - WXLogUtils . d ( TAG , " Set box - shadow : " + options . toString ( ) ) ; <nl> - <nl> target . post ( new Runnable ( ) { <nl> @ Override <nl> public void run ( ) { <nl> - if ( options . isInset ) { <nl> - setInsetBoxShadow ( target , options , quality ) ; <nl> - } else { <nl> - setNormalBoxShadow ( target , options , quality ) ; <nl> + if ( Build . VERSION . SDK_INT > = Build . VERSION_CODES . JELLY_BEAN_MR2 ) { <nl> + target . getOverlay ( ) . clear ( ) ; <nl> + if ( normalShadows . size ( ) > 0 ) { <nl> + setNormalBoxShadow ( target , normalShadows , quality , radii ) ; <nl> + } <nl> + <nl> + if ( insetShadows . size ( ) > 0 ) { <nl> + setInsetBoxShadow ( target , insetShadows , quality , radii ) ; <nl> + } <nl> } <nl> } <nl> } ) ; <nl> } <nl> <nl> - private static Bitmap createShadowBitmap ( int viewWidth , int viewHeight , <nl> - float [ ] radii , float shadowRadius , <nl> - float shadowSpread , <nl> - float dx , float dy , int shadowColor ) { <nl> - int canvasWidth = viewWidth + 2 * ( int ) ( shadowRadius + shadowSpread + Math . abs ( dx ) ) ; <nl> - int canvasHeight = viewHeight + 2 * ( int ) ( shadowRadius + shadowSpread + Math . abs ( dy ) ) ; <nl> - <nl> - Bitmap output = Bitmap . createBitmap ( canvasWidth , canvasHeight , Bitmap . Config . ARGB_4444 ) ; <nl> - if ( Build . VERSION . SDK_INT > = Build . VERSION_CODES . KITKAT ) { <nl> - WXLogUtils . d ( TAG , " Allocation memory for box - shadow : " + ( output . getAllocationByteCount ( ) / 1024 ) + " KB " ) ; <nl> - } <nl> - Canvas canvas = new Canvas ( output ) ; <nl> - <nl> - if ( false & & WXEnvironment . isApkDebugable ( ) ) { <nl> - / / Using for debug <nl> - Paint strokePaint = new Paint ( ) ; <nl> - strokePaint . setColor ( Color . BLACK ) ; <nl> - strokePaint . setStrokeWidth ( 2 ) ; <nl> - strokePaint . setStyle ( Paint . Style . STROKE ) ; <nl> - canvas . drawRect ( canvas . getClipBounds ( ) , strokePaint ) ; <nl> - } <nl> - <nl> + private static void drawShadow ( Canvas canvas , BoxShadowOptions options ) { <nl> RectF shadowRect = new RectF ( <nl> 0f , 0f , <nl> - viewWidth + 2f * shadowSpread , viewHeight + 2f * shadowSpread <nl> + options . viewWidth + 2f * options . spread , options . viewHeight + 2f * options . spread <nl> ) ; <nl> <nl> - float shadowDx = shadowRadius ; <nl> - float shadowDy = shadowRadius ; <nl> - if ( dx > 0 ) { <nl> - shadowDx = shadowDx + 2f * dx ; <nl> + if ( options . topLeft ! = null ) { <nl> + shadowRect . offset ( options . topLeft . x , options . topLeft . y ) ; <nl> + } <nl> + <nl> + float shadowDx = options . blur ; <nl> + float shadowDy = options . blur ; <nl> + if ( options . hShadow > 0 ) { <nl> + shadowDx = shadowDx + 2f * options . hShadow ; <nl> } <nl> - if ( dy > 0 ) { <nl> - shadowDy = shadowDy + 2f * dy ; <nl> + if ( options . vShadow > 0 ) { <nl> + shadowDy = shadowDy + 2f * options . vShadow ; <nl> } <nl> shadowRect . offset ( shadowDx , shadowDy ) ; <nl> <nl> Paint shadowPaint = new Paint ( ) ; <nl> shadowPaint . setAntiAlias ( true ) ; <nl> - shadowPaint . setColor ( shadowColor ) ; <nl> + shadowPaint . setColor ( options . color ) ; <nl> shadowPaint . setStyle ( Paint . Style . FILL ) ; <nl> <nl> - if ( shadowRadius > 0 ) { <nl> - shadowPaint . setMaskFilter ( new BlurMaskFilter ( shadowRadius , BlurMaskFilter . Blur . NORMAL ) ) ; <nl> + if ( options . blur > 0 ) { <nl> + shadowPaint . setMaskFilter ( new BlurMaskFilter ( options . blur , BlurMaskFilter . Blur . NORMAL ) ) ; <nl> } <nl> <nl> Path shadowPath = new Path ( ) ; <nl> float [ ] shadowRadii = new float [ 8 ] ; <nl> - for ( int i = 0 ; i < radii . length ; i + + ) { <nl> - float contentRadius = radii [ i ] ; <nl> + for ( int i = 0 ; i < options . radii . length ; i + + ) { <nl> + float contentRadius = options . radii [ i ] ; <nl> if ( contentRadius = = 0f ) { <nl> shadowRadii [ i ] = 0f ; <nl> } else { <nl> - shadowRadii [ i ] = radii [ i ] + shadowSpread ; <nl> + shadowRadii [ i ] = options . radii [ i ] + options . spread ; <nl> } <nl> } <nl> shadowPath . addRoundRect ( shadowRect , shadowRadii , Path . Direction . CCW ) ; <nl> canvas . drawPath ( shadowPath , shadowPaint ) ; <nl> - return output ; <nl> + <nl> + if ( false & & WXEnvironment . isApkDebugable ( ) ) { <nl> + Paint paint = new Paint ( ) ; <nl> + paint . setAntiAlias ( true ) ; <nl> + paint . setColor ( Color . BLACK ) ; <nl> + paint . setStyle ( Paint . Style . STROKE ) ; <nl> + canvas . drawRect ( shadowRect , paint ) ; <nl> + } <nl> } <nl> <nl> - private static void setNormalBoxShadow ( View target , BoxShadowOptions options , float quality ) { <nl> + private static void setNormalBoxShadow ( View target , List < BoxShadowOptions > options , float quality , float [ ] radii ) { <nl> int h = target . getHeight ( ) ; <nl> int w = target . getWidth ( ) ; <nl> <nl> private static void setNormalBoxShadow ( View target , BoxShadowOptions options , fl <nl> } <nl> <nl> if ( Build . VERSION . SDK_INT > = Build . VERSION_CODES . JELLY_BEAN_MR2 ) { <nl> - options . viewWidth = w ; <nl> - options . viewHeight = h ; <nl> + int maxWidth = 0 , maxHeight = 0 ; <nl> + for ( BoxShadowOptions option : options ) { <nl> + option . viewWidth = w ; <nl> + option . viewHeight = h ; <nl> + option . radii = radii ; <nl> + <nl> + Rect rect = option . getTargetCanvasRect ( ) ; <nl> + if ( maxWidth < rect . width ( ) ) { <nl> + maxWidth = rect . width ( ) ; <nl> + } <nl> + <nl> + if ( maxHeight < rect . height ( ) ) { <nl> + maxHeight = rect . height ( ) ; <nl> + } <nl> + } <nl> + <nl> + int canvasWidth = ( int ) ( maxWidth * quality ) ; <nl> + int canvasHeight = ( int ) ( maxHeight * quality ) ; <nl> + Bitmap output = Bitmap . createBitmap ( canvasWidth , canvasHeight , Bitmap . Config . ARGB_4444 ) ; <nl> + if ( Build . VERSION . SDK_INT > = Build . VERSION_CODES . KITKAT ) { <nl> + WXLogUtils . d ( TAG , " Allocation memory for box - shadow : " + ( output . getAllocationByteCount ( ) / 1024 ) + " KB " ) ; <nl> + } <nl> + Canvas canvas = new Canvas ( output ) ; <nl> + <nl> + if ( false & & WXEnvironment . isApkDebugable ( ) ) { <nl> + / / Using for debug <nl> + Paint strokePaint = new Paint ( ) ; <nl> + strokePaint . setColor ( Color . BLACK ) ; <nl> + strokePaint . setStrokeWidth ( 2 ) ; <nl> + strokePaint . setStyle ( Paint . Style . STROKE ) ; <nl> + canvas . drawRect ( canvas . getClipBounds ( ) , strokePaint ) ; <nl> + } <nl> + <nl> + for ( BoxShadowOptions option : options ) { <nl> + Rect rect = option . getTargetCanvasRect ( ) ; <nl> + float left = ( maxWidth - rect . width ( ) ) / 2f ; <nl> + float top = ( maxHeight - rect . height ( ) ) / 2f ; <nl> + option . topLeft = new PointF ( left , top ) ; <nl> <nl> - BoxShadowOptions scaleOptions = options . scale ( quality ) ; <nl> - Bitmap shadowBitmap = createShadowBitmap ( scaleOptions . viewWidth , scaleOptions . viewHeight , scaleOptions . radii , scaleOptions . blur , scaleOptions . spread , scaleOptions . hShadow , scaleOptions . vShadow , scaleOptions . color ) ; <nl> + BoxShadowOptions scaledOption = option . scale ( quality ) ; <nl> + drawShadow ( canvas , scaledOption ) ; <nl> + } <nl> <nl> / / Drawable ' s bounds must match the bitmap size , otherwise the shadows will be scaled <nl> - OverflowBitmapDrawable shadowDrawable = new OverflowBitmapDrawable ( target . getResources ( ) , shadowBitmap , options ) ; <nl> + int paddingX = ( maxWidth - w ) / 2 ; <nl> + int paddingY = ( maxHeight - h ) / 2 ; <nl> + OverflowBitmapDrawable shadowDrawable = new OverflowBitmapDrawable ( target . getResources ( ) , <nl> + output , new Point ( paddingX , paddingY ) , new Rect ( 0 , 0 , w , h ) , radii ) ; <nl> <nl> - target . getOverlay ( ) . clear ( ) ; <nl> target . getOverlay ( ) . add ( shadowDrawable ) ; <nl> / / Relayout to ensure the shadows are fully drawn <nl> ViewParent parent = target . getParent ( ) ; <nl> private static void setNormalBoxShadow ( View target , BoxShadowOptions options , fl <nl> } <nl> } <nl> <nl> - private static void setInsetBoxShadow ( View target , BoxShadowOptions options , float quality ) { <nl> + private static void setInsetBoxShadow ( View target , List < BoxShadowOptions > options , float quality , float [ ] radii ) { <nl> if ( target = = null | | options = = null ) { <nl> WXLogUtils . w ( TAG , " Illegal arguments " ) ; <nl> return ; <nl> private static void setInsetBoxShadow ( View target , BoxShadowOptions options , flo <nl> } <nl> <nl> if ( Build . VERSION . SDK_INT > = Build . VERSION_CODES . JELLY_BEAN_MR2 ) { <nl> - Drawable shadow = new InsetShadowDrawable ( target . getWidth ( ) , target . getHeight ( ) , <nl> - options . hShadow , options . vShadow , <nl> - options . blur , options . spread , <nl> - options . color , options . radii ) ; <nl> - target . getOverlay ( ) . clear ( ) ; <nl> - target . getOverlay ( ) . add ( shadow ) ; <nl> + Drawable [ ] drawables = new Drawable [ options . size ( ) ] ; <nl> + for ( int i = 0 ; i < options . size ( ) ; i + + ) { <nl> + BoxShadowOptions option = options . get ( i ) ; <nl> + Drawable shadow = new InsetShadowDrawable ( target . getWidth ( ) , target . getHeight ( ) , <nl> + option . hShadow , option . vShadow , <nl> + option . blur , option . spread , <nl> + option . color , radii ) ; <nl> + drawables [ i ] = shadow ; <nl> + } <nl> + <nl> + LayerDrawable layerDrawable = new LayerDrawable ( drawables ) ; <nl> + target . getOverlay ( ) . add ( layerDrawable ) ; <nl> target . invalidate ( ) ; <nl> } else { <nl> Log . w ( TAG , " Call setInsetBoxShadow ( ) requires API level 18 or higher . " ) ; <nl> } <nl> } <nl> <nl> - public static BoxShadowOptions parseBoxShadow ( String boxShadow , int viewport ) { <nl> + public static BoxShadowOptions [ ] parseBoxShadows ( String boxShadowStyle , int viewport ) { <nl> + / / normalization color expression to # AARRGGBB <nl> + if ( sColorPattern = = null ) { <nl> + sColorPattern = Pattern . compile ( " ( [ rR ] [ gG ] [ bB ] [ aA ] ? ) \ \ ( ( \ \ d + \ \ s * ) , \ \ s * ( \ \ d + \ \ s * ) , \ \ s * ( \ \ d + \ \ s * ) ( ? : , \ \ s * ( \ \ d + ( ? : \ \ . \ \ d + ) ? ) ) ? \ \ ) " ) ; <nl> + } <nl> + <nl> + Matcher matcher = sColorPattern . matcher ( boxShadowStyle ) ; <nl> + <nl> + String processedStyle = boxShadowStyle ; <nl> + while ( matcher . find ( ) ) { <nl> + String color = matcher . group ( ) ; <nl> + processedStyle = processedStyle . replace ( color , " # " + Integer . toHexString ( WXResourceUtils . getColor ( color , Color . BLACK ) ) ) ; <nl> + } <nl> + <nl> + String [ ] styles = processedStyle . split ( " , " ) ; <nl> + if ( styles ! = null & & styles . length > 0 ) { <nl> + BoxShadowOptions [ ] result = new BoxShadowOptions [ styles . length ] ; <nl> + for ( int i = 0 ; i < styles . length ; i + + ) { <nl> + result [ i ] = parseBoxShadow ( styles [ i ] , viewport ) ; <nl> + } <nl> + return result ; <nl> + } <nl> + return null ; <nl> + } <nl> + <nl> + private static BoxShadowOptions parseBoxShadow ( String boxShadow , int viewport ) { <nl> BoxShadowOptions result = new BoxShadowOptions ( viewport ) ; <nl> if ( TextUtils . isEmpty ( boxShadow ) ) { <nl> - result . isClear = true ; <nl> - return result ; <nl> + return null ; <nl> } <nl> <nl> String boxShadowCopy = boxShadow ; <nl> public static BoxShadowOptions parseBoxShadow ( String boxShadow , int viewport ) { <nl> / / match inset first <nl> if ( boxShadowCopy . contains ( " inset " ) ) { <nl> result . isInset = true ; <nl> - boxShadowCopy = boxShadowCopy . replace ( " inset " , " " ) . trim ( ) ; <nl> + boxShadowCopy = boxShadowCopy . replace ( " inset " , " " ) ; <nl> } <nl> <nl> + boxShadowCopy = boxShadowCopy . trim ( ) ; <nl> List < String > params = new ArrayList < > ( Arrays . asList ( boxShadowCopy . split ( " \ \ s + " ) ) ) ; <nl> <nl> / / match color <nl> public static BoxShadowOptions parseBoxShadow ( String boxShadow , int viewport ) { <nl> private static class OverflowBitmapDrawable extends BitmapDrawable { <nl> private int paddingX ; <nl> private int paddingY ; <nl> - private BoxShadowOptions options ; <nl> + private Rect viewRect ; <nl> + private float [ ] radii ; <nl> <nl> - private OverflowBitmapDrawable ( Resources resources , Bitmap bitmap , BoxShadowOptions options ) { <nl> + private OverflowBitmapDrawable ( Resources resources , Bitmap bitmap , Point topLeft , Rect viewRect , float [ ] radii ) { <nl> super ( resources , bitmap ) ; <nl> - this . paddingX = ( int ) ( options . blur + Math . abs ( options . hShadow ) + options . spread ) ; <nl> - this . paddingY = ( int ) ( options . blur + Math . abs ( options . vShadow ) + options . spread ) ; <nl> - this . options = options ; <nl> + this . paddingX = topLeft . x ; <nl> + this . paddingY = topLeft . y ; <nl> + this . viewRect = viewRect ; <nl> + this . radii = radii ; <nl> <nl> - setBounds ( - paddingX , - paddingY , options . viewWidth + paddingX , options . viewHeight + paddingY ) ; <nl> + setBounds ( - paddingX , - paddingY , viewRect . width ( ) + paddingX , viewRect . height ( ) + paddingY ) ; <nl> } <nl> <nl> @ Override <nl> public void draw ( Canvas canvas ) { <nl> canvas . clipRect ( newRect , Region . Op . REPLACE ) ; <nl> <nl> Path contentPath = new Path ( ) ; <nl> - RectF rectF = new RectF ( 0f , 0f , options . viewWidth , options . viewHeight ) ; <nl> - contentPath . addRoundRect ( rectF , options . radii , Path . Direction . CCW ) ; <nl> + RectF rectF = new RectF ( 0f , 0f , viewRect . width ( ) , viewRect . height ( ) ) ; <nl> + contentPath . addRoundRect ( rectF , radii , Path . Direction . CCW ) ; <nl> / / can not antialias <nl> canvas . clipPath ( contentPath , Region . Op . DIFFERENCE ) ; <nl> <nl> public int getOpacity ( ) { <nl> public int color = Color . BLACK ; <nl> public boolean isInset = false ; <nl> <nl> - public boolean isClear = false ; <nl> public int viewWidth = 0 ; <nl> public int viewHeight = 0 ; <nl> + public PointF topLeft = null ; <nl> <nl> private BoxShadowOptions ( int vp ) { <nl> if ( viewport ! = 0 ) { <nl> public BoxShadowOptions scale ( float scale ) { <nl> scaledOptions . viewHeight = ( int ) ( viewHeight * scale ) ; <nl> scaledOptions . viewWidth = ( int ) ( viewWidth * scale ) ; <nl> <nl> + if ( topLeft ! = null ) { <nl> + scaledOptions . topLeft = new PointF ( ) ; <nl> + scaledOptions . topLeft . x = topLeft . x * scale ; <nl> + scaledOptions . topLeft . y = topLeft . y * scale ; <nl> + } <nl> + <nl> scaledOptions . color = color ; <nl> scaledOptions . isInset = isInset ; <nl> - scaledOptions . isClear = isClear ; <nl> WXLogUtils . d ( TAG , " Scaled BoxShadowOptions : [ " + scale + " ] " + scaledOptions ) ; <nl> return scaledOptions ; <nl> } <nl> return null ; <nl> } <nl> <nl> + public Rect getTargetCanvasRect ( ) { <nl> + int canvasWidth = viewWidth + 2 * ( int ) ( blur + spread + Math . abs ( hShadow ) ) ; <nl> + int canvasHeight = viewHeight + 2 * ( int ) ( blur + spread + Math . abs ( vShadow ) ) ; <nl> + return new Rect ( 0 , 0 , canvasWidth , canvasHeight ) ; <nl> + } <nl> + <nl> @ Override <nl> public String toString ( ) { <nl> <nl> Binary files a / test / screenshot / border - android . png and b / test / screenshot / border - android . png differ <nl>
* [ android ] support multi box - shadow
apache/incubator-weex
7f79916c8d7541a5df2c509acf494027f14f7f66
2017-11-28T03:52:44Z
mmm a / include / swift / ClangImporter / ClangModule . h <nl> ppp b / include / swift / ClangImporter / ClangModule . h <nl> class ClangModuleUnit final : public LoadedFile { <nl> DeclName name , NLKind lookupKind , <nl> SmallVectorImpl < ValueDecl * > & results ) const override ; <nl> <nl> + virtual TypeDecl * <nl> + lookupNestedType ( Identifier name , <nl> + const NominalTypeDecl * baseType ) const override ; <nl> + <nl> virtual void lookupVisibleDecls ( ModuleDecl : : AccessPathTy accessPath , <nl> VisibleDeclConsumer & consumer , <nl> NLKind lookupKind ) const override ; <nl> mmm a / lib / ClangImporter / ClangImporter . cpp <nl> ppp b / lib / ClangImporter / ClangImporter . cpp <nl> static bool isVisibleClangEntry ( clang : : ASTContext & ctx , <nl> return true ; <nl> } <nl> <nl> + TypeDecl * <nl> + ClangModuleUnit : : lookupNestedType ( Identifier name , <nl> + const NominalTypeDecl * baseType ) const { <nl> + auto lookupTable = owner . findLookupTable ( clangModule ) ; <nl> + if ( ! lookupTable ) <nl> + return nullptr ; <nl> + <nl> + auto baseTypeContext = owner . getEffectiveClangContext ( baseType ) ; <nl> + if ( ! baseTypeContext ) <nl> + return nullptr ; <nl> + <nl> + auto & clangCtx = owner . getClangASTContext ( ) ; <nl> + <nl> + / / FIXME : This is very similar to what ' s in Implementation : : lookupValue and <nl> + / / Implementation : : loadAllMembers . <nl> + SmallVector < TypeDecl * , 2 > results ; <nl> + for ( auto entry : lookupTable - > lookup ( SerializedSwiftName ( name . str ( ) ) , <nl> + baseTypeContext ) ) { <nl> + / / If the entry is not visible , skip it . <nl> + if ( ! isVisibleClangEntry ( clangCtx , entry ) ) continue ; <nl> + <nl> + auto clangDecl = entry . dyn_cast < clang : : NamedDecl * > ( ) ; <nl> + auto clangTypeDecl = dyn_cast_or_null < clang : : TypeDecl > ( clangDecl ) ; <nl> + if ( ! clangTypeDecl ) <nl> + continue ; <nl> + <nl> + clangTypeDecl = cast < clang : : TypeDecl > ( clangTypeDecl - > getMostRecentDecl ( ) ) ; <nl> + <nl> + bool anyMatching = false ; <nl> + TypeDecl * originalDecl = nullptr ; <nl> + owner . forEachDistinctName ( clangTypeDecl , [ & ] ( ImportedName newName , <nl> + ImportNameVersion nameVersion ) { <nl> + if ( anyMatching ) <nl> + return ; <nl> + if ( ! newName . getDeclName ( ) . isSimpleName ( name ) ) <nl> + return ; <nl> + <nl> + auto decl = dyn_cast_or_null < TypeDecl > ( <nl> + owner . importDeclReal ( clangTypeDecl , nameVersion ) ) ; <nl> + if ( ! decl ) <nl> + return ; <nl> + <nl> + if ( ! originalDecl ) <nl> + originalDecl = decl ; <nl> + else if ( originalDecl = = decl ) <nl> + return ; <nl> + <nl> + auto * importedContext = decl - > getDeclContext ( ) - > <nl> + getAsNominalTypeOrNominalTypeExtensionContext ( ) ; <nl> + if ( importedContext ! = baseType ) <nl> + return ; <nl> + <nl> + assert ( decl - > getFullName ( ) . matchesRef ( name ) & & <nl> + " importFullName behaved differently from importDecl " ) ; <nl> + results . push_back ( decl ) ; <nl> + anyMatching = true ; <nl> + } ) ; <nl> + } <nl> + <nl> + if ( results . size ( ) = = 1 ) <nl> + return results . front ( ) ; <nl> + return nullptr ; <nl> + } <nl> + <nl> void ClangImporter : : loadExtensions ( NominalTypeDecl * nominal , <nl> unsigned previousGeneration ) { <nl> / / Determine the effective Clang context for this Swift nominal type . <nl> void ClangImporter : : Implementation : : lookupAllObjCMembers ( <nl> } <nl> <nl> EffectiveClangContext ClangImporter : : Implementation : : getEffectiveClangContext ( <nl> - NominalTypeDecl * nominal ) { <nl> + const NominalTypeDecl * nominal ) { <nl> / / If we have a Clang declaration , look at it to determine the <nl> / / effective Clang context . <nl> if ( auto constClangDecl = nominal - > getClangDecl ( ) ) { <nl> EffectiveClangContext ClangImporter : : Implementation : : getEffectiveClangContext ( <nl> <nl> / / Resolve the type . <nl> if ( auto typeResolver = getTypeResolver ( ) ) <nl> - typeResolver - > resolveDeclSignature ( nominal ) ; <nl> + typeResolver - > resolveDeclSignature ( const_cast < NominalTypeDecl * > ( nominal ) ) ; <nl> <nl> / / If it ' s an @ objc entity , go look for it . <nl> if ( nominal - > isObjC ( ) ) { <nl> mmm a / lib / ClangImporter / ImporterImpl . h <nl> ppp b / lib / ClangImporter / ImporterImpl . h <nl> class LLVM_LIBRARY_VISIBILITY ClangImporter : : Implementation <nl> VisibleDeclConsumer & consumer ) ; <nl> <nl> / / / Determine the effective Clang context for the given Swift nominal type . <nl> - EffectiveClangContext getEffectiveClangContext ( NominalTypeDecl * nominal ) ; <nl> + EffectiveClangContext <nl> + getEffectiveClangContext ( const NominalTypeDecl * nominal ) ; <nl> <nl> / / / Attempts to import the name of \ p decl with each possible <nl> / / / ImportNameVersion . \ p action will be called with each unique name . <nl> new file mode 100644 <nl> index 000000000000 . . 96d0ce40c1aa <nl> mmm / dev / null <nl> ppp b / test / Serialization / Inputs / xref - nested - clang - type / NestedClangTypes . h <nl> <nl> + struct Outer { <nl> + int value ; <nl> + } ; <nl> + <nl> + struct __attribute__ ( ( swift_name ( " Outer . InterestingValue " ) ) ) Inner { <nl> + int value ; <nl> + } ; <nl> new file mode 100644 <nl> index 000000000000 . . 4c0603a0f617 <nl> mmm / dev / null <nl> ppp b / test / Serialization / Inputs / xref - nested - clang - type / module . modulemap <nl> <nl> + module NestedClangTypes { <nl> + header " NestedClangTypes . h " <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 7816d4348f18 <nl> mmm / dev / null <nl> ppp b / test / Serialization / xref - nested - clang - type . swift <nl> <nl> + / / RUN : % empty - directory ( % t ) <nl> + <nl> + / / RUN : % target - swift - frontend - emit - module - o % t - I % S / Inputs / xref - nested - clang - type / % s - module - name Lib <nl> + <nl> + / / RUN : % target - swift - frontend - typecheck - I % t - I % S / Inputs / xref - nested - clang - type / % s - DCLIENT - verify <nl> + <nl> + # if CLIENT <nl> + <nl> + import Lib <nl> + <nl> + func test ( x : MyInner ) { } <nl> + <nl> + # else <nl> + <nl> + import NestedClangTypes <nl> + <nl> + public typealias MyOuter = Outer <nl> + public typealias MyInner = Outer . InterestingValue <nl> + <nl> + extension MyOuter { <nl> + public func use ( inner : MyInner ) { } <nl> + } <nl> + <nl> + # endif <nl> \ No newline at end of file <nl>
[ ClangImporter ] Add direct access for import - as - member types .
apple/swift
925f2913f83b47fa108432e2a15cd2daac576744
2017-07-14T00:56:40Z
mmm a / BUILD . gn <nl> ppp b / BUILD . gn <nl> declare_args ( ) { <nl> # Enable code - generation - time checking of types in the CodeStubAssembler . <nl> v8_enable_verify_csa = false <nl> <nl> + # Enable pointer compression ( sets - dV8_COMPRESS_POINTERS ) . <nl> + v8_enable_pointer_compression = false <nl> + <nl> # Interpreted regexp engine exists as platform - independent alternative <nl> # based where the regular expression is compiled to a bytecode . <nl> v8_interpreted_regexp = false <nl> config ( " features " ) { <nl> if ( v8_enable_minor_mc ) { <nl> defines + = [ " ENABLE_MINOR_MC " ] <nl> } <nl> + if ( v8_enable_pointer_compression ) { <nl> + defines + = [ " V8_COMPRESS_POINTERS " ] <nl> + } <nl> if ( v8_enable_object_print ) { <nl> defines + = [ " OBJECT_PRINT " ] <nl> } <nl> mmm a / include / v8 . h <nl> ppp b / include / v8 . h <nl> const int kSmiTag = 0 ; <nl> const int kSmiTagSize = 1 ; <nl> const intptr_t kSmiTagMask = ( 1 < < kSmiTagSize ) - 1 ; <nl> <nl> - template < size_t ptr_size > <nl> + template < size_t tagged_ptr_size > <nl> struct SmiTagging ; <nl> <nl> template < int kSmiShiftSize > <nl> V8_INLINE internal : : Object * IntToSmi ( int value ) { <nl> int smi_shift_bits = kSmiTagSize + kSmiShiftSize ; <nl> - uintptr_t tagged_value = <nl> - ( static_cast < uintptr_t > ( value ) < < smi_shift_bits ) | kSmiTag ; <nl> + intptr_t tagged_value = <nl> + ( static_cast < intptr_t > ( value ) < < smi_shift_bits ) | kSmiTag ; <nl> return reinterpret_cast < internal : : Object * > ( tagged_value ) ; <nl> } <nl> <nl> - / / Smi constants for 32 - bit systems . <nl> + / / Smi constants for systems where tagged pointer is a 32 - bit value . <nl> template < > <nl> struct SmiTagging < 4 > { <nl> enum { kSmiShiftSize = 0 , kSmiValueSize = 31 } ; <nl> struct SmiTagging < 4 > { <nl> } <nl> } ; <nl> <nl> - / / Smi constants for 64 - bit systems . <nl> + / / Smi constants for systems where tagged pointer is a 64 - bit value . <nl> template < > <nl> struct SmiTagging < 8 > { <nl> enum { kSmiShiftSize = 31 , kSmiValueSize = 32 } ; <nl> struct SmiTagging < 8 > { <nl> } <nl> } ; <nl> <nl> + # if V8_COMPRESS_POINTERS <nl> + static_assert ( <nl> + kApiPointerSize = = kApiInt64Size , <nl> + " Pointer compression can be enabled only for 64 - bit architectures " ) ; <nl> + typedef SmiTagging < 4 > PlatformSmiTagging ; <nl> + # else <nl> typedef SmiTagging < kApiPointerSize > PlatformSmiTagging ; <nl> + # endif <nl> + <nl> const int kSmiShiftSize = PlatformSmiTagging : : kSmiShiftSize ; <nl> const int kSmiValueSize = PlatformSmiTagging : : kSmiValueSize ; <nl> const int kSmiMinValue = ( static_cast < unsigned int > ( - 1 ) ) < < ( kSmiValueSize - 1 ) ; <nl> mmm a / src / arm64 / assembler - arm64 - inl . h <nl> ppp b / src / arm64 / assembler - arm64 - inl . h <nl> unsigned Operand : : shift_amount ( ) const { <nl> <nl> <nl> Operand Operand : : UntagSmi ( Register smi ) { <nl> - STATIC_ASSERT ( kXRegSizeInBits = = static_cast < unsigned > ( kSmiShift + <nl> - kSmiValueSize ) ) ; <nl> DCHECK ( smi . Is64Bits ( ) ) ; <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> return Operand ( smi , ASR , kSmiShift ) ; <nl> } <nl> <nl> <nl> Operand Operand : : UntagSmiAndScale ( Register smi , int scale ) { <nl> - STATIC_ASSERT ( kXRegSizeInBits = = static_cast < unsigned > ( kSmiShift + <nl> - kSmiValueSize ) ) ; <nl> DCHECK ( smi . Is64Bits ( ) ) ; <nl> DCHECK ( ( scale > = 0 ) & & ( scale < = ( 64 - kSmiValueSize ) ) ) ; <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> if ( scale > kSmiShift ) { <nl> return Operand ( smi , LSL , scale - kSmiShift ) ; <nl> } else if ( scale < kSmiShift ) { <nl> mmm a / src / arm64 / macro - assembler - arm64 - inl . h <nl> ppp b / src / arm64 / macro - assembler - arm64 - inl . h <nl> void TurboAssembler : : InitializeRootRegister ( ) { <nl> <nl> <nl> void MacroAssembler : : SmiTag ( Register dst , Register src ) { <nl> - STATIC_ASSERT ( kXRegSizeInBits = = <nl> - static_cast < unsigned > ( kSmiShift + kSmiValueSize ) ) ; <nl> DCHECK ( dst . Is64Bits ( ) & & src . Is64Bits ( ) ) ; <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> Lsl ( dst , src , kSmiShift ) ; <nl> } <nl> <nl> - <nl> void MacroAssembler : : SmiTag ( Register smi ) { SmiTag ( smi , smi ) ; } <nl> <nl> void TurboAssembler : : SmiUntag ( Register dst , Register src ) { <nl> - STATIC_ASSERT ( kXRegSizeInBits = = <nl> - static_cast < unsigned > ( kSmiShift + kSmiValueSize ) ) ; <nl> DCHECK ( dst . Is64Bits ( ) & & src . Is64Bits ( ) ) ; <nl> if ( FLAG_enable_slow_asserts ) { <nl> AssertSmi ( src ) ; <nl> } <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> Asr ( dst , src , kSmiShift ) ; <nl> } <nl> <nl> void TurboAssembler : : SmiUntag ( Register dst , const MemOperand & src ) { <nl> - STATIC_ASSERT ( kXRegSizeInBits = = <nl> - static_cast < unsigned > ( kSmiShift + kSmiValueSize ) ) ; <nl> DCHECK ( dst . Is64Bits ( ) ) ; <nl> - if ( src . IsImmediateOffset ( ) & & src . shift_amount ( ) = = 0 ) { <nl> - if ( FLAG_enable_slow_asserts ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> + if ( src . IsImmediateOffset ( ) & & src . shift_amount ( ) = = 0 ) { <nl> + if ( FLAG_enable_slow_asserts ) { <nl> + Ldr ( dst , src ) ; <nl> + AssertSmi ( dst ) ; <nl> + } <nl> + / / Load value directly from the upper half - word . <nl> + / / Assumes that Smis are shifted by 32 bits and little endianness . <nl> + DCHECK_EQ ( kSmiShift , 32 ) ; <nl> + Ldrsw ( dst , <nl> + MemOperand ( src . base ( ) , src . offset ( ) + ( kSmiShift / kBitsPerByte ) , <nl> + src . addrmode ( ) ) ) ; <nl> + <nl> + } else { <nl> Ldr ( dst , src ) ; <nl> - AssertSmi ( dst ) ; <nl> + SmiUntag ( dst ) ; <nl> } <nl> - / / Load value directly from the upper half - word . <nl> - / / Assumes that Smis are shifted by 32 bits and little endianness . <nl> - DCHECK_EQ ( kSmiShift , 32 ) ; <nl> - Ldrsw ( dst , MemOperand ( src . base ( ) , src . offset ( ) + ( kSmiShift / kBitsPerByte ) , <nl> - src . addrmode ( ) ) ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> Ldr ( dst , src ) ; <nl> SmiUntag ( dst ) ; <nl> } <nl> mmm a / src / arm64 / simulator - arm64 . cc <nl> ppp b / src / arm64 / simulator - arm64 . cc <nl> void Simulator : : Debug ( ) { <nl> current_heap - > ContainsSlow ( obj - > address ( ) ) ) { <nl> PrintF ( " ( " ) ; <nl> if ( ( value & kSmiTagMask ) = = 0 ) { <nl> - STATIC_ASSERT ( kSmiValueSize = = 32 ) ; <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> int32_t untagged = ( value > > kSmiShift ) & 0xFFFFFFFF ; <nl> PrintF ( " smi % " PRId32 , untagged ) ; <nl> } else { <nl> mmm a / src / code - stub - assembler . cc <nl> ppp b / src / code - stub - assembler . cc <nl> TNode < Float64T > CodeStubAssembler : : Float64Trunc ( SloppyTNode < Float64T > x ) { <nl> return TNode < Float64T > : : UncheckedCast ( var_x . value ( ) ) ; <nl> } <nl> <nl> + TNode < BoolT > CodeStubAssembler : : IsValidSmi ( TNode < Smi > smi ) { <nl> + if ( SmiValuesAre31Bits ( ) & & kPointerSize = = kInt64Size ) { <nl> + / / Check that the Smi value is properly sign - extended . <nl> + TNode < IntPtrT > value = Signed ( BitcastTaggedToWord ( smi ) ) ; <nl> + return WordEqual ( value , ChangeInt32ToIntPtr ( TruncateIntPtrToInt32 ( value ) ) ) ; <nl> + } <nl> + return Int32TrueConstant ( ) ; <nl> + } <nl> + <nl> Node * CodeStubAssembler : : SmiShiftBitsConstant ( ) { <nl> return IntPtrConstant ( kSmiShiftSize + kSmiTagSize ) ; <nl> } <nl> <nl> TNode < Smi > CodeStubAssembler : : SmiFromInt32 ( SloppyTNode < Int32T > value ) { <nl> TNode < IntPtrT > value_intptr = ChangeInt32ToIntPtr ( value ) ; <nl> - return BitcastWordToTaggedSigned ( <nl> - WordShl ( value_intptr , SmiShiftBitsConstant ( ) ) ) ; <nl> + TNode < Smi > smi = <nl> + BitcastWordToTaggedSigned ( WordShl ( value_intptr , SmiShiftBitsConstant ( ) ) ) ; <nl> + # if V8_COMPRESS_POINTERS <nl> + CSA_ASSERT ( this , IsValidSmi ( smi ) ) ; <nl> + # endif <nl> + return smi ; <nl> } <nl> <nl> TNode < BoolT > CodeStubAssembler : : IsValidPositiveSmi ( TNode < IntPtrT > value ) { <nl> TNode < Smi > CodeStubAssembler : : SmiTag ( SloppyTNode < IntPtrT > value ) { <nl> if ( ToInt32Constant ( value , constant_value ) & & Smi : : IsValid ( constant_value ) ) { <nl> return SmiConstant ( constant_value ) ; <nl> } <nl> - return BitcastWordToTaggedSigned ( WordShl ( value , SmiShiftBitsConstant ( ) ) ) ; <nl> + TNode < Smi > smi = <nl> + BitcastWordToTaggedSigned ( WordShl ( value , SmiShiftBitsConstant ( ) ) ) ; <nl> + # if V8_COMPRESS_POINTERS <nl> + CSA_ASSERT ( this , IsValidSmi ( smi ) ) ; <nl> + # endif <nl> + return smi ; <nl> } <nl> <nl> TNode < IntPtrT > CodeStubAssembler : : SmiUntag ( SloppyTNode < Smi > value ) { <nl> + # if V8_COMPRESS_POINTERS <nl> + CSA_ASSERT ( this , IsValidSmi ( value ) ) ; <nl> + # endif <nl> intptr_t constant_value ; <nl> if ( ToIntPtrConstant ( value , constant_value ) ) { <nl> return IntPtrConstant ( constant_value > > ( kSmiShiftSize + kSmiTagSize ) ) ; <nl> } <nl> - return UncheckedCast < IntPtrT > ( <nl> - WordSar ( BitcastTaggedToWord ( value ) , SmiShiftBitsConstant ( ) ) ) ; <nl> + return Signed ( WordSar ( BitcastTaggedToWord ( value ) , SmiShiftBitsConstant ( ) ) ) ; <nl> } <nl> <nl> TNode < Int32T > CodeStubAssembler : : SmiToInt32 ( SloppyTNode < Smi > value ) { <nl> TNode < Smi > CodeStubAssembler : : SmiMin ( TNode < Smi > a , TNode < Smi > b ) { <nl> <nl> TNode < Smi > CodeStubAssembler : : TrySmiAdd ( TNode < Smi > lhs , TNode < Smi > rhs , <nl> Label * if_overflow ) { <nl> - TNode < PairT < IntPtrT , BoolT > > pair = <nl> - IntPtrAddWithOverflow ( BitcastTaggedToWord ( lhs ) , BitcastTaggedToWord ( rhs ) ) ; <nl> - TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> - GotoIf ( overflow , if_overflow ) ; <nl> - TNode < IntPtrT > result = Projection < 0 > ( pair ) ; <nl> - return BitcastWordToTaggedSigned ( result ) ; <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> + TNode < PairT < IntPtrT , BoolT > > pair = IntPtrAddWithOverflow ( <nl> + BitcastTaggedToWord ( lhs ) , BitcastTaggedToWord ( rhs ) ) ; <nl> + TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> + GotoIf ( overflow , if_overflow ) ; <nl> + TNode < IntPtrT > result = Projection < 0 > ( pair ) ; <nl> + return BitcastWordToTaggedSigned ( result ) ; <nl> + } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> + TNode < PairT < Int32T , BoolT > > pair = <nl> + Int32AddWithOverflow ( TruncateIntPtrToInt32 ( BitcastTaggedToWord ( lhs ) ) , <nl> + TruncateIntPtrToInt32 ( BitcastTaggedToWord ( rhs ) ) ) ; <nl> + TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> + GotoIf ( overflow , if_overflow ) ; <nl> + TNode < Int32T > result = Projection < 0 > ( pair ) ; <nl> + return BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( result ) ) ; <nl> + } <nl> } <nl> <nl> TNode < Smi > CodeStubAssembler : : TrySmiSub ( TNode < Smi > lhs , TNode < Smi > rhs , <nl> Label * if_overflow ) { <nl> - TNode < PairT < IntPtrT , BoolT > > pair = <nl> - IntPtrSubWithOverflow ( BitcastTaggedToWord ( lhs ) , BitcastTaggedToWord ( rhs ) ) ; <nl> - TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> - GotoIf ( overflow , if_overflow ) ; <nl> - TNode < IntPtrT > result = Projection < 0 > ( pair ) ; <nl> - return BitcastWordToTaggedSigned ( result ) ; <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> + TNode < PairT < IntPtrT , BoolT > > pair = IntPtrSubWithOverflow ( <nl> + BitcastTaggedToWord ( lhs ) , BitcastTaggedToWord ( rhs ) ) ; <nl> + TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> + GotoIf ( overflow , if_overflow ) ; <nl> + TNode < IntPtrT > result = Projection < 0 > ( pair ) ; <nl> + return BitcastWordToTaggedSigned ( result ) ; <nl> + } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> + TNode < PairT < Int32T , BoolT > > pair = <nl> + Int32SubWithOverflow ( TruncateIntPtrToInt32 ( BitcastTaggedToWord ( lhs ) ) , <nl> + TruncateIntPtrToInt32 ( BitcastTaggedToWord ( rhs ) ) ) ; <nl> + TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> + GotoIf ( overflow , if_overflow ) ; <nl> + TNode < Int32T > result = Projection < 0 > ( pair ) ; <nl> + return BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( result ) ) ; <nl> + } <nl> } <nl> <nl> TNode < Object > CodeStubAssembler : : NumberMax ( SloppyTNode < Object > a , <nl> Node * CodeStubAssembler : : LoadObjectField ( SloppyTNode < HeapObject > object , <nl> <nl> TNode < IntPtrT > CodeStubAssembler : : LoadAndUntagObjectField ( <nl> SloppyTNode < HeapObject > object , int offset ) { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> offset + = kPointerSize / 2 ; <nl> # endif <nl> TNode < IntPtrT > CodeStubAssembler : : LoadAndUntagObjectField ( <nl> <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32ObjectField ( Node * object , <nl> int offset ) { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> offset + = kPointerSize / 2 ; <nl> # endif <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32ObjectField ( Node * object , <nl> } <nl> <nl> TNode < IntPtrT > CodeStubAssembler : : LoadAndUntagSmi ( Node * base , int index ) { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> index + = kPointerSize / 2 ; <nl> # endif <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32Root ( <nl> Node * roots_array_start = <nl> ExternalConstant ( ExternalReference : : roots_array_start ( isolate ( ) ) ) ; <nl> int index = root_index * kPointerSize ; <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> index + = kPointerSize / 2 ; <nl> # endif <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32Root ( <nl> } <nl> <nl> Node * CodeStubAssembler : : StoreAndTagSmi ( Node * base , int offset , Node * value ) { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> int zero_offset = offset + kPointerSize / 2 ; <nl> int payload_offset = offset ; <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32ArrayElement ( <nl> DCHECK_EQ ( additional_offset % kPointerSize , 0 ) ; <nl> int endian_correction = 0 ; <nl> # if V8_TARGET_LITTLE_ENDIAN <nl> - if ( Is64 ( ) ) endian_correction = kPointerSize / 2 ; <nl> + if ( SmiValuesAre32Bits ( ) ) endian_correction = kPointerSize / 2 ; <nl> # endif <nl> int32_t header_size = array_header_size + additional_offset - kHeapObjectTag + <nl> endian_correction ; <nl> TNode < Int32T > CodeStubAssembler : : LoadAndUntagToWord32ArrayElement ( <nl> offset , <nl> LoadAndUntagObjectField ( object , FixedArrayBase : : kLengthOffset ) , <nl> FixedArray : : kHeaderSize + endian_correction ) ) ; <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> return UncheckedCast < Int32T > ( Load ( MachineType : : Int32 ( ) , object , offset ) ) ; <nl> } else { <nl> return SmiToInt32 ( Load ( MachineType : : AnyTagged ( ) , object , offset ) ) ; <nl> TNode < Number > CodeStubAssembler : : ChangeFloat64ToTagged ( <nl> TVARIABLE ( Number , var_result ) ; <nl> BIND ( & if_valueisint32 ) ; <nl> { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> TNode < Smi > result = SmiTag ( ChangeInt32ToIntPtr ( value32 ) ) ; <nl> var_result = result ; <nl> Goto ( & if_join ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> TNode < PairT < Int32T , BoolT > > pair = Int32AddWithOverflow ( value32 , value32 ) ; <nl> TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> Label if_overflow ( this , Label : : kDeferred ) , if_notoverflow ( this ) ; <nl> TNode < Number > CodeStubAssembler : : ChangeFloat64ToTagged ( <nl> Goto ( & if_valueisheapnumber ) ; <nl> BIND ( & if_notoverflow ) ; <nl> { <nl> - TNode < IntPtrT > result = ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ; <nl> - var_result = BitcastWordToTaggedSigned ( result ) ; <nl> + TNode < Smi > result = <nl> + BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ) ; <nl> + var_result = result ; <nl> Goto ( & if_join ) ; <nl> } <nl> } <nl> TNode < Number > CodeStubAssembler : : ChangeFloat64ToTagged ( <nl> <nl> TNode < Number > CodeStubAssembler : : ChangeInt32ToTagged ( <nl> SloppyTNode < Int32T > value ) { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> return SmiTag ( ChangeInt32ToIntPtr ( value ) ) ; <nl> } <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> TVARIABLE ( Number , var_result ) ; <nl> TNode < PairT < Int32T , BoolT > > pair = Int32AddWithOverflow ( value , value ) ; <nl> TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> TNode < Number > CodeStubAssembler : : ChangeInt32ToTagged ( <nl> Goto ( & if_join ) ; <nl> BIND ( & if_notoverflow ) ; <nl> { <nl> - TNode < Smi > result = <nl> - BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ) ; <nl> + TNode < IntPtrT > almost_tagged_value = <nl> + ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ; <nl> + TNode < Smi > result ; <nl> + result = BitcastWordToTaggedSigned ( almost_tagged_value ) ; <nl> var_result = result ; <nl> } <nl> Goto ( & if_join ) ; <nl> TNode < Number > CodeStubAssembler : : ChangeUint32ToTagged ( <nl> <nl> BIND ( & if_not_overflow ) ; <nl> { <nl> - if ( Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> var_result = <nl> SmiTag ( ReinterpretCast < IntPtrT > ( ChangeUint32ToUint64 ( value ) ) ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> / / If tagging { value } results in an overflow , we need to use a HeapNumber <nl> / / to represent it . <nl> / / TODO ( tebbi ) : This overflow can never happen . <nl> TNode < Number > CodeStubAssembler : : ChangeUint32ToTagged ( <nl> TNode < BoolT > overflow = Projection < 1 > ( pair ) ; <nl> GotoIf ( overflow , & if_overflow ) ; <nl> <nl> - TNode < Smi > result = <nl> - BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ) ; <nl> - var_result = result ; <nl> + TNode < IntPtrT > almost_tagged_value = <nl> + ChangeInt32ToIntPtr ( Projection < 0 > ( pair ) ) ; <nl> + var_result = BitcastWordToTaggedSigned ( almost_tagged_value ) ; <nl> } <nl> } <nl> Goto ( & if_join ) ; <nl> TNode < String > CodeStubAssembler : : StringAdd ( Node * context , TNode < String > left , <nl> / / If new length is greater than String : : kMaxLength , goto runtime to <nl> / / throw . Note : we also need to invalidate the string length protector , so <nl> / / can ' t just throw here directly . <nl> - GotoIf ( SmiGreaterThan ( new_length , SmiConstant ( String : : kMaxLength ) ) , <nl> - & runtime ) ; <nl> + GotoIf ( SmiAbove ( new_length , SmiConstant ( String : : kMaxLength ) ) , & runtime ) ; <nl> <nl> TVARIABLE ( String , var_left , left ) ; <nl> TVARIABLE ( String , var_right , right ) ; <nl> mmm a / src / code - stub - assembler . h <nl> ppp b / src / code - stub - assembler . h <nl> struct IteratorRecord { <nl> compiler : : TNode < Object > next ; <nl> } ; <nl> <nl> + # define CSA_CHECK ( csa , x ) \ <nl> + ( csa ) - > Check ( \ <nl> + [ & ] ( ) - > compiler : : Node * { \ <nl> + return implicit_cast < compiler : : SloppyTNode < Word32T > > ( x ) ; \ <nl> + } , \ <nl> + # x , __FILE__ , __LINE__ ) <nl> + <nl> + # ifdef DEBUG <nl> + / / Add stringified versions to the given values , except the first . That is , <nl> + / / transform <nl> + / / x , a , b , c , d , e , f <nl> + / / to <nl> + / / a , " a " , b , " b " , c , " c " , d , " d " , e , " e " , f , " f " <nl> + / / <nl> + / / __VA_ARGS__ is ignored to allow the caller to pass through too many <nl> + / / parameters , and the first element is ignored to support having no extra <nl> + / / values without empty __VA_ARGS__ ( which cause all sorts of problems with <nl> + / / extra commas ) . <nl> + # define CSA_ASSERT_STRINGIFY_EXTRA_VALUES_5 ( _ , v1 , v2 , v3 , v4 , v5 , . . . ) \ <nl> + v1 , # v1 , v2 , # v2 , v3 , # v3 , v4 , # v4 , v5 , # v5 <nl> + <nl> + / / Stringify the given variable number of arguments . The arguments are trimmed <nl> + / / to 5 if there are too many , and padded with nullptr if there are not enough . <nl> + # define CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( . . . ) \ <nl> + CSA_ASSERT_STRINGIFY_EXTRA_VALUES_5 ( __VA_ARGS__ , nullptr , nullptr , nullptr , \ <nl> + nullptr , nullptr ) <nl> + <nl> + # define CSA_ASSERT_GET_FIRST ( x , . . . ) ( x ) <nl> + # define CSA_ASSERT_GET_FIRST_STR ( x , . . . ) # x <nl> + <nl> + / / CSA_ASSERT ( csa , < condition > , < extra values to print . . . > ) <nl> + <nl> + / / We have to jump through some hoops to allow < extra values to print . . . > to be <nl> + / / empty . <nl> + # define CSA_ASSERT ( csa , . . . ) \ <nl> + ( csa ) - > Assert ( \ <nl> + [ & ] ( ) - > compiler : : Node * { \ <nl> + return implicit_cast < compiler : : SloppyTNode < Word32T > > ( \ <nl> + EXPAND ( CSA_ASSERT_GET_FIRST ( __VA_ARGS__ ) ) ) ; \ <nl> + } , \ <nl> + EXPAND ( CSA_ASSERT_GET_FIRST_STR ( __VA_ARGS__ ) ) , __FILE__ , __LINE__ , \ <nl> + CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( __VA_ARGS__ ) ) <nl> + <nl> + / / CSA_ASSERT_BRANCH ( csa , [ ] ( Label * ok , Label * not_ok ) { . . . } , <nl> + / / < extra values to print . . . > ) <nl> + <nl> + # define CSA_ASSERT_BRANCH ( csa , . . . ) \ <nl> + ( csa ) - > Assert ( EXPAND ( CSA_ASSERT_GET_FIRST ( __VA_ARGS__ ) ) , \ <nl> + EXPAND ( CSA_ASSERT_GET_FIRST_STR ( __VA_ARGS__ ) ) , __FILE__ , \ <nl> + __LINE__ , CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( __VA_ARGS__ ) ) <nl> + <nl> + # define CSA_ASSERT_JS_ARGC_OP ( csa , Op , op , expected ) \ <nl> + ( csa ) - > Assert ( \ <nl> + [ & ] ( ) - > compiler : : Node * { \ <nl> + compiler : : Node * const argc = \ <nl> + ( csa ) - > Parameter ( Descriptor : : kActualArgumentsCount ) ; \ <nl> + return ( csa ) - > Op ( argc , ( csa ) - > Int32Constant ( expected ) ) ; \ <nl> + } , \ <nl> + " argc " # op " " # expected , __FILE__ , __LINE__ , \ <nl> + SmiFromInt32 ( ( csa ) - > Parameter ( Descriptor : : kActualArgumentsCount ) ) , \ <nl> + " argc " ) <nl> + <nl> + # define CSA_ASSERT_JS_ARGC_EQ ( csa , expected ) \ <nl> + CSA_ASSERT_JS_ARGC_OP ( csa , Word32Equal , = = , expected ) <nl> + <nl> + # define CSA_DEBUG_INFO ( name ) \ <nl> + { # name , __FILE__ , __LINE__ } <nl> + # define BIND ( label ) Bind ( label , CSA_DEBUG_INFO ( label ) ) <nl> + # define VARIABLE ( name , . . . ) \ <nl> + Variable name ( this , CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> + # define VARIABLE_CONSTRUCTOR ( name , . . . ) \ <nl> + name ( this , CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> + # define TYPED_VARIABLE_DEF ( type , name , . . . ) \ <nl> + TVariable < type > name ( CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> + # else / / DEBUG <nl> + # define CSA_ASSERT ( csa , . . . ) ( ( void ) 0 ) <nl> + # define CSA_ASSERT_BRANCH ( csa , . . . ) ( ( void ) 0 ) <nl> + # define CSA_ASSERT_JS_ARGC_EQ ( csa , expected ) ( ( void ) 0 ) <nl> + # define BIND ( label ) Bind ( label ) <nl> + # define VARIABLE ( name , . . . ) Variable name ( this , __VA_ARGS__ ) <nl> + # define VARIABLE_CONSTRUCTOR ( name , . . . ) name ( this , __VA_ARGS__ ) <nl> + # define TYPED_VARIABLE_DEF ( type , name , . . . ) TVariable < type > name ( __VA_ARGS__ ) <nl> + # endif / / DEBUG <nl> + <nl> + # define TVARIABLE ( . . . ) EXPAND ( TYPED_VARIABLE_DEF ( __VA_ARGS__ , this ) ) <nl> + <nl> + # ifdef ENABLE_SLOW_DCHECKS <nl> + # define CSA_SLOW_ASSERT ( csa , . . . ) \ <nl> + if ( FLAG_enable_slow_asserts ) { \ <nl> + CSA_ASSERT ( csa , __VA_ARGS__ ) ; \ <nl> + } <nl> + # else <nl> + # define CSA_SLOW_ASSERT ( csa , . . . ) ( ( void ) 0 ) <nl> + # endif <nl> + <nl> / / Provides JavaScript - specific " macro - assembler " functionality on top of the <nl> / / CodeAssembler . By factoring the JavaScript - isms out of the CodeAssembler , <nl> / / it ' s possible to add JavaScript - specific useful CodeAssembler " macros " <nl> class V8_EXPORT_PRIVATE CodeStubAssembler : public compiler : : CodeAssembler { <nl> TNode < Int32T > SmiToInt32 ( SloppyTNode < Smi > value ) ; <nl> <nl> / / Smi operations . <nl> - # define SMI_ARITHMETIC_BINOP ( SmiOpName , IntPtrOpName ) \ <nl> - TNode < Smi > SmiOpName ( TNode < Smi > a , TNode < Smi > b ) { \ <nl> - return BitcastWordToTaggedSigned ( \ <nl> - IntPtrOpName ( BitcastTaggedToWord ( a ) , BitcastTaggedToWord ( b ) ) ) ; \ <nl> - } <nl> - SMI_ARITHMETIC_BINOP ( SmiAdd , IntPtrAdd ) <nl> - SMI_ARITHMETIC_BINOP ( SmiSub , IntPtrSub ) <nl> - SMI_ARITHMETIC_BINOP ( SmiAnd , WordAnd ) <nl> - SMI_ARITHMETIC_BINOP ( SmiOr , WordOr ) <nl> + # define SMI_ARITHMETIC_BINOP ( SmiOpName , IntPtrOpName , Int32OpName ) \ <nl> + TNode < Smi > SmiOpName ( TNode < Smi > a , TNode < Smi > b ) { \ <nl> + if ( SmiValuesAre32Bits ( ) ) { \ <nl> + return BitcastWordToTaggedSigned ( \ <nl> + IntPtrOpName ( BitcastTaggedToWord ( a ) , BitcastTaggedToWord ( b ) ) ) ; \ <nl> + } else { \ <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; \ <nl> + if ( kPointerSize = = kInt64Size ) { \ <nl> + CSA_ASSERT ( this , IsValidSmi ( a ) ) ; \ <nl> + CSA_ASSERT ( this , IsValidSmi ( b ) ) ; \ <nl> + } \ <nl> + return BitcastWordToTaggedSigned ( ChangeInt32ToIntPtr ( \ <nl> + Int32OpName ( TruncateIntPtrToInt32 ( BitcastTaggedToWord ( a ) ) , \ <nl> + TruncateIntPtrToInt32 ( BitcastTaggedToWord ( b ) ) ) ) ) ; \ <nl> + } \ <nl> + } <nl> + SMI_ARITHMETIC_BINOP ( SmiAdd , IntPtrAdd , Int32Add ) <nl> + SMI_ARITHMETIC_BINOP ( SmiSub , IntPtrSub , Int32Sub ) <nl> + SMI_ARITHMETIC_BINOP ( SmiAnd , WordAnd , Word32And ) <nl> + SMI_ARITHMETIC_BINOP ( SmiOr , WordOr , Word32Or ) <nl> # undef SMI_ARITHMETIC_BINOP <nl> <nl> TNode < Smi > TrySmiAdd ( TNode < Smi > a , TNode < Smi > b , Label * if_overflow ) ; <nl> class V8_EXPORT_PRIVATE CodeStubAssembler : public compiler : : CodeAssembler { <nl> } <nl> } <nl> <nl> - # define SMI_COMPARISON_OP ( SmiOpName , IntPtrOpName ) \ <nl> - TNode < BoolT > SmiOpName ( TNode < Smi > a , TNode < Smi > b ) { \ <nl> - return IntPtrOpName ( BitcastTaggedToWord ( a ) , BitcastTaggedToWord ( b ) ) ; \ <nl> - } <nl> - SMI_COMPARISON_OP ( SmiEqual , WordEqual ) <nl> - SMI_COMPARISON_OP ( SmiNotEqual , WordNotEqual ) <nl> - SMI_COMPARISON_OP ( SmiAbove , UintPtrGreaterThan ) <nl> - SMI_COMPARISON_OP ( SmiAboveOrEqual , UintPtrGreaterThanOrEqual ) <nl> - SMI_COMPARISON_OP ( SmiBelow , UintPtrLessThan ) <nl> - SMI_COMPARISON_OP ( SmiLessThan , IntPtrLessThan ) <nl> - SMI_COMPARISON_OP ( SmiLessThanOrEqual , IntPtrLessThanOrEqual ) <nl> - SMI_COMPARISON_OP ( SmiGreaterThan , IntPtrGreaterThan ) <nl> - SMI_COMPARISON_OP ( SmiGreaterThanOrEqual , IntPtrGreaterThanOrEqual ) <nl> + # define SMI_COMPARISON_OP ( SmiOpName , IntPtrOpName , Int32OpName ) \ <nl> + TNode < BoolT > SmiOpName ( TNode < Smi > a , TNode < Smi > b ) { \ <nl> + if ( SmiValuesAre32Bits ( ) ) { \ <nl> + return IntPtrOpName ( BitcastTaggedToWord ( a ) , BitcastTaggedToWord ( b ) ) ; \ <nl> + } else { \ <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; \ <nl> + if ( kPointerSize = = kInt64Size ) { \ <nl> + CSA_ASSERT ( this , IsValidSmi ( a ) ) ; \ <nl> + CSA_ASSERT ( this , IsValidSmi ( b ) ) ; \ <nl> + } \ <nl> + return Int32OpName ( TruncateIntPtrToInt32 ( BitcastTaggedToWord ( a ) ) , \ <nl> + TruncateIntPtrToInt32 ( BitcastTaggedToWord ( b ) ) ) ; \ <nl> + } \ <nl> + } <nl> + SMI_COMPARISON_OP ( SmiEqual , WordEqual , Word32Equal ) <nl> + SMI_COMPARISON_OP ( SmiNotEqual , WordNotEqual , Word32NotEqual ) <nl> + SMI_COMPARISON_OP ( SmiAbove , UintPtrGreaterThan , Uint32GreaterThan ) <nl> + SMI_COMPARISON_OP ( SmiAboveOrEqual , UintPtrGreaterThanOrEqual , <nl> + Uint32GreaterThanOrEqual ) <nl> + SMI_COMPARISON_OP ( SmiBelow , UintPtrLessThan , Uint32LessThan ) <nl> + SMI_COMPARISON_OP ( SmiLessThan , IntPtrLessThan , Int32LessThan ) <nl> + SMI_COMPARISON_OP ( SmiLessThanOrEqual , IntPtrLessThanOrEqual , <nl> + Int32LessThanOrEqual ) <nl> + SMI_COMPARISON_OP ( SmiGreaterThan , IntPtrGreaterThan , Int32GreaterThan ) <nl> + SMI_COMPARISON_OP ( SmiGreaterThanOrEqual , IntPtrGreaterThanOrEqual , <nl> + Int32GreaterThanOrEqual ) <nl> # undef SMI_COMPARISON_OP <nl> TNode < Smi > SmiMax ( TNode < Smi > a , TNode < Smi > b ) ; <nl> TNode < Smi > SmiMin ( TNode < Smi > a , TNode < Smi > b ) ; <nl> class V8_EXPORT_PRIVATE CodeStubAssembler : public compiler : : CodeAssembler { <nl> Node * allocation_site , <nl> Node * size_in_bytes ) ; <nl> <nl> + TNode < BoolT > IsValidSmi ( TNode < Smi > smi ) ; <nl> Node * SmiShiftBitsConstant ( ) ; <nl> <nl> / / Emits keyed sloppy arguments load if the | value | is nullptr or store <nl> class ToDirectStringAssembler : public CodeStubAssembler { <nl> const Flags flags_ ; <nl> } ; <nl> <nl> - # define CSA_CHECK ( csa , x ) \ <nl> - ( csa ) - > Check ( \ <nl> - [ & ] ( ) - > compiler : : Node * { \ <nl> - return implicit_cast < compiler : : SloppyTNode < Word32T > > ( x ) ; \ <nl> - } , \ <nl> - # x , __FILE__ , __LINE__ ) <nl> - <nl> - # ifdef DEBUG <nl> - / / Add stringified versions to the given values , except the first . That is , <nl> - / / transform <nl> - / / x , a , b , c , d , e , f <nl> - / / to <nl> - / / a , " a " , b , " b " , c , " c " , d , " d " , e , " e " , f , " f " <nl> - / / <nl> - / / __VA_ARGS__ is ignored to allow the caller to pass through too many <nl> - / / parameters , and the first element is ignored to support having no extra <nl> - / / values without empty __VA_ARGS__ ( which cause all sorts of problems with <nl> - / / extra commas ) . <nl> - # define CSA_ASSERT_STRINGIFY_EXTRA_VALUES_5 ( _ , v1 , v2 , v3 , v4 , v5 , . . . ) \ <nl> - v1 , # v1 , v2 , # v2 , v3 , # v3 , v4 , # v4 , v5 , # v5 <nl> - <nl> - / / Stringify the given variable number of arguments . The arguments are trimmed <nl> - / / to 5 if there are too many , and padded with nullptr if there are not enough . <nl> - # define CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( . . . ) \ <nl> - CSA_ASSERT_STRINGIFY_EXTRA_VALUES_5 ( __VA_ARGS__ , nullptr , nullptr , nullptr , \ <nl> - nullptr , nullptr ) <nl> - <nl> - # define CSA_ASSERT_GET_FIRST ( x , . . . ) ( x ) <nl> - # define CSA_ASSERT_GET_FIRST_STR ( x , . . . ) # x <nl> - <nl> - / / CSA_ASSERT ( csa , < condition > , < extra values to print . . . > ) <nl> - <nl> - / / We have to jump through some hoops to allow < extra values to print . . . > to be <nl> - / / empty . <nl> - # define CSA_ASSERT ( csa , . . . ) \ <nl> - ( csa ) - > Assert ( \ <nl> - [ & ] ( ) - > compiler : : Node * { \ <nl> - return implicit_cast < compiler : : SloppyTNode < Word32T > > ( \ <nl> - EXPAND ( CSA_ASSERT_GET_FIRST ( __VA_ARGS__ ) ) ) ; \ <nl> - } , \ <nl> - EXPAND ( CSA_ASSERT_GET_FIRST_STR ( __VA_ARGS__ ) ) , __FILE__ , __LINE__ , \ <nl> - CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( __VA_ARGS__ ) ) <nl> - <nl> - / / CSA_ASSERT_BRANCH ( csa , [ ] ( Label * ok , Label * not_ok ) { . . . } , <nl> - / / < extra values to print . . . > ) <nl> - <nl> - # define CSA_ASSERT_BRANCH ( csa , . . . ) \ <nl> - ( csa ) - > Assert ( EXPAND ( CSA_ASSERT_GET_FIRST ( __VA_ARGS__ ) ) , \ <nl> - EXPAND ( CSA_ASSERT_GET_FIRST_STR ( __VA_ARGS__ ) ) , __FILE__ , \ <nl> - __LINE__ , CSA_ASSERT_STRINGIFY_EXTRA_VALUES ( __VA_ARGS__ ) ) <nl> - <nl> - # define CSA_ASSERT_JS_ARGC_OP ( csa , Op , op , expected ) \ <nl> - ( csa ) - > Assert ( \ <nl> - [ & ] ( ) - > compiler : : Node * { \ <nl> - compiler : : Node * const argc = \ <nl> - ( csa ) - > Parameter ( Descriptor : : kActualArgumentsCount ) ; \ <nl> - return ( csa ) - > Op ( argc , ( csa ) - > Int32Constant ( expected ) ) ; \ <nl> - } , \ <nl> - " argc " # op " " # expected , __FILE__ , __LINE__ , \ <nl> - SmiFromInt32 ( ( csa ) - > Parameter ( Descriptor : : kActualArgumentsCount ) ) , \ <nl> - " argc " ) <nl> - <nl> - # define CSA_ASSERT_JS_ARGC_EQ ( csa , expected ) \ <nl> - CSA_ASSERT_JS_ARGC_OP ( csa , Word32Equal , = = , expected ) <nl> - <nl> - # define CSA_DEBUG_INFO ( name ) \ <nl> - { # name , __FILE__ , __LINE__ } <nl> - # define BIND ( label ) Bind ( label , CSA_DEBUG_INFO ( label ) ) <nl> - # define VARIABLE ( name , . . . ) \ <nl> - Variable name ( this , CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> - # define VARIABLE_CONSTRUCTOR ( name , . . . ) \ <nl> - name ( this , CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> - # define TYPED_VARIABLE_DEF ( type , name , . . . ) \ <nl> - TVariable < type > name ( CSA_DEBUG_INFO ( name ) , __VA_ARGS__ ) <nl> - # else / / DEBUG <nl> - # define CSA_ASSERT ( csa , . . . ) ( ( void ) 0 ) <nl> - # define CSA_ASSERT_BRANCH ( csa , . . . ) ( ( void ) 0 ) <nl> - # define CSA_ASSERT_JS_ARGC_EQ ( csa , expected ) ( ( void ) 0 ) <nl> - # define BIND ( label ) Bind ( label ) <nl> - # define VARIABLE ( name , . . . ) Variable name ( this , __VA_ARGS__ ) <nl> - # define VARIABLE_CONSTRUCTOR ( name , . . . ) name ( this , __VA_ARGS__ ) <nl> - # define TYPED_VARIABLE_DEF ( type , name , . . . ) TVariable < type > name ( __VA_ARGS__ ) <nl> - # endif / / DEBUG <nl> - <nl> - # define TVARIABLE ( . . . ) EXPAND ( TYPED_VARIABLE_DEF ( __VA_ARGS__ , this ) ) <nl> - <nl> - # ifdef ENABLE_SLOW_DCHECKS <nl> - # define CSA_SLOW_ASSERT ( csa , . . . ) \ <nl> - if ( FLAG_enable_slow_asserts ) { \ <nl> - CSA_ASSERT ( csa , __VA_ARGS__ ) ; \ <nl> - } <nl> - # else <nl> - # define CSA_SLOW_ASSERT ( csa , . . . ) ( ( void ) 0 ) <nl> - # endif <nl> <nl> DEFINE_OPERATORS_FOR_FLAGS ( CodeStubAssembler : : AllocationFlags ) ; <nl> <nl> mmm a / src / compiler / code - assembler . h <nl> ppp b / src / compiler / code - assembler . h <nl> class SloppyTNode : public TNode < T > { <nl> V ( Int32Add , Word32T , Word32T , Word32T ) \ <nl> V ( Int32AddWithOverflow , PAIR_TYPE ( Int32T , BoolT ) , Int32T , Int32T ) \ <nl> V ( Int32Sub , Word32T , Word32T , Word32T ) \ <nl> + V ( Int32SubWithOverflow , PAIR_TYPE ( Int32T , BoolT ) , Int32T , Int32T ) \ <nl> V ( Int32Mul , Word32T , Word32T , Word32T ) \ <nl> V ( Int32MulWithOverflow , PAIR_TYPE ( Int32T , BoolT ) , Int32T , Int32T ) \ <nl> V ( Int32Div , Int32T , Int32T , Int32T ) \ <nl> mmm a / src / compiler / effect - control - linearizer . cc <nl> ppp b / src / compiler / effect - control - linearizer . cc <nl> Node * EffectControlLinearizer : : LowerChangeFloat64ToTagged ( Node * node ) { <nl> __ Bind ( & if_smi ) ; <nl> } <nl> <nl> - if ( machine ( ) - > Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> Node * value_smi = ChangeInt32ToSmi ( value32 ) ; <nl> __ Goto ( & done , value_smi ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> Node * add = __ Int32AddWithOverflow ( value32 , value32 ) ; <nl> Node * ovf = __ Projection ( 1 , add ) ; <nl> __ GotoIf ( ovf , & if_heapnumber ) ; <nl> Node * value_smi = __ Projection ( 0 , add ) ; <nl> + value_smi = ChangeInt32ToIntPtr ( value_smi ) ; <nl> __ Goto ( & done , value_smi ) ; <nl> } <nl> } <nl> Node * EffectControlLinearizer : : LowerChangeInt31ToTaggedSigned ( Node * node ) { <nl> Node * EffectControlLinearizer : : LowerChangeInt32ToTagged ( Node * node ) { <nl> Node * value = node - > InputAt ( 0 ) ; <nl> <nl> - if ( machine ( ) - > Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> return ChangeInt32ToSmi ( value ) ; <nl> } <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> <nl> auto if_overflow = __ MakeDeferredLabel ( ) ; <nl> auto done = __ MakeLabel ( MachineRepresentation : : kTagged ) ; <nl> Node * EffectControlLinearizer : : LowerChangeInt32ToTagged ( Node * node ) { <nl> Node * add = __ Int32AddWithOverflow ( value , value ) ; <nl> Node * ovf = __ Projection ( 1 , add ) ; <nl> __ GotoIf ( ovf , & if_overflow ) ; <nl> - __ Goto ( & done , __ Projection ( 0 , add ) ) ; <nl> + Node * value_smi = __ Projection ( 0 , add ) ; <nl> + value_smi = ChangeInt32ToIntPtr ( value_smi ) ; <nl> + __ Goto ( & done , value_smi ) ; <nl> <nl> __ Bind ( & if_overflow ) ; <nl> Node * number = AllocateHeapNumberWithValue ( __ ChangeInt32ToFloat64 ( value ) ) ; <nl> Node * EffectControlLinearizer : : LowerCheckedInt32ToTaggedSigned ( <nl> Node * check = __ Projection ( 1 , add ) ; <nl> __ DeoptimizeIf ( DeoptimizeReason : : kOverflow , params . feedback ( ) , check , <nl> frame_state ) ; <nl> - return __ Projection ( 0 , add ) ; <nl> + Node * result = __ Projection ( 0 , add ) ; <nl> + result = ChangeInt32ToIntPtr ( result ) ; <nl> + return result ; <nl> } <nl> <nl> Node * EffectControlLinearizer : : LowerCheckedUint32ToInt32 ( Node * node , <nl> mmm a / src / compiler / wasm - compiler . cc <nl> ppp b / src / compiler / wasm - compiler . cc <nl> bool CanCover ( Node * value , IrOpcode : : Value opcode ) { <nl> return true ; <nl> } <nl> <nl> - Node * WasmGraphBuilder : : BuildChangeInt32ToSmi ( Node * value ) { <nl> + Node * WasmGraphBuilder : : BuildChangeInt32ToIntPtr ( Node * value ) { <nl> if ( mcgraph ( ) - > machine ( ) - > Is64 ( ) ) { <nl> value = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > ChangeInt32ToInt64 ( ) , value ) ; <nl> } <nl> + return value ; <nl> + } <nl> + <nl> + Node * WasmGraphBuilder : : BuildChangeInt32ToSmi ( Node * value ) { <nl> + value = BuildChangeInt32ToIntPtr ( value ) ; <nl> return graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > WordShl ( ) , value , <nl> BuildSmiShiftBitsConstant ( ) ) ; <nl> } <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> MachineOperatorBuilder * machine = mcgraph ( ) - > machine ( ) ; <nl> CommonOperatorBuilder * common = mcgraph ( ) - > common ( ) ; <nl> <nl> - if ( machine - > Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> return BuildChangeInt32ToSmi ( value ) ; <nl> } <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> <nl> Node * effect = * effect_ ; <nl> Node * control = * control_ ; <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> <nl> Node * if_false = graph ( ) - > NewNode ( common - > IfFalse ( ) , branch ) ; <nl> Node * vfalse = graph ( ) - > NewNode ( common - > Projection ( 0 ) , add , if_false ) ; <nl> + vfalse = BuildChangeInt32ToIntPtr ( vfalse ) ; <nl> <nl> Node * merge = graph ( ) - > NewNode ( common - > Merge ( 2 ) , if_true , if_false ) ; <nl> Node * phi = graph ( ) - > NewNode ( common - > Phi ( MachineRepresentation : : kTagged , 2 ) , <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> / / On 64 - bit machines we can just wrap the 32 - bit integer in a smi , for <nl> / / 32 - bit machines we need to deal with potential overflow and fallback to <nl> / / boxing . <nl> - if ( machine - > Is64 ( ) ) { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> vsmi = BuildChangeInt32ToSmi ( value32 ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> Node * smi_tag = graph ( ) - > NewNode ( machine - > Int32AddWithOverflow ( ) , value32 , <nl> value32 , if_smi ) ; <nl> <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> <nl> if_smi = graph ( ) - > NewNode ( common - > IfFalse ( ) , branch_ovf ) ; <nl> vsmi = graph ( ) - > NewNode ( common - > Projection ( 0 ) , smi_tag , if_smi ) ; <nl> + vsmi = BuildChangeInt32ToIntPtr ( vsmi ) ; <nl> } <nl> <nl> / / Allocate the box for the { value } . <nl> mmm a / src / compiler / wasm - compiler . h <nl> ppp b / src / compiler / wasm - compiler . h <nl> class WasmGraphBuilder { <nl> MachineType result_type , wasm : : TrapReason trap_zero , <nl> wasm : : WasmCodePosition position ) ; <nl> <nl> + Node * BuildChangeInt32ToIntPtr ( Node * value ) ; <nl> Node * BuildChangeInt32ToSmi ( Node * value ) ; <nl> Node * BuildChangeUint31ToSmi ( Node * value ) ; <nl> Node * BuildSmiShiftBitsConstant ( ) ; <nl> mmm a / src / globals . h <nl> ppp b / src / globals . h <nl> inline std : : ostream & operator < < ( std : : ostream & os , <nl> UNREACHABLE ( ) ; <nl> } <nl> <nl> + static_assert ( kSmiValueSize < = 32 , " Unsupported Smi tagging scheme " ) ; <nl> + / / Smi sign bit position must be 32 - bit aligned so we can use sign extension <nl> + / / instructions on 64 - bit architectures without additional shifts . <nl> + static_assert ( ( kSmiValueSize + kSmiShiftSize + kSmiTagSize ) % 32 = = 0 , <nl> + " Unsupported Smi tagging scheme " ) ; <nl> + <nl> + constexpr bool kIsSmiValueInUpper32Bits = <nl> + ( kSmiValueSize + kSmiShiftSize + kSmiTagSize ) = = 64 ; <nl> + constexpr bool kIsSmiValueInLower32Bits = <nl> + ( kSmiValueSize + kSmiShiftSize + kSmiTagSize ) = = 32 ; <nl> + static_assert ( ! SmiValuesAre32Bits ( ) = = SmiValuesAre31Bits ( ) , <nl> + " Unsupported Smi tagging scheme " ) ; <nl> + static_assert ( SmiValuesAre32Bits ( ) = = kIsSmiValueInUpper32Bits , <nl> + " Unsupported Smi tagging scheme " ) ; <nl> + static_assert ( SmiValuesAre31Bits ( ) = = kIsSmiValueInLower32Bits , <nl> + " Unsupported Smi tagging scheme " ) ; <nl> + <nl> / / Mask for the sign bit in a smi . <nl> - constexpr intptr_t kSmiSignMask = kIntptrSignBit ; <nl> + constexpr intptr_t kSmiSignMask = static_cast < intptr_t > ( <nl> + uintptr_t { 1 } < < ( kSmiValueSize + kSmiShiftSize + kSmiTagSize - 1 ) ) ; <nl> <nl> constexpr int kObjectAlignmentBits = kPointerSizeLog2 ; <nl> constexpr intptr_t kObjectAlignment = 1 < < kObjectAlignmentBits ; <nl> mmm a / src / layout - descriptor - inl . h <nl> ppp b / src / layout - descriptor - inl . h <nl> LayoutDescriptor * LayoutDescriptor : : FromSmi ( Smi * smi ) { <nl> <nl> <nl> Handle < LayoutDescriptor > LayoutDescriptor : : New ( Isolate * isolate , int length ) { <nl> - if ( length < = kSmiValueSize ) { <nl> + if ( length < = kBitsInSmiLayout ) { <nl> / / The whole bit vector fits into a smi . <nl> return handle ( LayoutDescriptor : : FromSmi ( Smi : : kZero ) , isolate ) ; <nl> } <nl> bool LayoutDescriptor : : IsSlowLayout ( ) { return ! IsSmi ( ) ; } <nl> <nl> <nl> int LayoutDescriptor : : capacity ( ) { <nl> - return IsSlowLayout ( ) ? ( length ( ) * kBitsPerByte ) : kSmiValueSize ; <nl> + return IsSlowLayout ( ) ? ( length ( ) * kBitsPerByte ) : kBitsInSmiLayout ; <nl> } <nl> <nl> <nl> int LayoutDescriptor : : CalculateCapacity ( Map * map , DescriptorArray * descriptors , <nl> int layout_descriptor_length ; <nl> const int kMaxWordsPerField = kDoubleSize / kPointerSize ; <nl> <nl> - if ( num_descriptors < = kSmiValueSize / kMaxWordsPerField ) { <nl> + if ( num_descriptors < = kBitsInSmiLayout / kMaxWordsPerField ) { <nl> / / Even in the " worst " case ( all fields are doubles ) it would fit into <nl> / / a Smi , so no need to calculate length . <nl> - layout_descriptor_length = kSmiValueSize ; <nl> + layout_descriptor_length = kBitsInSmiLayout ; <nl> <nl> } else { <nl> layout_descriptor_length = 0 ; <nl> mmm a / src / layout - descriptor . cc <nl> ppp b / src / layout - descriptor . cc <nl> bool LayoutDescriptor : : IsTagged ( int field_index , int max_sequence_length , <nl> bool is_tagged = ( value & layout_mask ) = = 0 ; <nl> if ( ! is_tagged ) value = ~ value ; / / Count set bits instead of cleared bits . <nl> value = value & ~ ( layout_mask - 1 ) ; / / Clear bits we are not interested in . <nl> - int sequence_length = <nl> - base : : bits : : CountTrailingZeros ( value ) - layout_bit_index ; <nl> + int sequence_length ; <nl> + if ( IsSlowLayout ( ) ) { <nl> + sequence_length = base : : bits : : CountTrailingZeros ( value ) - layout_bit_index ; <nl> <nl> - if ( layout_bit_index + sequence_length = = kBitsPerLayoutWord ) { <nl> - / / This is a contiguous sequence till the end of current word , proceed <nl> - / / counting in the subsequent words . <nl> - if ( IsSlowLayout ( ) ) { <nl> + if ( layout_bit_index + sequence_length = = kBitsPerLayoutWord ) { <nl> + / / This is a contiguous sequence till the end of current word , proceed <nl> + / / counting in the subsequent words . <nl> + + layout_word_index ; <nl> int num_words = number_of_layout_words ( ) ; <nl> for ( ; layout_word_index < num_words ; layout_word_index + + ) { <nl> bool LayoutDescriptor : : IsTagged ( int field_index , int max_sequence_length , <nl> if ( sequence_length > = max_sequence_length ) break ; <nl> if ( cur_sequence_length ! = kBitsPerLayoutWord ) break ; <nl> } <nl> + if ( is_tagged & & ( field_index + sequence_length = = capacity ( ) ) ) { <nl> + / / The contiguous sequence of tagged fields lasts till the end of the <nl> + / / layout descriptor which means that all the fields starting from <nl> + / / field_index are tagged . <nl> + sequence_length = std : : numeric_limits < int > : : max ( ) ; <nl> + } <nl> } <nl> + } else { / / Fast layout . <nl> + sequence_length = Min ( base : : bits : : CountTrailingZeros ( value ) , <nl> + static_cast < unsigned > ( kBitsInSmiLayout ) ) - <nl> + layout_bit_index ; <nl> if ( is_tagged & & ( field_index + sequence_length = = capacity ( ) ) ) { <nl> / / The contiguous sequence of tagged fields lasts till the end of the <nl> / / layout descriptor which means that all the fields starting from <nl> mmm a / src / layout - descriptor . h <nl> ppp b / src / layout - descriptor . h <nl> class LayoutDescriptor : public ByteArray { <nl> LayoutDescriptor * SetTaggedForTesting ( int field_index , bool tagged ) ; <nl> <nl> private : <nl> + / / Exclude sign - bit to simplify encoding . <nl> + static constexpr int kBitsInSmiLayout = <nl> + SmiValuesAre32Bits ( ) ? 32 : kSmiValueSize - 1 ; <nl> + <nl> static const int kBitsPerLayoutWord = 32 ; <nl> int number_of_layout_words ( ) { return length ( ) / kUInt32Size ; } <nl> uint32_t get_layout_word ( int index ) const { return get_uint32 ( index ) ; } <nl> mmm a / src / mips64 / macro - assembler - mips64 . cc <nl> ppp b / src / mips64 / macro - assembler - mips64 . cc <nl> void TurboAssembler : : SmiUntag ( Register dst , const MemOperand & src ) { <nl> if ( SmiValuesAre32Bits ( ) ) { <nl> Lw ( dst , MemOperand ( src . rm ( ) , SmiWordOffset ( src . offset ( ) ) ) ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> Lw ( dst , src ) ; <nl> SmiUntag ( dst ) ; <nl> } <nl> mmm a / src / mips64 / macro - assembler - mips64 . h <nl> ppp b / src / mips64 / macro - assembler - mips64 . h <nl> class TurboAssembler : public Assembler { <nl> void SmiUntag ( Register dst , const MemOperand & src ) ; <nl> void SmiUntag ( Register dst , Register src ) { <nl> if ( SmiValuesAre32Bits ( ) ) { <nl> - STATIC_ASSERT ( kSmiShift = = 32 ) ; <nl> - dsra32 ( dst , src , 0 ) ; <nl> + dsra32 ( dst , src , kSmiShift - 32 ) ; <nl> } else { <nl> - sra ( dst , src , kSmiTagSize ) ; <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> + sra ( dst , src , kSmiShift ) ; <nl> } <nl> } <nl> <nl> const Operand & rt = Operand ( zero_reg ) , BranchDelaySlot bd = PROTECT <nl> void SmiTag ( Register dst , Register src ) { <nl> STATIC_ASSERT ( kSmiTag = = 0 ) ; <nl> if ( SmiValuesAre32Bits ( ) ) { <nl> - STATIC_ASSERT ( kSmiShift = = 32 ) ; <nl> dsll32 ( dst , src , 0 ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> Addu ( dst , src , src ) ; <nl> } <nl> } <nl> const Operand & rt = Operand ( zero_reg ) , BranchDelaySlot bd = PROTECT <nl> / / The int portion is upper 32 - bits of 64 - bit word . <nl> dsra ( dst , src , kSmiShift - scale ) ; <nl> } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> DCHECK_GE ( scale , kSmiTagSize ) ; <nl> sll ( dst , src , scale - kSmiTagSize ) ; <nl> } <nl> mmm a / src / string - search . h <nl> ppp b / src / string - search . h <nl> int SearchString ( Isolate * isolate , <nl> / / and pattern as vectors before calling SearchString . Used from the <nl> / / StringIndexOf builtin . <nl> template < typename SubjectChar , typename PatternChar > <nl> - int SearchStringRaw ( Isolate * isolate , const SubjectChar * subject_ptr , <nl> - int subject_length , const PatternChar * pattern_ptr , <nl> - int pattern_length , int start_index ) { <nl> + intptr_t SearchStringRaw ( Isolate * isolate , const SubjectChar * subject_ptr , <nl> + int subject_length , const PatternChar * pattern_ptr , <nl> + int pattern_length , int start_index ) { <nl> DisallowHeapAllocation no_gc ; <nl> Vector < const SubjectChar > subject ( subject_ptr , subject_length ) ; <nl> Vector < const PatternChar > pattern ( pattern_ptr , pattern_length ) ; <nl> mmm a / src / wasm / baseline / arm / liftoff - assembler - arm . h <nl> ppp b / src / wasm / baseline / arm / liftoff - assembler - arm . h <nl> bool LiftoffAssembler : : emit_i64_remu ( LiftoffRegister dst , LiftoffRegister lhs , <nl> return false ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + UNREACHABLE ( ) ; <nl> + } <nl> + <nl> bool LiftoffAssembler : : emit_type_conversion ( WasmOpcode opcode , <nl> LiftoffRegister dst , <nl> LiftoffRegister src , Label * trap ) { <nl> mmm a / src / wasm / baseline / arm64 / liftoff - assembler - arm64 . h <nl> ppp b / src / wasm / baseline / arm64 / liftoff - assembler - arm64 . h <nl> bool LiftoffAssembler : : emit_i64_remu ( LiftoffRegister dst , LiftoffRegister lhs , <nl> return true ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + Sxtw ( dst , src ) ; <nl> + } <nl> + <nl> bool LiftoffAssembler : : emit_type_conversion ( WasmOpcode opcode , <nl> LiftoffRegister dst , <nl> LiftoffRegister src , Label * trap ) { <nl> mmm a / src / wasm / baseline / ia32 / liftoff - assembler - ia32 . h <nl> ppp b / src / wasm / baseline / ia32 / liftoff - assembler - ia32 . h <nl> void LiftoffAssembler : : emit_i64_shr ( LiftoffRegister dst , LiftoffRegister src , <nl> & TurboAssembler : : ShrPair_cl , pinned ) ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + UNREACHABLE ( ) ; <nl> + } <nl> + <nl> void LiftoffAssembler : : emit_f32_add ( DoubleRegister dst , DoubleRegister lhs , <nl> DoubleRegister rhs ) { <nl> if ( CpuFeatures : : IsSupported ( AVX ) ) { <nl> mmm a / src / wasm / baseline / liftoff - assembler . h <nl> ppp b / src / wasm / baseline / liftoff - assembler . h <nl> class LiftoffAssembler : public TurboAssembler { <nl> inline void emit_i64_shr ( LiftoffRegister dst , LiftoffRegister src , <nl> Register amount , LiftoffRegList pinned = { } ) ; <nl> <nl> + inline void emit_i32_to_intptr ( Register dst , Register src ) ; <nl> + <nl> inline void emit_ptrsize_add ( Register dst , Register lhs , Register rhs ) { <nl> if ( kPointerSize = = 8 ) { <nl> emit_i64_add ( LiftoffRegister ( dst ) , LiftoffRegister ( lhs ) , <nl> mmm a / src / wasm / baseline / liftoff - compiler . cc <nl> ppp b / src / wasm / baseline / liftoff - compiler . cc <nl> class LiftoffCompiler { <nl> void Int32ToSmi ( LiftoffRegister dst , Register src , Register scratch ) { <nl> constexpr int kTotalSmiShift = kSmiTagSize + kSmiShiftSize ; <nl> / / TODO ( clemensh ) : Shift by immediate directly . <nl> - if ( kPointerSize = = 4 ) { <nl> - __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> - WasmValue ( int32_t { kTotalSmiShift } ) ) ; <nl> - __ emit_i32_shl ( dst . gp ( ) , src , scratch ) ; <nl> - } else { <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> WasmValue ( int64_t { kTotalSmiShift } ) ) ; <nl> __ emit_i64_shl ( dst , LiftoffRegister ( src ) , scratch ) ; <nl> + } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> + __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> + WasmValue ( int32_t { kTotalSmiShift } ) ) ; <nl> + __ emit_i32_shl ( dst . gp ( ) , src , scratch ) ; <nl> + if ( kPointerSize = = kInt64Size ) { <nl> + __ emit_i32_to_intptr ( dst . gp ( ) , dst . gp ( ) ) ; <nl> + } <nl> } <nl> } <nl> <nl> void SmiToInt32 ( Register dst , LiftoffRegister src , Register scratch ) { <nl> constexpr int kTotalSmiShift = kSmiTagSize + kSmiShiftSize ; <nl> / / TODO ( clemensh ) : Shift by immediate directly . <nl> - if ( kPointerSize = = 4 ) { <nl> - __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> - WasmValue ( int32_t { kTotalSmiShift } ) ) ; <nl> - __ emit_i32_sar ( dst , src . gp ( ) , scratch ) ; <nl> - } else { <nl> - / / Assert that we shift by exactly 32 bit . This makes the returned value a <nl> - / / zero - extended 32 - bit value without emitting further instructions . <nl> - static_assert ( kPointerSize = = 4 | | kTotalSmiShift = = 32 , <nl> - " shift by exactly 32 bit " ) ; <nl> + if ( SmiValuesAre32Bits ( ) ) { <nl> __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> WasmValue ( int64_t { kTotalSmiShift } ) ) ; <nl> __ emit_i64_shr ( LiftoffRegister ( dst ) , src , scratch ) ; <nl> + } else { <nl> + DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> + __ LoadConstant ( LiftoffRegister ( scratch ) , <nl> + WasmValue ( int32_t { kTotalSmiShift } ) ) ; <nl> + __ emit_i32_sar ( dst , src . gp ( ) , scratch ) ; <nl> } <nl> } <nl> <nl> mmm a / src / wasm / baseline / mips / liftoff - assembler - mips . h <nl> ppp b / src / wasm / baseline / mips / liftoff - assembler - mips . h <nl> void LiftoffAssembler : : emit_i64_shr ( LiftoffRegister dst , LiftoffRegister src , <nl> & TurboAssembler : : ShrPair , pinned ) ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + UNREACHABLE ( ) ; <nl> + } <nl> + <nl> void LiftoffAssembler : : emit_f32_neg ( DoubleRegister dst , DoubleRegister src ) { <nl> TurboAssembler : : Neg_s ( dst , src ) ; <nl> } <nl> mmm a / src / wasm / baseline / mips64 / liftoff - assembler - mips64 . h <nl> ppp b / src / wasm / baseline / mips64 / liftoff - assembler - mips64 . h <nl> I64_SHIFTOP ( shr , dsrlv ) <nl> <nl> # undef I64_SHIFTOP <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + addu ( dst , src , zero_reg ) ; <nl> + } <nl> + <nl> void LiftoffAssembler : : emit_f32_neg ( DoubleRegister dst , DoubleRegister src ) { <nl> TurboAssembler : : Neg_s ( dst , src ) ; <nl> } <nl> mmm a / src / wasm / baseline / ppc / liftoff - assembler - ppc . h <nl> ppp b / src / wasm / baseline / ppc / liftoff - assembler - ppc . h <nl> bool LiftoffAssembler : : emit_i64_remu ( LiftoffRegister dst , LiftoffRegister lhs , <nl> return true ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + UNREACHABLE ( ) ; <nl> + } <nl> + <nl> bool LiftoffAssembler : : emit_type_conversion ( WasmOpcode opcode , <nl> LiftoffRegister dst , <nl> LiftoffRegister src , Label * trap ) { <nl> mmm a / src / wasm / baseline / s390 / liftoff - assembler - s390 . h <nl> ppp b / src / wasm / baseline / s390 / liftoff - assembler - s390 . h <nl> bool LiftoffAssembler : : emit_i64_remu ( LiftoffRegister dst , LiftoffRegister lhs , <nl> return true ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + UNREACHABLE ( ) ; <nl> + } <nl> + <nl> bool LiftoffAssembler : : emit_type_conversion ( WasmOpcode opcode , <nl> LiftoffRegister dst , <nl> LiftoffRegister src , Label * trap ) { <nl> mmm a / src / wasm / baseline / x64 / liftoff - assembler - x64 . h <nl> ppp b / src / wasm / baseline / x64 / liftoff - assembler - x64 . h <nl> void LiftoffAssembler : : emit_i64_shr ( LiftoffRegister dst , LiftoffRegister src , <nl> & Assembler : : shrq_cl , pinned ) ; <nl> } <nl> <nl> + void LiftoffAssembler : : emit_i32_to_intptr ( Register dst , Register src ) { <nl> + movsxlq ( dst , src ) ; <nl> + } <nl> + <nl> void LiftoffAssembler : : emit_f32_add ( DoubleRegister dst , DoubleRegister lhs , <nl> DoubleRegister rhs ) { <nl> if ( CpuFeatures : : IsSupported ( AVX ) ) { <nl> mmm a / src / x64 / macro - assembler - x64 . cc <nl> ppp b / src / x64 / macro - assembler - x64 . cc <nl> void MacroAssembler : : SmiTag ( Register dst , Register src ) { <nl> if ( dst ! = src ) { <nl> movp ( dst , src ) ; <nl> } <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> shlp ( dst , Immediate ( kSmiShift ) ) ; <nl> } <nl> <nl> void TurboAssembler : : SmiUntag ( Register dst , Register src ) { <nl> if ( dst ! = src ) { <nl> movp ( dst , src ) ; <nl> } <nl> + DCHECK ( SmiValuesAre32Bits ( ) | | SmiValuesAre31Bits ( ) ) ; <nl> sarp ( dst , Immediate ( kSmiShift ) ) ; <nl> } <nl> <nl> void MacroAssembler : : SmiAddConstant ( Operand dst , Smi * constant ) { <nl> Immediate ( constant - > value ( ) ) ) ; <nl> } else { <nl> DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> - addp ( dst , Immediate ( constant ) ) ; <nl> + if ( kPointerSize = = kInt64Size ) { <nl> + / / Sign - extend value after addition <nl> + movl ( kScratchRegister , dst ) ; <nl> + addl ( kScratchRegister , Immediate ( constant ) ) ; <nl> + movsxlq ( kScratchRegister , kScratchRegister ) ; <nl> + movq ( dst , kScratchRegister ) ; <nl> + } else { <nl> + DCHECK_EQ ( kSmiShiftSize , 32 ) ; <nl> + addp ( dst , Immediate ( constant ) ) ; <nl> + } <nl> } <nl> } <nl> } <nl> SmiIndex MacroAssembler : : SmiToIndex ( Register dst , <nl> return SmiIndex ( dst , times_1 ) ; <nl> } else { <nl> DCHECK ( SmiValuesAre31Bits ( ) ) ; <nl> - DCHECK ( shift > = times_1 & & shift < = ( static_cast < int > ( times_8 ) + 1 ) ) ; <nl> if ( dst ! = src ) { <nl> movp ( dst , src ) ; <nl> } <nl> / / We have to sign extend the index register to 64 - bit as the SMI might <nl> / / be negative . <nl> movsxlq ( dst , dst ) ; <nl> - if ( shift = = times_1 ) { <nl> - sarq ( dst , Immediate ( kSmiShift ) ) ; <nl> - return SmiIndex ( dst , times_1 ) ; <nl> + if ( shift < kSmiShift ) { <nl> + sarq ( dst , Immediate ( kSmiShift - shift ) ) ; <nl> + } else if ( shift ! = kSmiShift ) { <nl> + if ( shift - kSmiShift < = static_cast < int > ( times_8 ) ) { <nl> + return SmiIndex ( dst , static_cast < ScaleFactor > ( shift - kSmiShift ) ) ; <nl> + } <nl> + shlq ( dst , Immediate ( shift - kSmiShift ) ) ; <nl> } <nl> - return SmiIndex ( dst , static_cast < ScaleFactor > ( shift - 1 ) ) ; <nl> + return SmiIndex ( dst , times_1 ) ; <nl> } <nl> } <nl> <nl> mmm a / test / cctest / test - log - stack - tracer . cc <nl> ppp b / test / cctest / test - log - stack - tracer . cc <nl> static void construct_call ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> . FromJust ( ) ; <nl> # elif defined ( V8_HOST_ARCH_64_BIT ) <nl> Address fp = calling_frame - > fp ( ) ; <nl> - int32_t low_bits = static_cast < int32_t > ( fp & 0xFFFFFFFF ) ; <nl> - int32_t high_bits = static_cast < int32_t > ( fp > > 32 ) ; <nl> - args . This ( ) - > Set ( context , v8_str ( " low_bits " ) , v8_num ( low_bits ) ) . FromJust ( ) ; <nl> - args . This ( ) - > Set ( context , v8_str ( " high_bits " ) , v8_num ( high_bits ) ) . FromJust ( ) ; <nl> + uint64_t kSmiValueMask = <nl> + ( static_cast < uintptr_t > ( 1 ) < < ( kSmiValueSize - 1 ) ) - 1 ; <nl> + int32_t low_bits = static_cast < int32_t > ( fp & kSmiValueMask ) ; <nl> + fp > > = kSmiValueSize - 1 ; <nl> + int32_t high_bits = static_cast < int32_t > ( fp & kSmiValueMask ) ; <nl> + fp > > = kSmiValueSize - 1 ; <nl> + CHECK_EQ ( fp , 0 ) ; / / Ensure all the bits are successfully encoded . <nl> + args . This ( ) - > Set ( context , v8_str ( " low_bits " ) , v8_int ( low_bits ) ) . FromJust ( ) ; <nl> + args . This ( ) - > Set ( context , v8_str ( " high_bits " ) , v8_int ( high_bits ) ) . FromJust ( ) ; <nl> # else <nl> # error Host architecture is neither 32 - bit nor 64 - bit . <nl> # endif <nl> mmm a / test / cctest / test - macro - assembler - x64 . cc <nl> ppp b / test / cctest / test - macro - assembler - x64 . cc <nl> TEST ( SmiCompare ) { <nl> Isolate * isolate = CcTest : : i_isolate ( ) ; <nl> HandleScope handles ( isolate ) ; <nl> size_t allocated ; <nl> - byte * buffer = AllocateAssemblerBuffer ( & allocated ) ; <nl> + byte * buffer = <nl> + AllocateAssemblerBuffer ( & allocated , 2 * Assembler : : kMinimalBufferSize ) ; <nl> MacroAssembler assembler ( isolate , buffer , static_cast < int > ( allocated ) , <nl> v8 : : internal : : CodeObjectRequired : : kYes ) ; <nl> <nl> mmm a / test / cctest / test - unboxed - doubles . cc <nl> ppp b / test / cctest / test - unboxed - doubles . cc <nl> void WriteToField ( JSObject * object , int descriptor , Object * value ) { <nl> } <nl> <nl> const int kNumberOfBits = 32 ; <nl> + const int kBitsInSmiLayout = SmiValuesAre32Bits ( ) ? 32 : kSmiValueSize - 1 ; <nl> <nl> enum TestPropertyKind { <nl> PROP_ACCESSOR_INFO , <nl> TEST ( LayoutDescriptorBasicFast ) { <nl> <nl> CHECK ( ! layout_desc - > IsSlowLayout ( ) ) ; <nl> CHECK ( layout_desc - > IsFastPointerLayout ( ) ) ; <nl> - CHECK_EQ ( kSmiValueSize , layout_desc - > capacity ( ) ) ; <nl> + CHECK_EQ ( kBitsInSmiLayout , layout_desc - > capacity ( ) ) ; <nl> <nl> - for ( int i = 0 ; i < kSmiValueSize + 13 ; i + + ) { <nl> + for ( int i = 0 ; i < kBitsInSmiLayout + 13 ; i + + ) { <nl> CHECK ( layout_desc - > IsTagged ( i ) ) ; <nl> } <nl> CHECK ( layout_desc - > IsTagged ( - 1 ) ) ; <nl> TEST ( LayoutDescriptorBasicFast ) { <nl> CHECK ( layout_desc - > IsTagged ( 15635 ) ) ; <nl> CHECK ( layout_desc - > IsFastPointerLayout ( ) ) ; <nl> <nl> - for ( int i = 0 ; i < kSmiValueSize ; i + + ) { <nl> + for ( int i = 0 ; i < kBitsInSmiLayout ; i + + ) { <nl> layout_desc = layout_desc - > SetTaggedForTesting ( i , false ) ; <nl> CHECK ( ! layout_desc - > IsTagged ( i ) ) ; <nl> layout_desc = layout_desc - > SetTaggedForTesting ( i , true ) ; <nl> TEST ( LayoutDescriptorBasicSlow ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> / / All properties tagged . <nl> TEST ( LayoutDescriptorBasicSlow ) { <nl> <nl> layout_descriptor = LayoutDescriptor : : New ( map , descriptors , kPropsCount ) ; <nl> CHECK_EQ ( LayoutDescriptor : : FastPointerLayout ( ) , * layout_descriptor ) ; <nl> - CHECK_EQ ( kSmiValueSize , layout_descriptor - > capacity ( ) ) ; <nl> + CHECK_EQ ( kBitsInSmiLayout , layout_descriptor - > capacity ( ) ) ; <nl> InitializeVerifiedMapDescriptors ( * map , * descriptors , * layout_descriptor ) ; <nl> } <nl> <nl> TEST ( LayoutDescriptorBasicSlow ) { <nl> CHECK_NE ( LayoutDescriptor : : FastPointerLayout ( ) , * layout_descriptor ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> CHECK ( ! layout_descriptor - > IsFastPointerLayout ( ) ) ; <nl> - CHECK_GT ( layout_descriptor - > capacity ( ) , kSmiValueSize ) ; <nl> + CHECK_GT ( layout_descriptor - > capacity ( ) , kBitsInSmiLayout ) ; <nl> <nl> CHECK ( ! layout_descriptor - > IsTagged ( 0 ) ) ; <nl> CHECK ( ! layout_descriptor - > IsTagged ( kPropsCount - 1 ) ) ; <nl> static void TestLayoutDescriptorQueriesFast ( int max_sequence_length ) { <nl> <nl> { <nl> int bit_flip_positions [ ] = { 1000 } ; <nl> - TestLayoutDescriptorQueries ( kSmiValueSize , bit_flip_positions , <nl> + TestLayoutDescriptorQueries ( kBitsInSmiLayout , bit_flip_positions , <nl> max_sequence_length ) ; <nl> } <nl> <nl> { <nl> int bit_flip_positions [ ] = { 0 , 1000 } ; <nl> - TestLayoutDescriptorQueries ( kSmiValueSize , bit_flip_positions , <nl> + TestLayoutDescriptorQueries ( kBitsInSmiLayout , bit_flip_positions , <nl> max_sequence_length ) ; <nl> } <nl> <nl> static void TestLayoutDescriptorQueriesFast ( int max_sequence_length ) { <nl> for ( int i = 0 ; i < = kNumberOfBits ; i + + ) { <nl> bit_flip_positions [ i ] = i ; <nl> } <nl> - TestLayoutDescriptorQueries ( kSmiValueSize , bit_flip_positions , <nl> + TestLayoutDescriptorQueries ( kBitsInSmiLayout , bit_flip_positions , <nl> max_sequence_length ) ; <nl> } <nl> <nl> { <nl> int bit_flip_positions [ ] = { 3 , 7 , 8 , 10 , 15 , 21 , 30 , 1000 } ; <nl> - TestLayoutDescriptorQueries ( kSmiValueSize , bit_flip_positions , <nl> + TestLayoutDescriptorQueries ( kBitsInSmiLayout , bit_flip_positions , <nl> max_sequence_length ) ; <nl> } <nl> <nl> { <nl> int bit_flip_positions [ ] = { 0 , 1 , 2 , 3 , 5 , 7 , 9 , <nl> 12 , 15 , 18 , 22 , 26 , 29 , 1000 } ; <nl> - TestLayoutDescriptorQueries ( kSmiValueSize , bit_flip_positions , <nl> + TestLayoutDescriptorQueries ( kBitsInSmiLayout , bit_flip_positions , <nl> max_sequence_length ) ; <nl> } <nl> } <nl> TEST ( LayoutDescriptorCreateNewSlow ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = static_cast < TestPropertyKind > ( i % PROP_KIND_NUMBER ) ; <nl> TEST ( LayoutDescriptorAppend ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = static_cast < TestPropertyKind > ( i % PROP_KIND_NUMBER ) ; <nl> TEST ( LayoutDescriptorAppend ) { <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = <nl> - TestLayoutDescriptorAppend ( isolate , kSmiValueSize , props , kPropsCount ) ; <nl> + TestLayoutDescriptorAppend ( isolate , kBitsInSmiLayout , props , kPropsCount ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> - layout_descriptor = TestLayoutDescriptorAppend ( isolate , kSmiValueSize * 2 , <nl> + layout_descriptor = TestLayoutDescriptorAppend ( isolate , kBitsInSmiLayout * 2 , <nl> props , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> TEST ( LayoutDescriptorAppendAllDoubles ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = PROP_DOUBLE ; <nl> TEST ( LayoutDescriptorAppendAllDoubles ) { <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = <nl> - TestLayoutDescriptorAppend ( isolate , kSmiValueSize , props , kPropsCount ) ; <nl> + TestLayoutDescriptorAppend ( isolate , kBitsInSmiLayout , props , kPropsCount ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> - layout_descriptor = TestLayoutDescriptorAppend ( isolate , kSmiValueSize + 1 , <nl> + layout_descriptor = TestLayoutDescriptorAppend ( isolate , kBitsInSmiLayout + 1 , <nl> props , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> - layout_descriptor = TestLayoutDescriptorAppend ( isolate , kSmiValueSize * 2 , <nl> + layout_descriptor = TestLayoutDescriptorAppend ( isolate , kBitsInSmiLayout * 2 , <nl> props , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> TEST ( LayoutDescriptorAppendAllDoubles ) { <nl> <nl> { <nl> / / Ensure layout descriptor switches into slow mode at the right moment . <nl> - layout_descriptor = <nl> - TestLayoutDescriptorAppend ( isolate , kPropsCount , props , kSmiValueSize ) ; <nl> + layout_descriptor = TestLayoutDescriptorAppend ( isolate , kPropsCount , props , <nl> + kBitsInSmiLayout ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppend ( isolate , kPropsCount , props , <nl> - kSmiValueSize + 1 ) ; <nl> + kBitsInSmiLayout + 1 ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> } <nl> } <nl> TEST ( LayoutDescriptorAppendIfFastOrUseFull ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = static_cast < TestPropertyKind > ( i % PROP_KIND_NUMBER ) ; <nl> TEST ( LayoutDescriptorAppendIfFastOrUseFull ) { <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kSmiValueSize , descriptors , kPropsCount ) ; <nl> + isolate , kBitsInSmiLayout , descriptors , kPropsCount ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kSmiValueSize * 2 , descriptors , kPropsCount ) ; <nl> + isolate , kBitsInSmiLayout * 2 , descriptors , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> TEST ( LayoutDescriptorAppendIfFastOrUseFullAllDoubles ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = PROP_DOUBLE ; <nl> TEST ( LayoutDescriptorAppendIfFastOrUseFullAllDoubles ) { <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kSmiValueSize , descriptors , kPropsCount ) ; <nl> + isolate , kBitsInSmiLayout , descriptors , kPropsCount ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kSmiValueSize + 1 , descriptors , kPropsCount ) ; <nl> + isolate , kBitsInSmiLayout + 1 , descriptors , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kSmiValueSize * 2 , descriptors , kPropsCount ) ; <nl> + isolate , kBitsInSmiLayout * 2 , descriptors , kPropsCount ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> TEST ( LayoutDescriptorAppendIfFastOrUseFullAllDoubles ) { <nl> { <nl> / / Ensure layout descriptor switches into slow mode at the right moment . <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kPropsCount , descriptors , kSmiValueSize ) ; <nl> + isolate , kPropsCount , descriptors , kBitsInSmiLayout ) ; <nl> CHECK ( ! layout_descriptor - > IsSlowLayout ( ) ) ; <nl> <nl> layout_descriptor = TestLayoutDescriptorAppendIfFastOrUseFull ( <nl> - isolate , kPropsCount , descriptors , kSmiValueSize + 1 ) ; <nl> + isolate , kPropsCount , descriptors , kBitsInSmiLayout + 1 ) ; <nl> CHECK ( layout_descriptor - > IsSlowLayout ( ) ) ; <nl> } <nl> } <nl> TEST ( Regress436816 ) { <nl> / / mid - test states would fail heap verification . <nl> CcTest : : CollectAllGarbage ( ) ; <nl> <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = PROP_DOUBLE ; <nl> TEST ( LayoutDescriptorHelperMixed ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = static_cast < TestPropertyKind > ( i % PROP_KIND_NUMBER ) ; <nl> TEST ( LayoutDescriptorHelperMixed ) { <nl> <nl> TestLayoutDescriptorHelper ( isolate , 13 , descriptors , kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize , descriptors , kPropsCount ) ; <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout , descriptors , <nl> + kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize * 2 , descriptors , <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout * 2 , descriptors , <nl> kPropsCount ) ; <nl> <nl> TestLayoutDescriptorHelper ( isolate , kPropsCount , descriptors , kPropsCount ) ; <nl> TEST ( LayoutDescriptorHelperAllTagged ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = PROP_TAGGED ; <nl> TEST ( LayoutDescriptorHelperAllTagged ) { <nl> <nl> TestLayoutDescriptorHelper ( isolate , 13 , descriptors , kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize , descriptors , kPropsCount ) ; <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout , descriptors , <nl> + kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize * 2 , descriptors , <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout * 2 , descriptors , <nl> kPropsCount ) ; <nl> <nl> TestLayoutDescriptorHelper ( isolate , kPropsCount , descriptors , kPropsCount ) ; <nl> TEST ( LayoutDescriptorHelperAllDoubles ) { <nl> v8 : : HandleScope scope ( CcTest : : isolate ( ) ) ; <nl> <nl> Handle < LayoutDescriptor > layout_descriptor ; <nl> - const int kPropsCount = kSmiValueSize * 3 ; <nl> + const int kPropsCount = kBitsInSmiLayout * 3 ; <nl> TestPropertyKind props [ kPropsCount ] ; <nl> for ( int i = 0 ; i < kPropsCount ; i + + ) { <nl> props [ i ] = PROP_DOUBLE ; <nl> TEST ( LayoutDescriptorHelperAllDoubles ) { <nl> <nl> TestLayoutDescriptorHelper ( isolate , 13 , descriptors , kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize , descriptors , kPropsCount ) ; <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout , descriptors , <nl> + kPropsCount ) ; <nl> <nl> - TestLayoutDescriptorHelper ( isolate , kSmiValueSize * 2 , descriptors , <nl> + TestLayoutDescriptorHelper ( isolate , kBitsInSmiLayout * 2 , descriptors , <nl> kPropsCount ) ; <nl> <nl> TestLayoutDescriptorHelper ( isolate , kPropsCount , descriptors , kPropsCount ) ; <nl> mmm a / test / cctest / trace - extension . cc <nl> ppp b / test / cctest / trace - extension . cc <nl> Address TraceExtension : : GetFP ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> # if defined ( V8_HOST_ARCH_32_BIT ) <nl> Address fp = * reinterpret_cast < Address * > ( * args [ 0 ] ) ; <nl> # elif defined ( V8_HOST_ARCH_64_BIT ) <nl> - int64_t low_bits = * reinterpret_cast < uint64_t * > ( * args [ 0 ] ) > > 32 ; <nl> - int64_t high_bits = * reinterpret_cast < uint64_t * > ( * args [ 1 ] ) ; <nl> - Address fp = static_cast < Address > ( high_bits | low_bits ) ; <nl> + uint64_t kSmiValueMask = <nl> + ( static_cast < uintptr_t > ( 1 ) < < ( kSmiValueSize - 1 ) ) - 1 ; <nl> + uint64_t low_bits = <nl> + ( * reinterpret_cast < Smi * * > ( * args [ 0 ] ) ) - > value ( ) & kSmiValueMask ; <nl> + uint64_t high_bits = <nl> + ( * reinterpret_cast < Smi * * > ( * args [ 1 ] ) ) - > value ( ) & kSmiValueMask ; <nl> + Address fp = <nl> + static_cast < Address > ( ( high_bits < < ( kSmiValueSize - 1 ) ) | low_bits ) ; <nl> # else <nl> # error Host architecture is neither 32 - bit nor 64 - bit . <nl> # endif <nl>
[ ptr - compr ] Support 31 - bit Smis in lower half - word on 64 - bit architectures .
v8/v8
d123f30b6df5507b2acda8e85ad63e05de8ca8a7
2018-06-05T11:37:35Z
mmm a / include / swift / AST / DiagnosticsParse . def <nl> ppp b / include / swift / AST / DiagnosticsParse . def <nl> ERROR ( attr_specialize_unknown_parameter_name , none , <nl> ERROR ( attr_specialize_expected_bool_value , none , <nl> " expected a boolean true or false value in ' _specialize ' attribute " , ( ) ) <nl> <nl> - WARNING ( attr_specialize_export_true_no_op , none , <nl> - " ' exported : true ' has no effect in ' _specialize ' attribute " , ( ) ) <nl> - <nl> ERROR ( attr_specialize_missing_parameter_label_or_where_clause , none , <nl> " expected a parameter label or a where clause in ' _specialize ' attribute " , ( ) ) <nl> <nl> mmm a / lib / Parse / ParseDecl . cpp <nl> ppp b / lib / Parse / ParseDecl . cpp <nl> bool Parser : : parseSpecializeAttributeArguments ( <nl> ParamLabel ) ; <nl> } <nl> if ( ParamLabel = = " exported " ) { <nl> - auto trueLoc = Tok . getLoc ( ) ; <nl> bool isTrue = consumeIf ( tok : : kw_true ) ; <nl> bool isFalse = consumeIf ( tok : : kw_false ) ; <nl> if ( ! isTrue & & ! isFalse ) { <nl>
Merge remote - tracking branch ' origin / main ' into next
apple/swift
db771fcd7ae1d2bcc183fd9d531cbf00164e1a0b
2020-10-29T22:15:34Z
mmm a / src / training / tesstrain . sh <nl> ppp b / src / training / tesstrain . sh <nl> else <nl> phase_D_generate_dawg <nl> phase_E_extract_features " box . train " 8 " tr " <nl> phase_C_cluster_prototypes " $ { TRAINING_DIR } / $ { LANG_CODE } . normproto " <nl> - if [ [ " $ { ENABLE_SHAPE_CLUSTERING } " = = " y " ] ] ; then <nl> - phase_S_cluster_shapes <nl> - fi <nl> + phase_S_cluster_shapes <nl> phase_M_cluster_microfeatures <nl> phase_B_generate_ambiguities <nl> make__traineddata <nl>
Merge pull request from diegodlh / shape_clustering_flag
tesseract-ocr/tesseract
093efcde0fc4fb28ecba7d1574621b6832bc2dc3
2019-01-24T06:54:48Z
mmm a / xbmc / interfaces / json - rpc / FavouritesOperations . cpp <nl> ppp b / xbmc / interfaces / json - rpc / FavouritesOperations . cpp <nl> <nl> # include " FavouritesOperations . h " <nl> # include " favourites / FavouritesService . h " <nl> # include " input / WindowTranslator . h " <nl> + # include " URL . h " <nl> # include " utils / StringUtils . h " <nl> # include " Util . h " <nl> # include " utils / URIUtils . h " <nl> JSONRPC_STATUS CFavouritesOperations : : GetFavourites ( const std : : string & method , I <nl> <nl> std : : string function ; <nl> std : : vector < std : : string > parameters ; <nl> - CUtil : : SplitExecFunction ( item - > GetPath ( ) , function , parameters ) ; <nl> + <nl> + / / FIXME : this path is internal to the favourites system and should not be parsed and exposed <nl> + CURL url ( item - > GetPath ( ) ) ; <nl> + std : : string internalPath = CURL : : Decode ( url . GetHostName ( ) ) ; <nl> + <nl> + CUtil : : SplitExecFunction ( internalPath , function , parameters ) ; <nl> if ( parameters . empty ( ) ) <nl> continue ; <nl> <nl> mmm a / xbmc / interfaces / json - rpc / schema / version . txt <nl> ppp b / xbmc / interfaces / json - rpc / schema / version . txt <nl> @ @ - 1 + 1 @ @ <nl> - JSONRPC_VERSION 9 . 1 . 0 <nl> + JSONRPC_VERSION 9 . 1 . 1 <nl>
[ jsonrpc ] fix GetFavourites after dd29b3e
xbmc/xbmc
e981a6aed305c6886cff57d1f4ba2a9ab0794ffc
2018-02-03T09:44:08Z
mmm a / src / preferences / options . ui <nl> ppp b / src / preferences / options . ui <nl> <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl> QGroupBox { <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl> QGroupBox { <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl> QGroupBox { <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl> QGroupBox { <nl> < property name = " geometry " > <nl> < rect > <nl> < x > 0 < / x > <nl> - < y > 0 < / y > <nl> + < y > - 51 < / y > <nl> < width > 507 < / width > <nl> < height > 457 < / height > <nl> < / rect > <nl> QGroupBox { <nl> < property name = " geometry " > <nl> < rect > <nl> < x > 0 < / x > <nl> - < y > 0 < / y > <nl> + < y > - 25 < / y > <nl> < width > 570 < / width > <nl> < height > 422 < / height > <nl> < / rect > <nl> QGroupBox { <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl> QGroupBox { <nl> < property name = " styleSheet " > <nl> < string notr = " true " > QGroupBox : : title { <nl> font - weight : normal ; <nl> - margin - left : 10px ; <nl> + margin - left : 0px ; <nl> margin - top : 5px ; <nl> } <nl> QGroupBox { <nl>
Fix some alignment issues in program preferences ( Thanks charles )
qbittorrent/qBittorrent
8d699dc1775c7fde2bdf4a0ad072f5b790310e4e
2010-12-09T17:17:26Z
mmm a / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> <nl> # include < Parsers / ASTIdentifier . h > <nl> # include < Parsers / ASTNameTypePair . h > <nl> # include < Parsers / ExpressionListParsers . h > <nl> + # include < Parsers / parseQuery . h > <nl> # include < DataStreams / ExpressionBlockInputStream . h > <nl> # include < DataStreams / copyData . h > <nl> # include < IO / WriteBufferFromFile . h > <nl> void MergeTreeData : : initPrimaryKey ( ) <nl> void MergeTreeData : : initPartitionKey ( ) <nl> { <nl> String partition_expr_str = " toYYYYMM ( " + date_column_name + " ) " ; <nl> - Tokens tokens ( partition_expr_str . data ( ) , partition_expr_str . data ( ) + partition_expr_str . size ( ) ) ; <nl> ParserNotEmptyExpressionList parser ( / * allow_alias_without_as_keyword = * / false ) ; <nl> - TokenIterator token_it ( tokens ) ; <nl> - Expected expected ; <nl> - bool parsed = parser . parse ( token_it , partition_expr_ast , expected ) ; <nl> - if ( ! parsed | | ! token_it - > isEnd ( ) ) <nl> - throw Exception ( " Can ' t parse partition expression : ` " + partition_expr_str + " ` " , ErrorCodes : : SYNTAX_ERROR ) ; <nl> - <nl> + partition_expr_ast = parseQuery ( <nl> + parser , partition_expr_str . data ( ) , partition_expr_str . data ( ) + partition_expr_str . length ( ) , " partition expression " ) ; <nl> partition_expr = ExpressionAnalyzer ( partition_expr_ast , context , nullptr , getColumnsList ( ) ) . getActions ( false ) ; <nl> for ( const ASTPtr & ast : partition_expr_ast - > children ) <nl> partition_expr_columns . emplace_back ( ast - > getColumnName ( ) ) ; <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataPart . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataPart . cpp <nl> void MinMaxIndex : : update ( const Block & block , const Names & column_names ) <nl> { <nl> if ( ! initialized ) <nl> { <nl> - min_column_values . resize ( column_names . size ( ) , / * dont_init_elems = * / true ) ; <nl> - max_column_values . resize ( column_names . size ( ) , / * dont_init_elems = * / true ) ; <nl> + min_column_values . resize ( column_names . size ( ) ) ; <nl> + max_column_values . resize ( column_names . size ( ) ) ; <nl> } <nl> <nl> for ( size_t i = 0 ; i < column_names . size ( ) ; + + i ) <nl> void MinMaxIndex : : update ( const Block & block , const Names & column_names ) <nl> <nl> if ( ! initialized ) <nl> { <nl> - new ( min_column_values . place ( i ) ) Field ( min_value ) ; <nl> - new ( max_column_values . place ( i ) ) Field ( max_value ) ; <nl> + min_column_values [ i ] = Field ( min_value ) ; <nl> + max_column_values [ i ] = Field ( max_value ) ; <nl> } <nl> else <nl> { <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataPart . h <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataPart . h <nl> struct MergeTreeDataPartChecksums <nl> } ; <nl> <nl> <nl> + / / / Index that for each part stores min and max values of a set of columns . This allows quickly excluding <nl> + / / / parts based on conditions on these columns imposed by a query . <nl> + / / / Currently this index is built using only columns required by partition expression , but in principle it <nl> + / / / can be built using any set of columns . <nl> struct MinMaxIndex <nl> { <nl> void update ( const Block & block , const Names & column_names ) ; <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataWriter . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataWriter . cpp <nl> namespace <nl> <nl> void buildScatterSelector ( <nl> const ConstColumnPlainPtrs & columns , <nl> - PODArray < size_t > & partitions_rows , <nl> + PODArray < size_t > & partition_num_to_first_row , <nl> IColumn : : Selector & selector ) <nl> { <nl> - / / / Use generic hashed variant since partitioning is unlikely to be a bottleneck <nl> + / / / Use generic hashed variant since partitioning is unlikely to be a bottleneck . <nl> using Data = HashMap < UInt128 , size_t , UInt128TrivialHash > ; <nl> Data partitions_map ; <nl> <nl> void buildScatterSelector ( <nl> <nl> if ( inserted ) <nl> { <nl> - partitions_rows . push_back ( i ) ; <nl> + partition_num_to_first_row . push_back ( i ) ; <nl> it - > second = partitions_count ; <nl> <nl> + + partitions_count ; <nl> BlocksWithPartition MergeTreeDataWriter : : splitBlockIntoParts ( const Block & block <nl> for ( const String & name : data . partition_expr_columns ) <nl> partition_columns . emplace_back ( block_copy . getByName ( name ) . column . get ( ) ) ; <nl> <nl> - PODArray < size_t > partitions_rows ; <nl> + PODArray < size_t > partition_num_to_first_row ; <nl> IColumn : : Selector selector ; <nl> - buildScatterSelector ( partition_columns , partitions_rows , selector ) ; <nl> + buildScatterSelector ( partition_columns , partition_num_to_first_row , selector ) ; <nl> <nl> - size_t partitions_count = partitions_rows . size ( ) ; <nl> + size_t partitions_count = partition_num_to_first_row . size ( ) ; <nl> result . reserve ( partitions_count ) ; <nl> <nl> auto get_partition = [ & ] ( size_t num ) <nl> { <nl> - Row partition ( partition_columns . size ( ) , DontInitElemsTag { } ) ; <nl> + Row partition ( partition_columns . size ( ) ) ; <nl> for ( size_t i = 0 ; i < partition_columns . size ( ) ; + + i ) <nl> - new ( partition . place ( i ) ) Field ( ( * partition_columns [ i ] ) [ partitions_rows [ num ] ] ) ; <nl> + partition [ i ] = Field ( ( * partition_columns [ i ] ) [ partition_num_to_first_row [ num ] ] ) ; <nl> return partition ; <nl> } ; <nl> <nl> mmm a / dbms / src / Storages / StorageReplicatedMergeTree . cpp <nl> ppp b / dbms / src / Storages / StorageReplicatedMergeTree . cpp <nl> bool StorageReplicatedMergeTree : : executeLogEntry ( const LogEntry & entry ) <nl> / / / Logging <nl> Stopwatch stopwatch ; <nl> <nl> - MergeTreeDataMerger : : FuturePart future_part ( parts ) ; <nl> - if ( future_part . name ! = entry . new_part_name ) <nl> + MergeTreeDataMerger : : FuturePart future_merged_part ( parts ) ; <nl> + if ( future_merged_part . name ! = entry . new_part_name ) <nl> throw Exception ( <nl> - " Future merged part name ` " + future_part . name + " ` differs from part name in log entry : ` " + entry . new_part_name + " ` " , <nl> + " Future merged part name ` " + future_merged_part . name + <nl> + " ` differs from part name in log entry : ` " + entry . new_part_name + " ` " , <nl> ErrorCodes : : BAD_DATA_PART_NAME ) ; <nl> <nl> auto part = merger . mergePartsToTemporaryPart ( <nl> - future_part , * merge_entry , aio_threshold , entry . create_time , reserved_space . get ( ) , entry . deduplicate ) ; <nl> + future_merged_part , * merge_entry , aio_threshold , entry . create_time , reserved_space . get ( ) , entry . deduplicate ) ; <nl> <nl> zkutil : : Ops ops ; <nl> <nl> void StorageReplicatedMergeTree : : mergeSelectingThread ( ) <nl> } <nl> else <nl> { <nl> - MergeTreeDataMerger : : FuturePart future_part ; <nl> + MergeTreeDataMerger : : FuturePart future_merged_part ; <nl> <nl> size_t max_parts_size_for_merge = merger . getMaxPartsSizeForMerge ( data . settings . max_replicated_merges_in_queue , merges_queued ) ; <nl> <nl> void StorageReplicatedMergeTree : : mergeSelectingThread ( ) <nl> <nl> if ( max_parts_size_for_merge > 0 <nl> & & merger . selectPartsToMerge ( <nl> - future_part , false , <nl> + future_merged_part , false , <nl> max_parts_size_for_merge , <nl> can_merge ) <nl> - & & createLogEntryToMergeParts ( future_part . parts , future_part . name , deduplicate ) ) <nl> + & & createLogEntryToMergeParts ( future_merged_part . parts , future_merged_part . name , deduplicate ) ) <nl> { <nl> success = true ; <nl> need_pull = true ; <nl> bool StorageReplicatedMergeTree : : optimize ( const ASTPtr & query , const String & p <nl> <nl> size_t disk_space = DiskSpaceMonitor : : getUnreservedFreeSpace ( full_path ) ; <nl> <nl> - MergeTreeDataMerger : : FuturePart future_part ; <nl> + MergeTreeDataMerger : : FuturePart future_merged_part ; <nl> bool selected = false ; <nl> <nl> if ( partition_id . empty ( ) ) <nl> { <nl> - selected = merger . selectPartsToMerge ( future_part , false , data . settings . max_bytes_to_merge_at_max_space_in_pool , can_merge ) ; <nl> + selected = merger . selectPartsToMerge ( <nl> + future_merged_part , false , data . settings . max_bytes_to_merge_at_max_space_in_pool , can_merge ) ; <nl> } <nl> else <nl> { <nl> - selected = merger . selectAllPartsToMergeWithinPartition ( future_part , disk_space , can_merge , partition_id , final ) ; <nl> + selected = merger . selectAllPartsToMergeWithinPartition ( future_merged_part , disk_space , can_merge , partition_id , final ) ; <nl> } <nl> <nl> if ( ! selected ) <nl> return false ; <nl> <nl> - if ( ! createLogEntryToMergeParts ( future_part . parts , future_part . name , deduplicate , & merge_entry ) ) <nl> + if ( ! createLogEntryToMergeParts ( future_merged_part . parts , future_merged_part . name , deduplicate , & merge_entry ) ) <nl> return false ; <nl> } <nl> <nl>
PR fixes [ # CLICKHOUSE - 3000 ]
ClickHouse/ClickHouse
d2847f22af32aa25911dbc74c53724735c682340
2017-08-31T20:32:03Z
mmm a / tensorflow / python / eager / ops_test . py <nl> ppp b / tensorflow / python / eager / ops_test . py <nl> def testComposition ( self ) : <nl> self . assertAllEqual ( 3 , three_x ) <nl> <nl> def testOperatorOverrides ( self ) : <nl> - def _testOperations ( v1 , v2 ) : <nl> + def ops_test ( v1 , v2 ) : <nl> a = constant_op . constant ( v1 ) <nl> b = constant_op . constant ( v2 ) <nl> <nl> def _testOperations ( v1 , v2 ) : <nl> self . assertAllEqual ( ( a ! = b ) , np . not_equal ( v1 , v2 ) [ 0 ] ) <nl> self . assertAllEqual ( v1 [ 0 ] , a [ constant_op . constant ( 0 ) ] ) <nl> <nl> - _testOperations ( [ 1 , 4 , 8 ] , [ 2 , 3 , 5 ] ) <nl> - _testOperations ( [ 1 , - 4 , - 5 ] , [ - 2 , 3 , - 6 ] ) <nl> + ops_test ( [ 1 , 4 , 8 ] , [ 2 , 3 , 5 ] ) <nl> + ops_test ( [ 1 , - 4 , - 5 ] , [ - 2 , 3 , - 6 ] ) <nl> <nl> def test_basic_slice ( self ) : <nl> npt = np . arange ( 1 , 19 , dtype = np . float32 ) . reshape ( 3 , 2 , 3 ) <nl>
Name corrected to snake_case
tensorflow/tensorflow
2cd7ce59b4de68708946d080a8111c848c2ec6ad
2019-04-02T18:03:06Z
mmm a / src / common / profiler . cpp <nl> ppp b / src / common / profiler . cpp <nl> void TimingResultsAggregator : : AddFrame ( const ProfilingFrameResult & frame_result ) <nl> static AggregatedDuration AggregateField ( const std : : vector < Duration > & v , size_t len ) { <nl> AggregatedDuration result ; <nl> result . avg = Duration : : zero ( ) ; <nl> - <nl> result . min = result . max = ( len = = 0 ? Duration : : zero ( ) : v [ 0 ] ) ; <nl> <nl> - for ( size_t i = 1 ; i < len ; + + i ) { <nl> + for ( size_t i = 0 ; i < len ; + + i ) { <nl> Duration value = v [ i ] ; <nl> result . avg + = value ; <nl> result . min = std : : min ( result . min , value ) ; <nl>
Profiler : Fix off - by - one error when computing average .
yuzu-emu/yuzu
ed12b08e7aa006817265bfe076bd101bcefd455a
2015-05-07T22:48:31Z
new file mode 100644 <nl> index 00000000 . . c90e049f <nl> mmm / dev / null <nl> ppp b / ISSUE_TEMPLATE / compatibility_template . md <nl> <nl> + # Compatibility Report <nl> + - Name of the game with compatibility issues : <nl> + - Steam AppID of the game : <nl> + <nl> + # # System Information <nl> + - Driver - / ( LLVM - ) / kernel - version / GPU : < ! - - e . g . Mesa 18 . 2 / 7 . 0 . 0 / 4 . 17 / RX 580 - - > <nl> + - Link to full system information report as [ Gist ] ( https : / / gist . github . com / ) : <nl> + - Proton version : <nl> + <nl> + # # I confirm : <nl> + - [ ] that I haven ' t found an existing compatibility report for this game . <nl> + - [ ] that I have checked whether there are updates for my system available . <nl> + <nl> + < ! - - Please add ` PROTON_LOG = 1 % command % ` to the game ' s launch options and drag <nl> + and drop the generated ` $ HOME / steam - $ APPID . log ` into this issue report - - > <nl> + <nl> + # # Symptoms < ! - - What ' s the problem ? - - > <nl> + <nl> + <nl> + # # Reproduction <nl> + <nl> + <nl> + < ! - - <nl> + 1 . You can find the Steam AppID in the URL of the shop page of the game . <nl> + e . g . for ` The Witcher 3 : Wild Hunt ` the AppID is ` 292030 ` . <nl> + 2 . You can find your driver and Linux version , as well as your graphics <nl> + processor ' s name in the system information report of Steam . <nl> + 3 . You can retrieve a full system information report by clicking <nl> + ` Help ` > ` System Information ` in the Steam client on your machine . <nl> + 4 . Please copy it to your clipboard by pressing ` Ctrl + A ` and then ` Ctrl + C ` . <nl> + Then paste it in a [ Gist ] ( https : / / gist . github . com / ) and post the link in <nl> + this issue to prevent chaos by too much info in one place . <nl> + 5 . Please search for open issues and pull requests by the name of the game and <nl> + find out whether they are relevant and should be referenced above . <nl> + - - > <nl>
Add template for compatibility issues
ValveSoftware/Proton
37a1e5819e44fe0474b566a05f17d0d4c9d3b231
2018-09-06T19:22:36Z
mmm a / docs / tutorials / index . md <nl> ppp b / docs / tutorials / index . md <nl> Select API : & nbsp ; <nl> * [ MXNet - Scala Examples ] ( https : / / github . com / apache / incubator - mxnet / tree / master / scala - package / examples / src / main / scala / org / apache / mxnetexamples ) <nl> < hr > <nl> <nl> + # # Java Tutorials <nl> + * Getting Started <nl> + * [ Developer Environment Setup on IntelliJ IDE ] ( / tutorials / java / mxnet_java_on_intellij . html ) <nl> + * [ MXNet - Java Examples ] ( https : / / github . com / apache / incubator - mxnet / tree / master / scala - package / examples / src / main / java / org / apache / mxnetexamples ) <nl> + < hr > <nl> + <nl> # # C + + Tutorials <nl> <nl> * Models <nl> new file mode 100644 <nl> index 00000000000 . . b90a92b0a7b <nl> mmm / dev / null <nl> ppp b / docs / tutorials / java / mxnet_java_on_intellij . md <nl> <nl> + # Run MXNet Java Examples Using the IntelliJ IDE ( macOS ) <nl> + <nl> + This tutorial guides you through setting up a simple Java project in IntelliJ IDE on macOS and demonstrates usage of the MXNet Java APIs . <nl> + <nl> + # # Prerequisites : <nl> + To use this tutorial you need the following pre - requisites : <nl> + <nl> + - [ Java 8 JDK ] ( http : / / www . oracle . com / technetwork / java / javase / downloads / index . html ) <nl> + - [ Maven ] ( https : / / maven . apache . org / install . html ) <nl> + - [ OpenCV ] ( https : / / opencv . org / ) <nl> + - [ IntelliJ IDEA ] ( https : / / www . jetbrains . com / idea / ) ( One can download the community edition from [ here ] ( https : / / www . jetbrains . com / idea / download ) ) <nl> + <nl> + # # # MacOS Prerequisites <nl> + <nl> + * * Step 1 . * * Install brew : <nl> + ` ` ` <nl> + / usr / bin / ruby - e " $ ( curl - fsSL https : / / raw . githubusercontent . com / Homebrew / install / master / install ) " <nl> + ` ` ` <nl> + <nl> + Or , if you already have brew , update it : <nl> + ` ` ` <nl> + brew update <nl> + ` ` ` <nl> + <nl> + * * Step 2 . * * Install Java 8 : <nl> + ` ` ` <nl> + brew tap caskroom / versions <nl> + brew cask install java8 <nl> + ` ` ` <nl> + <nl> + * * Step 3 . * * Install maven : <nl> + ` ` ` <nl> + brew install maven <nl> + ` ` ` <nl> + <nl> + * * Step 4 . * * Install OpenCV : <nl> + ` ` ` <nl> + brew install opencv <nl> + ` ` ` <nl> + <nl> + You can also run this tutorial on an Ubuntu machine after installing the following prerequisites . <nl> + # # # Ubuntu Prerequisites <nl> + <nl> + * * Step 1 . * * Download the MXNet source . <nl> + <nl> + ` ` ` bash <nl> + git clone - - recursive https : / / github . com / apache / incubator - mxnet . git mxnet <nl> + cd mxnet <nl> + ` ` ` <nl> + <nl> + * * Step 2 . * * Run the dependency installation scripts . <nl> + <nl> + ` ` ` bash <nl> + sudo . / ci / docker / install / ubuntu_core . sh <nl> + sudo . / ci / docker / install / ubuntu_scala . sh <nl> + ` ` ` <nl> + <nl> + The ` ubuntu_scala . sh ` installs the common dependencies required for both MXNet Scala and MXNet Java packages . <nl> + <nl> + # # Set Up Your Project <nl> + <nl> + * * Step 1 . * * Install and setup [ IntelliJ IDEA ] ( https : / / www . jetbrains . com / idea / ) <nl> + <nl> + * * Step 2 . * * Create a new Project : <nl> + <nl> + ! [ intellij welcome ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / scala / intellij - welcome . png ) <nl> + <nl> + From the IntelliJ welcome screen , select " Create New Project " . <nl> + <nl> + Choose the Maven project type . <nl> + <nl> + Select the checkbox for ` Create from archetype ` , then choose ` org . apache . maven . archetypes : maven - archetype - quickstart ` from the list below . More on this can be found on a Maven tutorial : [ Maven in 5 Minutes ] ( https : / / maven . apache . org / guides / getting - started / maven - in - five - minutes . html ) . <nl> + <nl> + ! [ maven project type - archetype ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / project - archetype . png ) <nl> + <nl> + click ` Next ` . <nl> + <nl> + ! [ project metadata ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / intellij - project - metadata . png ) <nl> + <nl> + Set the project ' s metadata . For this tutorial , use the following : <nl> + <nl> + * * GroupId * * <nl> + ` ` ` <nl> + mxnet <nl> + ` ` ` <nl> + * * ArtifactId * * <nl> + ` ` ` <nl> + ArtifactId : javaMXNet <nl> + ` ` ` <nl> + * * Version * * <nl> + ` ` ` <nl> + 1 . 0 - SNAPSHOT <nl> + ` ` ` <nl> + <nl> + TODO <nl> + ! [ project properties ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / intellij - project - properties . png ) <nl> + <nl> + Review the project ' s properties . The settings can be left as their default . <nl> + <nl> + TODO <nl> + ! [ project location ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / intellij - project - location . png ) <nl> + <nl> + Set the project ' s location . The rest of the settings can be left as their default . <nl> + <nl> + TODO <nl> + ! [ project 1 ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / intellij - project - pom . png ) <nl> + <nl> + After clicking Finish , you will be presented with the project ' s first view . <nl> + The project ' s ` pom . xml ` will be open for editing . <nl> + <nl> + * * Step 3 . * * Add the following Maven dependency to your ` pom . xml ` file under the ` dependencies ` tag : <nl> + <nl> + ` ` ` html <nl> + < dependency > <nl> + < groupId > org . apache . mxnet < / groupId > <nl> + < artifactId > mxnet - full_2 . 11 - osx - x86_64 - cpu < / artifactId > <nl> + < version > 1 . 4 . 0 < / version > <nl> + < / dependency > <nl> + ` ` ` <nl> + <nl> + To view the latest MXNet Maven packages , you can check [ MXNet Maven package repository ] ( https : / / search . maven . org / # search % 7Cga % 7C1 % 7Cg % 3A % 22org . apache . mxnet % 22 ) <nl> + <nl> + <nl> + * * Step 4 . * * Import dependencies with Maven : <nl> + <nl> + - Note the prompt in the lower right corner that states " Maven projects need to be imported " . If this is not visible , click on the little greed balloon that appears in the lower right corner . <nl> + <nl> + ! [ import_dependencies ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / project - import - changes . png ) <nl> + <nl> + Click " Import Changes " in this prompt . <nl> + <nl> + * * Step 5 . * * Build the project : <nl> + - To build the project , from the menu choose Build , and then choose Build Project . <nl> + <nl> + * * Step 6 . * * Navigate to the App . java class in the project and paste the following code , overwriting the original hello world code . <nl> + ` ` ` java <nl> + package mxnet ; <nl> + <nl> + import org . apache . mxnet . javaapi . Context ; <nl> + import org . apache . mxnet . javaapi . NDArray ; <nl> + <nl> + public class App <nl> + { <nl> + public static void main ( String [ ] args ) <nl> + { <nl> + NDArray nd = NDArray . ones ( Context . cpu ( ) , new int [ ] { 10 , 20 } ) ; <nl> + System . out . println ( " Testing MXNet by generating a 10x20 NDArray " ) ; <nl> + System . out . println ( " Shape of NDArray is : " + nd . shape ( ) ) ; <nl> + } <nl> + } <nl> + ` ` ` <nl> + <nl> + * * Step 7 . * * Now run the App . java by clicking the green arrow as highlighted in the image below . <nl> + <nl> + ! [ run hello mxnet ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / java / intellij - run - projects . png ) <nl> + <nl> + <nl> + The result should be this output : <nl> + <nl> + ` ` ` <nl> + Testing MXNet by generating a 10x20 NDArray <nl> + Shape of NDArray is : ( 10 , 20 ) <nl> + <nl> + Process finished with exit code 0 <nl> + ` ` ` <nl> + <nl> + <nl> + # # # Troubleshooting <nl> + <nl> + If you get an error , check the dependencies at the beginning of this tutorial . For example , you might see the following in the middle of the error messages , where ` x . x ` would the version it ' s looking for . <nl> + <nl> + ` ` ` <nl> + . . . <nl> + Library not loaded : / usr / local / opt / opencv / lib / libopencv_calib3d . x . x . dylib <nl> + . . . <nl> + ` ` ` <nl> + <nl> + This can be resolved be installing OpenCV . <nl> + <nl> + <nl> + # # # Command Line Build Option <nl> + <nl> + - You can also compile the project by using the following command at the command line . Change directories to this project ' s root folder then run the following : <nl> + <nl> + ` ` ` bash <nl> + mvn clean install dependency : copy - dependencies <nl> + ` ` ` <nl> + If the command succeeds , you should see a lot of info and some warning messages , followed by : <nl> + <nl> + ` ` ` bash <nl> + [ INFO ] mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + [ INFO ] BUILD SUCCESS <nl> + [ INFO ] mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + [ INFO ] Total time : 3 . 475 s <nl> + [ INFO ] Finished at : 2018 - 11 - 08T05 : 06 : 31 - 08 : 00 <nl> + [ INFO ] mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> + ` ` ` <nl> + The build generates a new jar file in the ` target ` folder called ` javaMXNet - 1 . 0 - SNAPSHOT . jar ` . <nl> + <nl> + To run the App . java use the following command from the project ' s root folder and you should see the same output as we got when the project was run from IntelliJ . <nl> + ` ` ` bash <nl> + java - cp target / javaMXNet - 1 . 0 - SNAPSHOT . jar : target / dependency / * mxnet . App <nl> + ` ` ` <nl> + <nl> + # # Next Steps <nl> + For more information about MXNet Java resources , see the following : <nl> + <nl> + * [ Java Inference API ] ( https : / / mxnet . incubator . apache . org / api / java / infer . html ) <nl> + * [ Java Inference Examples ] ( https : / / github . com / apache / incubator - mxnet / tree / java - api / scala - package / examples / src / main / java / org / apache / mxnetexamples / infer / ) <nl> + * [ MXNet Tutorials Index ] ( http : / / mxnet . io / tutorials / index . html ) <nl> mmm a / tests / tutorials / test_sanity_tutorials . py <nl> ppp b / tests / tutorials / test_sanity_tutorials . py <nl> <nl> ' unsupervised_learning / index . md ' , <nl> ' vision / index . md ' , <nl> ' tensorrt / index . md ' , <nl> - ' tensorrt / inference_with_trt . md ' ] <nl> + ' tensorrt / inference_with_trt . md ' , <nl> + ' java / mxnet_java_on_intellij . md ' ] <nl> whitelist_set = set ( whitelist ) <nl> <nl> def test_tutorial_downloadable ( ) : <nl>
[ MXNET - 1187 ] Added Tutorial for Java under mxnet . io / docs / tutorials ( )
apache/incubator-mxnet
149ea17d6bfdf1e20d5e3f7968b33fce43653f43
2018-11-08T19:05:19Z
new file mode 100644 <nl> index 0000000000 . . 72e56b438e <nl> mmm / dev / null <nl> ppp b / code / sorting / insertion_sort / insertion_sort . cs <nl> <nl> + / * <nl> + * C # Program to Perform Insertion Sort <nl> + * / <nl> + using System ; <nl> + using System . Collections . Generic ; <nl> + using System . Linq ; <nl> + using System . Text ; <nl> + using System . IO ; <nl> + namespace ConsoleApplication1 <nl> + { <nl> + class Program <nl> + { <nl> + static void Main ( string [ ] args ) <nl> + { <nl> + int [ ] arr = new int [ 5 ] { 83 , 12 , 3 , 34 , 60 } ; <nl> + int i ; <nl> + Console . WriteLine ( " The Array is : " ) ; <nl> + for ( i = 0 ; i < 5 ; i + + ) <nl> + { <nl> + Console . WriteLine ( arr [ i ] ) ; <nl> + } <nl> + insertsort ( arr , 5 ) ; <nl> + Console . WriteLine ( " The Sorted Array is : " ) ; <nl> + for ( i = 0 ; i < 5 ; i + + ) <nl> + Console . WriteLine ( arr [ i ] ) ; <nl> + Console . ReadLine ( ) ; <nl> + } <nl> + static void insertsort ( int [ ] data , int n ) <nl> + { <nl> + int i , j ; <nl> + for ( i = 1 ; i < n ; i + + ) <nl> + { <nl> + int item = data [ i ] ; <nl> + int ins = 0 ; <nl> + for ( j = i - 1 ; j > = 0 & & ins ! = 1 ; ) <nl> + { <nl> + if ( item < data [ j ] ) <nl> + { <nl> + data [ j + 1 ] = data [ j ] ; <nl> + j - - ; <nl> + data [ j + 1 ] = item ; <nl> + } <nl> + else ins = 1 ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl>
Merge pull request from enumbutz / patch - 1
OpenGenus/cosmos
664622ef31dc4e27893247b1447bdfff09f0faac
2017-10-26T11:17:13Z
mmm a / src / app / main . cpp <nl> ppp b / src / app / main . cpp <nl> const char * sysSigName [ ] = { <nl> } ; <nl> # endif <nl> <nl> + # if ! defined Q_OS_WIN & & ! defined Q_OS_HAIKU <nl> + void reportToUser ( const char * str ) ; <nl> + # endif <nl> + <nl> void displayVersion ( ) ; <nl> bool userAgreesWithLegalNotice ( ) ; <nl> void displayBadArgMessage ( const QString & message ) ; <nl> int main ( int argc , char * argv [ ] ) <nl> } <nl> } <nl> <nl> + # if ! defined Q_OS_WIN & & ! defined Q_OS_HAIKU <nl> + void reportToUser ( const char * str ) <nl> + { <nl> + const size_t strLen = strlen ( str ) ; <nl> + if ( write ( STDERR_FILENO , str , strLen ) < static_cast < ssize_t > ( strLen ) ) { <nl> + auto dummy = write ( STDOUT_FILENO , str , strLen ) ; <nl> + Q_UNUSED ( dummy ) ; <nl> + } <nl> + } <nl> + # endif <nl> + <nl> # if defined ( Q_OS_UNIX ) | | defined ( STACKTRACE_WIN ) <nl> void sigNormalHandler ( int signum ) <nl> { <nl> void sigNormalHandler ( int signum ) <nl> const char str1 [ ] = " Catching signal : " ; <nl> const char * sigName = sysSigName [ signum ] ; <nl> const char str2 [ ] = " \ nExiting cleanly \ n " ; <nl> - write ( STDERR_FILENO , str1 , strlen ( str1 ) ) ; <nl> - write ( STDERR_FILENO , sigName , strlen ( sigName ) ) ; <nl> - write ( STDERR_FILENO , str2 , strlen ( str2 ) ) ; <nl> + reportToUser ( str1 ) ; <nl> + reportToUser ( sigName ) ; <nl> + reportToUser ( str2 ) ; <nl> # endif / / ! defined Q_OS_WIN & & ! defined Q_OS_HAIKU <nl> signal ( signum , SIG_DFL ) ; <nl> qApp - > exit ( ) ; / / unsafe , but exit anyway <nl> void sigAbnormalHandler ( int signum ) <nl> const char * sigName = sysSigName [ signum ] ; <nl> const char str2 [ ] = " \ nPlease file a bug report at http : / / bug . qbittorrent . org and provide the following information : \ n \ n " <nl> " qBittorrent version : " QBT_VERSION " \ n " ; <nl> - write ( STDERR_FILENO , str1 , strlen ( str1 ) ) ; <nl> - write ( STDERR_FILENO , sigName , strlen ( sigName ) ) ; <nl> - write ( STDERR_FILENO , str2 , strlen ( str2 ) ) ; <nl> + reportToUser ( str1 ) ; <nl> + reportToUser ( sigName ) ; <nl> + reportToUser ( str2 ) ; <nl> print_stacktrace ( ) ; / / unsafe <nl> # endif / / ! defined Q_OS_WIN & & ! defined Q_OS_HAIKU <nl> # ifdef STACKTRACE_WIN <nl>
Merge pull request from evsh / fix - release - build
qbittorrent/qBittorrent
fc0c28d376746cacec7b1cfe580e0caf6563ef6e
2017-05-03T01:14:50Z
mmm a / modules / planning / scenarios / side_pass / side_pass_stop_on_wait_point . cc <nl> ppp b / modules / planning / scenarios / side_pass / side_pass_stop_on_wait_point . cc <nl> Stage : : StageStatus SidePassStopOnWaitPoint : : Process ( <nl> } <nl> <nl> / / Get the nearest obstacle <nl> - Obstacle * nearest_obstacle = nullptr ; <nl> + const Obstacle * nearest_obstacle = nullptr ; <nl> if ( ! GetTheSOfNearestObstacle ( reference_line , path_decision . obstacles ( ) , <nl> nearest_obstacle ) ) { <nl> AERROR < < " Failed while running the function to get nearest obstacle . " ; <nl> bool SidePassStopOnWaitPoint : : IsFarAwayFromObstacles ( <nl> const IndexedList < std : : string , Obstacle > & indexed_obstacle_list , <nl> const PathPoint & first_path_point , const PathPoint & last_path_point ) { <nl> common : : SLPoint first_sl_point ; <nl> + <nl> if ( ! reference_line . XYToSL ( Vec2d ( first_path_point . x ( ) , first_path_point . y ( ) ) , <nl> & first_sl_point ) ) { <nl> AERROR < < " Failed to get the projection from TrajectoryPoint onto " <nl> " reference_line " ; <nl> return false ; <nl> } <nl> + <nl> common : : SLPoint last_sl_point ; <nl> if ( ! reference_line . XYToSL ( Vec2d ( last_path_point . x ( ) , last_path_point . y ( ) ) , <nl> & last_sl_point ) ) { <nl> bool SidePassStopOnWaitPoint : : IsFarAwayFromObstacles ( <nl> bool SidePassStopOnWaitPoint : : GetTheSOfNearestObstacle ( <nl> const ReferenceLine & reference_line , <nl> const IndexedList < std : : string , Obstacle > & indexed_obstacle_list , <nl> - const Obstacle * nearest_obstacle ) { <nl> + const Obstacle * & nearest_obstacle ) { <nl> <nl> / / Get the first path point . This can be used later to <nl> / / filter out other obstaces that are behind ADC . <nl> bool SidePassStopOnWaitPoint : : GetMoveForwardLastPathPoint ( <nl> PathPoint * const last_path_point , bool * should_not_move_at_all ) { <nl> * should_not_move_at_all = false ; <nl> int count = 0 ; <nl> + <nl> bool exist_nearest_obs = ( nearest_obstacle ! = nullptr ) ; <nl> double s_max = 0 . 0 ; <nl> if ( exist_nearest_obs ) { <nl> - s_max = nearest_obstacle - > PerceptionSLBoundary ( ) . start_s ( ) ; ; <nl> + ADEBUG < < " There exists a nearest obstacle . " ; <nl> + s_max = nearest_obstacle - > PerceptionSLBoundary ( ) . start_s ( ) ; <nl> } <nl> <nl> for ( const auto & path_point : <nl> mmm a / modules / planning / scenarios / side_pass / side_pass_stop_on_wait_point . h <nl> ppp b / modules / planning / scenarios / side_pass / side_pass_stop_on_wait_point . h <nl> class SidePassStopOnWaitPoint : public Stage { <nl> bool GetTheSOfNearestObstacle ( <nl> const ReferenceLine & reference_line , <nl> const IndexedList < std : : string , Obstacle > & indexed_obstacle_list , <nl> - const Obstacle * nearest_obstacle ) ; <nl> + const Obstacle * & nearest_obstacle ) ; <nl> bool GetMoveForwardLastPathPoint ( <nl> const ReferenceLine & reference_line , <nl> const Obstacle * nearest_obstacle , <nl>
Planning : minor bug fix on pass - by - reference for a const ptr .
ApolloAuto/apollo
e9126f2ca2caccafb145891d8f438933211c8e6b
2018-12-13T23:19:49Z
mmm a / . travis . yml <nl> ppp b / . travis . yml <nl> <nl> distro : trusty <nl> sudo : required <nl> language : cpp <nl> - addons : <nl> - apt : <nl> - sources : <nl> - - ubuntu - toolchain - r - test <nl> <nl> matrix : <nl> include : <nl> - os : linux <nl> compiler : gcc <nl> + addons : <nl> + apt : <nl> + sources : <nl> + - ubuntu - toolchain - r - test <nl> + packages : <nl> + - g + + - 4 . 8 <nl> env : COMPILER = g + + - 4 . 8 <nl> - os : linux <nl> compiler : gcc <nl> + addons : <nl> + apt : <nl> + sources : <nl> + - ubuntu - toolchain - r - test <nl> + packages : <nl> + - g + + - 4 . 8 <nl> env : COMPILER = g + + - 4 . 9 <nl> - os : linux <nl> compiler : gcc <nl> + addons : <nl> + apt : <nl> + sources : <nl> + - ubuntu - toolchain - r - test <nl> + packages : <nl> + - g + + - 4 . 8 <nl> env : COMPILER = g + + - 5 <nl> - os : osx <nl> compiler : clang <nl>
Moved addons back into the matrix specification
pytorch/pytorch
2e2522bf3007e33f535cee4c6f8223ebec9bdb47
2016-12-29T20:34:26Z
mmm a / tensorflow / core / lib / core / stringpiece . cc <nl> ppp b / tensorflow / core / lib / core / stringpiece . cc <nl> limitations under the License . <nl> <nl> namespace tensorflow { <nl> <nl> - size_t StringPiece : : Hasher : : operator ( ) ( StringPiece s ) const { <nl> + size_t StringPieceHasher : : operator ( ) ( StringPiece s ) const { <nl> return Hash64 ( s . data ( ) , s . size ( ) ) ; <nl> } <nl> <nl> mmm a / tensorflow / core / lib / core / stringpiece . h <nl> ppp b / tensorflow / core / lib / core / stringpiece . h <nl> limitations under the License . <nl> <nl> namespace tensorflow { <nl> <nl> + struct StringPieceHasher ; <nl> + <nl> class StringPiece { <nl> public : <nl> typedef size_t size_type ; <nl> class StringPiece { <nl> <nl> StringPiece substr ( size_t pos , size_t n = npos ) const ; <nl> <nl> - struct Hasher { <nl> - size_t operator ( ) ( StringPiece arg ) const ; <nl> - } ; <nl> + using Hasher = : : tensorflow : : StringPieceHasher ; <nl> <nl> / / Return a string that contains the copy of the referenced data . <nl> std : : string ToString ( ) const { return std : : string ( data_ , size_ ) ; } <nl> class StringPiece { <nl> / / Intentionally copyable <nl> } ; <nl> <nl> + struct StringPieceHasher { <nl> + size_t operator ( ) ( StringPiece s ) const ; <nl> + } ; <nl> + <nl> inline bool operator = = ( StringPiece x , StringPiece y ) { <nl> return ( ( x . size ( ) = = y . size ( ) ) & & <nl> ( memcmp ( x . data ( ) , y . data ( ) , x . size ( ) ) = = 0 ) ) ; <nl>
Moved tensorflow : : StringPiece : : Hasher out of tensorflow : : StringPiece ( to tensorflow : : StringPieceHasher ) and replaced it with an alias .
tensorflow/tensorflow
dd8ad028e79005377d326a02fa77f655a0f62699
2017-11-20T22:18:27Z
mmm a / include / swift / AST / Builtins . def <nl> ppp b / include / swift / AST / Builtins . def <nl> BUILTIN_SIL_OPERATION ( Init , " initialize " , Special ) <nl> / / / MarkDependence has type ( T , U ) - > T <nl> BUILTIN_SIL_OPERATION ( MarkDependence , " markDependence " , Special ) <nl> <nl> + / / / allocValueBuffer : < T > ( inout Builtin . UnsafeValueBuffer , T . Type ) <nl> + / / / - > Builtin . RawPointer <nl> + BUILTIN_SIL_OPERATION ( AllocValueBuffer , " allocValueBuffer " , Special ) <nl> + <nl> + / / / projectValueBuffer : < T > ( inout Builtin . UnsafeValueBuffer , T . Type ) <nl> + / / / - > Builtin . RawPointer <nl> + BUILTIN_SIL_OPERATION ( ProjectValueBuffer , " projectValueBuffer " , Special ) <nl> + <nl> + / / / deallocValueBuffer : < T > ( inout Builtin . UnsafeValueBuffer , T . Type ) <nl> + / / / - > ( ) <nl> + BUILTIN_SIL_OPERATION ( DeallocValueBuffer , " deallocValueBuffer " , Special ) <nl> + <nl> / / / MakeMaterializeForSetCallback has type <nl> / / / ( ( Builtin . RawPointer , <nl> / / / inout Builtin . UnsafeValueBuffer , <nl> mmm a / lib / AST / Builtins . cpp <nl> ppp b / lib / AST / Builtins . cpp <nl> static ValueDecl * getTryPinOperation ( ASTContext & ctx , Identifier name ) { <nl> builder . addParameter ( makeConcrete ( ctx . TheNativeObjectType ) ) ; <nl> builder . setResult ( makeGenericParam ( ) ) ; <nl> return builder . build ( name ) ; <nl> + } <nl> <nl> + static ValueDecl * getProjectValueBufferOperation ( ASTContext & ctx , <nl> + Identifier name ) { <nl> + / / < T > ( inout Builtin . UnsafeValueBuffer , T . Type ) - > Builtin . RawPointer <nl> + GenericSignatureBuilder builder ( ctx ) ; <nl> + builder . addParameter ( makeConcrete ( <nl> + InOutType : : get ( ctx . TheUnsafeValueBufferType ) ) ) ; <nl> + builder . addParameter ( makeMetatype ( makeGenericParam ( ) ) ) ; <nl> + builder . setResult ( makeConcrete ( ctx . TheRawPointerType ) ) ; <nl> + return builder . build ( name ) ; <nl> + } <nl> <nl> + static ValueDecl * getDeallocValueBufferOperation ( ASTContext & ctx , <nl> + Identifier name ) { <nl> + / / < T > ( inout Builtin . UnsafeValueBuffer , T . Type ) - > ( ) <nl> + GenericSignatureBuilder builder ( ctx ) ; <nl> + builder . addParameter ( makeConcrete ( <nl> + InOutType : : get ( ctx . TheUnsafeValueBufferType ) ) ) ; <nl> + builder . addParameter ( makeMetatype ( makeGenericParam ( ) ) ) ; <nl> + builder . setResult ( makeConcrete ( ctx . TheRawPointerType ) ) ; <nl> + return builder . build ( name ) ; <nl> } <nl> <nl> static ValueDecl * <nl> ValueDecl * swift : : getBuiltinValueDecl ( ASTContext & Context , Identifier Id ) { <nl> if ( ! Types . empty ( ) ) return nullptr ; <nl> return getReinterpretCastOperation ( Context , Id ) ; <nl> <nl> + case BuiltinValueKind : : AllocValueBuffer : <nl> + case BuiltinValueKind : : ProjectValueBuffer : <nl> + if ( ! Types . empty ( ) ) return nullptr ; <nl> + return getProjectValueBufferOperation ( Context , Id ) ; <nl> + <nl> + case BuiltinValueKind : : DeallocValueBuffer : <nl> + if ( ! Types . empty ( ) ) return nullptr ; <nl> + return getDeallocValueBufferOperation ( Context , Id ) ; <nl> + <nl> case BuiltinValueKind : : MakeMaterializeForSetCallback : <nl> if ( ! Types . empty ( ) ) return nullptr ; <nl> return getMakeMaterializeForSetCallbackOperation ( Context , Id ) ; <nl> mmm a / lib / SILGen / SILGenBuiltin . cpp <nl> ppp b / lib / SILGen / SILGenBuiltin . cpp <nl> <nl> <nl> # include " SpecializedEmitter . h " <nl> <nl> + # include " Cleanup . h " <nl> # include " Initialization . h " <nl> + # include " LValue . h " <nl> # include " RValue . h " <nl> + # include " Scope . h " <nl> # include " SILGenFunction . h " <nl> # include " swift / AST / ASTContext . h " <nl> # include " swift / AST / Builtins . h " <nl> static ManagedValue emitBuiltinMarkDependence ( SILGenFunction & gen , <nl> return gen . emitManagedRValueWithCleanup ( result ) ; <nl> } <nl> <nl> + <nl> + using ValueBufferOperation = <nl> + llvm : : function_ref < ManagedValue ( SILValue bufferAddr , <nl> + SILType valueType ) > ; <nl> + <nl> + static ManagedValue <nl> + emitValueBufferOperation ( SILGenFunction & gen , <nl> + SILLocation loc , <nl> + ArrayRef < Substitution > subs , <nl> + Expr * tupleArg , <nl> + SGFContext C , <nl> + const ValueBufferOperation & operation ) { <nl> + <nl> + assert ( subs . size ( ) = = 1 ) ; <nl> + auto args = decomposeArguments ( gen , tupleArg , 2 ) ; <nl> + <nl> + / / It ' s really not safe if we ever need to do writeback for this , <nl> + / / but go ahead and satisfy the rules , and bound the cleanups while <nl> + / / we ' re at it . <nl> + FullExpr fullExpr ( gen . Cleanups , CleanupLocation : : getCleanupLocation ( loc ) ) ; <nl> + WritebackScope writebackScope ( gen ) ; <nl> + <nl> + LValue bufferLV = gen . emitLValue ( args [ 0 ] , AccessKind : : ReadWrite ) ; <nl> + <nl> + / / Ignore the metatype argument . <nl> + gen . emitIgnoredExpr ( args [ 1 ] ) ; <nl> + <nl> + ManagedValue bufferAddr = <nl> + gen . emitAddressOfLValue ( args [ 0 ] , std : : move ( bufferLV ) , <nl> + AccessKind : : ReadWrite ) ; <nl> + <nl> + / / Like Builtin . load / initialize , we use the current abstraction level . <nl> + / / ( This is crucial , because we expect the result to be passed to <nl> + / / those builtins ! ) <nl> + SILType valueTy = gen . getLoweredType ( subs [ 0 ] . getReplacement ( ) ) ; <nl> + <nl> + return operation ( bufferAddr . getValue ( ) , valueTy ) ; <nl> + } <nl> + <nl> + <nl> + static ManagedValue <nl> + emitBuiltinAllocValueBuffer ( SILGenFunction & gen , <nl> + SILLocation loc , <nl> + ArrayRef < Substitution > subs , <nl> + Expr * tupleArg , <nl> + SGFContext C ) { <nl> + return emitValueBufferOperation ( gen , loc , subs , tupleArg , C , <nl> + [ & ] ( SILValue bufferAddr , SILType valueTy ) <nl> + - > ManagedValue { <nl> + SILValue result = <nl> + gen . B . createAllocValueBuffer ( loc , valueTy , bufferAddr ) ; <nl> + result = gen . B . createAddressToPointer ( loc , result , <nl> + SILType : : getRawPointerType ( gen . getASTContext ( ) ) ) ; <nl> + return ManagedValue : : forUnmanaged ( result ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + static ManagedValue <nl> + emitBuiltinProjectValueBuffer ( SILGenFunction & gen , <nl> + SILLocation loc , <nl> + ArrayRef < Substitution > subs , <nl> + Expr * tupleArg , <nl> + SGFContext C ) { <nl> + return emitValueBufferOperation ( gen , loc , subs , tupleArg , C , <nl> + [ & ] ( SILValue bufferAddr , SILType valueTy ) <nl> + - > ManagedValue { <nl> + SILValue result = <nl> + gen . B . createProjectValueBuffer ( loc , valueTy , bufferAddr ) ; <nl> + result = gen . B . createAddressToPointer ( loc , result , <nl> + SILType : : getRawPointerType ( gen . getASTContext ( ) ) ) ; <nl> + return ManagedValue : : forUnmanaged ( result ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + static ManagedValue <nl> + emitBuiltinDeallocValueBuffer ( SILGenFunction & gen , <nl> + SILLocation loc , <nl> + ArrayRef < Substitution > subs , <nl> + Expr * tupleArg , <nl> + SGFContext C ) { <nl> + return emitValueBufferOperation ( gen , loc , subs , tupleArg , C , <nl> + [ & ] ( SILValue bufferAddr , SILType valueTy ) <nl> + - > ManagedValue { <nl> + gen . B . createDeallocValueBuffer ( loc , valueTy , bufferAddr ) ; <nl> + return ManagedValue : : forUnmanaged ( gen . emitEmptyTuple ( loc ) ) ; <nl> + } ) ; <nl> + } <nl> + <nl> static CanType makeThick ( CanMetatypeType oldMetatype ) { <nl> return CanMetatypeType : : get ( oldMetatype . getInstanceType ( ) , <nl> MetatypeRepresentation : : Thick ) ; <nl> mmm a / test / SILGen / builtins . swift <nl> ppp b / test / SILGen / builtins . swift <nl> func pinUnpin ( object : Builtin . NativeObject ) { <nl> / / CHECK - NEXT : [ [ T0 : % . * ] ] = tuple ( ) <nl> / / CHECK - NEXT : return [ [ T0 ] ] : $ ( ) <nl> } <nl> + <nl> + / / CHECK - LABEL : sil hidden @ _TF8builtins19allocateValueBufferFRBbBp : $ @ thin ( @ inout Builtin . UnsafeValueBuffer ) - > Builtin . RawPointer <nl> + / / CHECK - NEXT : bb0 ( [ [ BUFFER : % . * ] ] : $ * Builtin . UnsafeValueBuffer ) : <nl> + / / CHECK - NEXT : metatype $ @ thin Int . Type <nl> + / / CHECK - NEXT : [ [ T0 : % . * ] ] = alloc_value_buffer $ Int in [ [ BUFFER ] ] : $ * Builtin . UnsafeValueBuffer <nl> + / / CHECK - NEXT : [ [ T1 : % . * ] ] = address_to_pointer [ [ T0 ] ] : $ * Int to $ Builtin . RawPointer <nl> + / / CHECK - NEXT : return [ [ T1 ] ] : $ Builtin . RawPointer <nl> + func allocateValueBuffer ( inout buffer : Builtin . UnsafeValueBuffer ) - > Builtin . RawPointer { <nl> + return Builtin . allocValueBuffer ( & buffer , Int . self ) <nl> + } <nl> + <nl> + / / CHECK - LABEL : sil hidden @ _TF8builtins18projectValueBufferFRBbBp : $ @ thin ( @ inout Builtin . UnsafeValueBuffer ) - > Builtin . RawPointer <nl> + / / CHECK - NEXT : bb0 ( [ [ BUFFER : % . * ] ] : $ * Builtin . UnsafeValueBuffer ) : <nl> + / / CHECK - NEXT : metatype $ @ thin Int . Type <nl> + / / CHECK - NEXT : [ [ T0 : % . * ] ] = project_value_buffer $ Int in [ [ BUFFER ] ] : $ * Builtin . UnsafeValueBuffer <nl> + / / CHECK - NEXT : [ [ T1 : % . * ] ] = address_to_pointer [ [ T0 ] ] : $ * Int to $ Builtin . RawPointer <nl> + / / CHECK - NEXT : return [ [ T1 ] ] : $ Builtin . RawPointer <nl> + func projectValueBuffer ( inout buffer : Builtin . UnsafeValueBuffer ) - > Builtin . RawPointer { <nl> + return Builtin . projectValueBuffer ( & buffer , Int . self ) <nl> + } <nl> + <nl> + / / CHECK - LABEL : sil hidden @ _TF8builtins18deallocValueBufferFRBbT_ : $ @ thin ( @ inout Builtin . UnsafeValueBuffer ) - > ( ) <nl> + / / CHECK - NEXT : bb0 ( [ [ BUFFER : % . * ] ] : $ * Builtin . UnsafeValueBuffer ) : <nl> + / / CHECK - NEXT : metatype $ @ thin Int . Type <nl> + / / CHECK - NEXT : dealloc_value_buffer $ Int in [ [ BUFFER ] ] : $ * Builtin . UnsafeValueBuffer <nl> + / / CHECK - NEXT : tuple ( ) <nl> + / / CHECK - NEXT : [ [ T0 : % . * ] ] = tuple ( ) <nl> + / / CHECK - NEXT : return [ [ T0 ] ] : $ ( ) <nl> + func deallocValueBuffer ( inout buffer : Builtin . UnsafeValueBuffer ) - > ( ) { <nl> + Builtin . deallocValueBuffer ( & buffer , Int . self ) <nl> + } <nl>
Add builtins for allocating , projecting , and deallocating
apple/swift
f19c31fbecb34480c9ca5ff2bf64996c092e2db1
2014-12-19T22:41:13Z
mmm a / modules / calib3d / include / opencv2 / calib3d . hpp <nl> ppp b / modules / calib3d / include / opencv2 / calib3d . hpp <nl> respectively . In the old interface all the vectors of object points from differe <nl> concatenated together . <nl> @ param imageSize Size of the image used only to initialize the camera intrinsic matrix . <nl> @ param cameraMatrix Input / output 3x3 floating - point camera intrinsic matrix <nl> - \ f $ \ cameramatrix { A } \ f $ . If @ ref CV_CALIB_USE_INTRINSIC_GUESS <nl> + \ f $ \ cameramatrix { A } \ f $ . If @ ref CALIB_USE_INTRINSIC_GUESS <nl> and / or @ ref CALIB_FIX_ASPECT_RATIO are specified , some or all of fx , fy , cx , cy must be <nl> initialized before calling the function . <nl> @ param distCoeffs Input / output vector of distortion coefficients <nl>
docs ( calib3d ) : avoid reference on legacy C API constants
opencv/opencv
94e7be3714c03efd82228ac01c1a777f9f486394
2020-12-17T21:03:27Z
mmm a / ports / fmt / CONTROL <nl> ppp b / ports / fmt / CONTROL <nl> <nl> Source : fmt <nl> - Version : 7 . 1 . 1 <nl> + Version : 7 . 1 . 2 <nl> Port - Version : 0 <nl> Homepage : https : / / github . com / fmtlib / fmt <nl> Description : Formatting library for C + + . It can be used as a safe alternative to printf or as a fast alternative to IOStreams . <nl> mmm a / ports / fmt / portfile . cmake <nl> ppp b / ports / fmt / portfile . cmake <nl> <nl> vcpkg_from_github ( <nl> OUT_SOURCE_PATH SOURCE_PATH <nl> REPO fmtlib / fmt <nl> - REF 5f7f7b954d0e958f3d94f3d906177c6a1090f079 # v7 . 1 . 1 <nl> - SHA512 d0453e96a9c09641a1931b8fce15ac8544252f72373159809c9a5227ac1408d8e00a0de33dfa007afa586adbc06ab6a9c8f3bd20dc6911927fab1d4cc6fc7c03 <nl> + REF cc09f1a6798c085c325569ef466bcdcffdc266d4 # v7 . 1 . 2 <nl> + SHA512 a7bdd62ec98e3098182bc5080938b37284ced83f007ea3ef45e27407c04fc13a9e5852ab959b3d02088286480924c71e9fd23492c20d8752cf7e890b2a1ec52e <nl> HEAD_REF master <nl> PATCHES fix - warning4189 . patch <nl> ) <nl>
[ fmt ] update to 7 . 1 . 2 ( )
microsoft/vcpkg
d218ca7e6f6eab8679d2e968b43a208e689ac920
2020-11-06T21:19:33Z
mmm a / arangod / Aql / ExecutionNode . h <nl> ppp b / arangod / Aql / ExecutionNode . h <nl> namespace triagens { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> virtual std : : vector < Variable const * > getVariablesUsedHere ( ) const override final { <nl> + / / Please do not change the order here without adjusting the <nl> + / / optimizer rule distributeInCluster as well ! <nl> std : : vector < Variable const * > v ; <nl> v . push_back ( _inDocVariable ) ; <nl> <nl> namespace triagens { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> virtual std : : vector < Variable const * > getVariablesUsedHere ( ) const override final { <nl> + / / Please do not change the order here without adjusting the <nl> + / / optimizer rule distributeInCluster as well ! <nl> std : : vector < Variable const * > v ; <nl> v . push_back ( _inDocVariable ) ; <nl> <nl> namespace triagens { <nl> : ExecutionNode ( plan , id ) , <nl> _vocbase ( vocbase ) , <nl> _collection ( collection ) , <nl> - _varId ( varId ) { <nl> + _varId ( varId ) { <nl> } <nl> <nl> DistributeNode ( ExecutionPlan * , <nl> mmm a / arangod / Aql / OptimizerRules . cpp <nl> ppp b / arangod / Aql / OptimizerRules . cpp <nl> int triagens : : aql : : distributeInClusterRule ( Optimizer * opt , <nl> <nl> Collection const * collection = static_cast < ModificationNode * > ( node ) - > collection ( ) ; <nl> <nl> + bool defaultSharding = true ; <nl> + / / check if collection shard keys are only _key <nl> + std : : vector < std : : string > shardKeys = collection - > shardKeys ( ) ; <nl> + if ( shardKeys . size ( ) ! = 1 | | shardKeys [ 0 ] ! = TRI_VOC_ATTRIBUTE_KEY ) { <nl> + defaultSharding = false ; <nl> + } <nl> + <nl> if ( nodeType = = ExecutionNode : : REMOVE | | <nl> - nodeType = = ExecutionNode : : UPDATE | | <nl> - nodeType = = ExecutionNode : : REPLACE ) { <nl> - / / check if collection shard keys are only _key <nl> - std : : vector < std : : string > shardKeys = collection - > shardKeys ( ) ; <nl> - if ( shardKeys . size ( ) ! = 1 | | shardKeys [ 0 ] ! = TRI_VOC_ATTRIBUTE_KEY ) { <nl> + nodeType = = ExecutionNode : : UPDATE ) { <nl> + if ( ! defaultSharding ) { <nl> + / / We have to use a ScatterNode . <nl> opt - > addPlan ( plan , rule - > level , wasModified ) ; <nl> return TRI_ERROR_NO_ERROR ; <nl> } <nl> int triagens : : aql : : distributeInClusterRule ( Optimizer * opt , <nl> vocbase , collection , node - > getVariablesUsedHere ( ) [ 0 ] - > id ) ; <nl> } <nl> else if ( nodeType = = ExecutionNode : : REPLACE ) { <nl> - auto replNode = static_cast < ReplaceNode const * > ( node ) ; <nl> - distNode = new DistributeNode ( plan , plan - > nextId ( ) , <nl> - vocbase , collection , replNode - > _inKeyVariable ) ; <nl> - / / FIXME : DistributeBlock must look into two places <nl> + std : : vector < Variable const * > v = node - > getVariablesUsedHere ( ) ; <nl> + if ( defaultSharding ) { <nl> + / / We only look into _inKeyVariable <nl> + distNode = new DistributeNode ( plan , plan - > nextId ( ) , <nl> + vocbase , collection , v [ 1 ] - > id ) ; <nl> + } <nl> + else { <nl> + / / We only look into _inDocVariable <nl> + distNode = new DistributeNode ( plan , plan - > nextId ( ) , <nl> + vocbase , collection , v [ 0 ] - > id ) ; <nl> + } <nl> } <nl> - else / / if ( nodeType = = ExecutionNode : : UPDATE ) { <nl> - auto updNode = static_cast < UpdateNode const * > ( node ) ; <nl> + else { / / if ( nodeType = = ExecutionNode : : UPDATE ) <nl> + std : : vector < Variable const * > v = node - > getVariablesUsedHere ( ) ; <nl> distNode = new DistributeNode ( plan , plan - > nextId ( ) , <nl> - vocbase , collection , updNode - > _inKeyVariable ) ; <nl> + vocbase , collection , v [ 1 ] - > id ) ; <nl> + / / This is the _inKeyVariable ! This works , since we use a ScatterNode <nl> + / / for non - default - sharding attributes . <nl> } <nl> plan - > registerNode ( distNode ) ; <nl> distNode - > addDependency ( deps [ 0 ] ) ; <nl>
Fix modifying AQL in cluster .
arangodb/arangodb
6fe1fb8568ccf69664bfa2f823ec21dce20b6ce0
2014-12-23T21:44:01Z
mmm a / hphp / hack / test / integration / test_fresh_init . py <nl> ppp b / hphp / hack / test / integration / test_fresh_init . py <nl> def check_cmd ( self , expected_output , stdin = None , options = ( ) , retries = 3 ) : <nl> hh_client , <nl> ' check ' , <nl> ' - - retries ' , <nl> - ' 20 ' , <nl> + ' 30 ' , <nl> ' - - no - load ' , <nl> self . repo_dir <nl> ] + list ( map ( lambda x : x . format ( root = root ) , options ) ) , <nl>
Give check cmd on fresh init more time
facebook/hhvm
91fdf99f674d5e61c04ecff9cb5376cf87c0ba86
2016-10-21T20:46:20Z
mmm a / folly / Portability . h <nl> ppp b / folly / Portability . h <nl> constexpr auto kIsLinux = false ; <nl> <nl> # if defined ( _WIN32 ) <nl> constexpr auto kIsWindows = true ; <nl> - constexpr auto kMscVer = _MSC_VER ; <nl> # else <nl> constexpr auto kIsWindows = false ; <nl> + # endif <nl> + <nl> + # if _MSC_VER <nl> + constexpr auto kMscVer = _MSC_VER ; <nl> + # else <nl> constexpr auto kMscVer = 0 ; <nl> # endif <nl> } / / namespace folly <nl> mmm a / folly / experimental / hazptr / hazptr - impl . h <nl> ppp b / folly / experimental / hazptr / hazptr - impl . h <nl> class hazptr_priv { <nl> } ; <nl> <nl> static_assert ( <nl> - folly : : kIsWindows | | std : : is_trivial < hazptr_priv > : : value , <nl> + folly : : kMscVer | | std : : is_trivial < hazptr_priv > : : value , <nl> " hazptr_priv must be trivial to avoid a branch to check initialization " ) ; <nl> <nl> void hazptr_priv_init ( ) ; <nl>
Split definition of kMscVer from kIsWindows
facebook/folly
3af93759fcff01b86d62af911f4bd634faade57d
2018-02-20T20:53:04Z
mmm a / src / library_browser . js <nl> ppp b / src / library_browser . js <nl> mergeInto ( LibraryManager . library , { <nl> window . requestAnimationFrame ( func ) ; <nl> } , <nl> <nl> - getMovementX : function ( delta , event ) { <nl> - if ( ! Browser . pointerLock ) return delta ; <nl> + getMovementX : function ( event ) { <nl> return event [ ' movementX ' ] | | <nl> event [ ' mozMovementX ' ] | | <nl> event [ ' webkitMovementX ' ] | | <nl> - 0 ; / / delta ; <nl> + 0 ; <nl> } , <nl> <nl> - getMovementY : function ( delta , event ) { <nl> - if ( ! Browser . pointerLock ) return delta ; <nl> + getMovementY : function ( event ) { <nl> return event [ ' movementY ' ] | | <nl> event [ ' mozMovementY ' ] | | <nl> event [ ' webkitMovementY ' ] | | <nl> - 0 ; / / delta ; <nl> + 0 ; <nl> } , <nl> <nl> asyncLoad : function ( url , callback ) { <nl> mmm a / src / library_sdl . js <nl> ppp b / src / library_sdl . js <nl> var LibrarySDL = { <nl> } <nl> / / fall through <nl> case ' mousemove ' : { <nl> - var x = event . pageX - Module [ ' canvas ' ] . offsetLeft ; <nl> - var y = event . pageY - Module [ ' canvas ' ] . offsetTop ; <nl> + if ( Browser . pointerLock ) { <nl> + / / When the pointer is locked , calculate the coordinates <nl> + / / based on the movement of the mouse . <nl> + var movementX = Browser . getMovementX ( event ) ; <nl> + var movementY = Browser . getMovementY ( event ) ; <nl> + var x = SDL . mouseX + movementX ; <nl> + var y = SDL . mouseY + movementY ; <nl> + } else { <nl> + / / Otherwise , calculate the movement based on the changes <nl> + / / in the coordinates . <nl> + var x = event . pageX - Module [ " canvas " ] . offsetLeft ; <nl> + var y = event . pageY - Module [ " canvas " ] . offsetTop ; <nl> + var movementX = x - SDL . mouseX ; <nl> + var movementY = y - SDL . mouseY ; <nl> + } <nl> if ( event . type ! = ' mousemove ' ) { <nl> var down = event . type = = = ' mousedown ' ; <nl> { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseButtonEvent . type ' , ' SDL . DOMEventToSDLEvent [ event . type ] ' , ' i32 ' ) } } } ; <nl> var LibrarySDL = { <nl> { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . state ' , ' SDL . buttonState ' , ' i8 ' ) } } } ; <nl> { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . x ' , ' x ' , ' i32 ' ) } } } ; <nl> { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . y ' , ' y ' , ' i32 ' ) } } } ; <nl> - { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . xrel ' , ' Browser . getMovementX ( x - SDL . mouseX , event ) ' , ' i32 ' ) } } } ; <nl> - { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . yrel ' , ' Browser . getMovementY ( y - SDL . mouseY , event ) ' , ' i32 ' ) } } } ; <nl> + { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . xrel ' , ' movementX ' , ' i32 ' ) } } } ; <nl> + { { { makeSetValue ( ' ptr ' , ' SDL . structs . MouseMotionEvent . yrel ' , ' movementY ' , ' i32 ' ) } } } ; <nl> } <nl> SDL . mouseX = x ; <nl> SDL . mouseY = y ; <nl>
Merge pull request from ehsan / mouselockmovement
emscripten-core/emscripten
8f371ae5c3aeebb018e2e0c60f4c2f27e2b36837
2012-06-17T17:34:17Z
mmm a / stdlib / public / core / HashedCollections . swift . gyb <nl> ppp b / stdlib / public / core / HashedCollections . swift . gyb <nl> internal enum _Variant $ { Self } Storage < $ { TypeParametersDecl } > : _HashStorageType { <nl> switch self { <nl> case . Native : <nl> let oldCapacity = native . capacity <nl> - # if _runtime ( _ObjC ) <nl> if isUniquelyReferenced ( ) & & oldCapacity > = minimumCapacity { <nl> + # if _runtime ( _ObjC ) <nl> / / Clear the cache of bridged elements . <nl> switch self { <nl> case . Native ( let owner ) : <nl> internal enum _Variant $ { Self } Storage < $ { TypeParametersDecl } > : _HashStorageType { <nl> case . Cocoa : <nl> _sanityCheckFailure ( " internal error : not backed by native storage " ) <nl> } <nl> + # endif <nl> return ( reallocated : false , capacityChanged : false ) <nl> } <nl> - # endif <nl> <nl> let oldNativeStorage = native <nl> let newNativeOwner = NativeStorageOwner ( minimumCapacity : minimumCapacity ) <nl> mmm a / validation - test / stdlib / SwiftPrivateSerializationMsgPack . swift <nl> ppp b / validation - test / stdlib / SwiftPrivateSerializationMsgPack . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> <nl> - / / UNSUPPORTED : OS = linux - gnu <nl> - / / FIXME : on Linux , this test does not finish in reasonable time because of : <nl> - / / < rdar : / / problem / 20089729 > Dictionary reallocates storage on every mutation <nl> - <nl> import SwiftPrivateSerialization <nl> import StdlibUnittest <nl> <nl>
Check if existing capacity is enough even on non - objc .
apple/swift
388f0dd5de8259b8426f194eaae6db47e95e84b5
2015-03-13T20:14:20Z
mmm a / src / arm / interface - descriptors - arm . cc <nl> ppp b / src / arm / interface - descriptors - arm . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r0 , / / argument count ( not including receiver ) <nl> r1 , / / target to call checked to be Array function <nl> mmm a / src / arm64 / interface - descriptors - arm64 . cc <nl> ppp b / src / arm64 / interface - descriptors - arm64 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> x0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> x0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> x0 , / / argument count ( not including receiver ) <nl> x1 , / / target to call checked to be Array function <nl> mmm a / src / builtins / arm / builtins - arm . cc <nl> ppp b / src / builtins / arm / builtins - arm . cc <nl> static void Generate_StackOverflowCheck ( MacroAssembler * masm , Register num_args , <nl> <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> Register num_args , Register index , <nl> - Register limit , Register scratch , <nl> - Label * stack_overflow ) { <nl> - / / Add a stack check before pushing arguments . <nl> - Generate_StackOverflowCheck ( masm , num_args , scratch , stack_overflow ) ; <nl> - <nl> + Register limit , Register scratch ) { <nl> / / Find the address of the last argument . <nl> __ mov ( limit , num_args ) ; <nl> __ mov ( limit , Operand ( limit , LSL , kPointerSizeLog2 ) ) ; <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r0 : the number of arguments ( not including the receiver ) <nl> / / - - r2 : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> <nl> __ add ( r3 , r0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> <nl> + Generate_StackOverflowCheck ( masm , r3 , r4 , & stack_overflow ) ; <nl> + <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ mov ( r3 , r0 ) ; / / Argument count is correct . <nl> + } <nl> + <nl> / / Push the arguments . r2 , r4 , r5 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , r3 , r2 , r4 , r5 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , r3 , r2 , r4 , r5 ) ; <nl> <nl> / / Call the target . <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> __ mov ( ip , Operand : : Zero ( ) ) ; <nl> __ push ( ip ) ; <nl> <nl> + Generate_StackOverflowCheck ( masm , r0 , r5 , & stack_overflow ) ; <nl> + <nl> / / Push the arguments . r5 , r4 , r6 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , r0 , r4 , r5 , r6 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , r0 , r4 , r5 , r6 ) ; <nl> <nl> __ AssertUndefinedOrAllocationSite ( r2 , r5 ) ; <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Label stack_overflow ; <nl> <nl> - __ add ( r4 , r0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> + / / Push a slot for the receiver to be constructed . <nl> + __ mov ( ip , Operand : : Zero ( ) ) ; <nl> + __ push ( ip ) ; <nl> + <nl> + Generate_StackOverflowCheck ( masm , r0 , r5 , & stack_overflow ) ; <nl> <nl> - / / TODO ( mythria ) : Add a stack check before pushing arguments . <nl> / / Push the arguments . r3 , r5 , r6 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , r4 , r3 , r5 , r6 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , r0 , r3 , r5 , r6 ) ; <nl> <nl> / / Array constructor expects constructor in r3 . It is same as r1 here . <nl> __ mov ( r3 , r1 ) ; <nl> mmm a / src / builtins / arm64 / builtins - arm64 . cc <nl> ppp b / src / builtins / arm64 / builtins - arm64 . cc <nl> static void Generate_StackOverflowCheck ( MacroAssembler * masm , Register num_args , <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> Register num_args , Register index , <nl> Register last_arg , Register stack_addr , <nl> - Register scratch , <nl> - Label * stack_overflow ) { <nl> - / / Add a stack check before pushing arguments . <nl> - Generate_StackOverflowCheck ( masm , num_args , scratch , stack_overflow ) ; <nl> - <nl> + Register scratch ) { <nl> __ Mov ( scratch , num_args ) ; <nl> __ lsl ( scratch , scratch , kPointerSizeLog2 ) ; <nl> __ sub ( last_arg , index , scratch ) ; <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - x0 : the number of arguments ( not including the receiver ) <nl> / / - - x2 : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> / / Add one for the receiver . <nl> __ add ( x3 , x0 , Operand ( 1 ) ) ; <nl> <nl> + / / Add a stack check before pushing arguments . <nl> + Generate_StackOverflowCheck ( masm , x3 , x6 , & stack_overflow ) ; <nl> + <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ Mov ( x3 , x0 ) ; / / Argument count is correct . <nl> + } <nl> + <nl> / / Push the arguments . x2 , x4 , x5 , x6 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , x3 , x2 , x4 , x5 , x6 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , x3 , x2 , x4 , x5 , x6 ) ; <nl> <nl> / / Call the target . <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - x0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> / / Push a slot for the receiver . <nl> __ Push ( xzr ) ; <nl> <nl> + / / Add a stack check before pushing arguments . <nl> + Generate_StackOverflowCheck ( masm , x0 , x7 , & stack_overflow ) ; <nl> + <nl> / / Push the arguments . x5 , x4 , x6 , x7 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , x0 , x4 , x5 , x6 , x7 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , x0 , x4 , x5 , x6 , x7 ) ; <nl> <nl> __ AssertUndefinedOrAllocationSite ( x2 , x6 ) ; <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - x0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Label stack_overflow ; <nl> <nl> - __ add ( x4 , x0 , Operand ( 1 ) ) ; / / Add one for the receiver . <nl> + / / Push a slot for the receiver . <nl> + __ Push ( xzr ) ; <nl> + <nl> + / / Add a stack check before pushing arguments . <nl> + Generate_StackOverflowCheck ( masm , x0 , x7 , & stack_overflow ) ; <nl> <nl> / / Push the arguments . x3 , x5 , x6 , x7 will be modified . <nl> - Generate_InterpreterPushArgs ( masm , x4 , x3 , x5 , x6 , x7 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , x0 , x3 , x5 , x6 , x7 ) ; <nl> <nl> / / Array constructor expects constructor in x3 . It is same as call target . <nl> __ mov ( x3 , x1 ) ; <nl> mmm a / src / builtins / builtins - definitions . h <nl> ppp b / src / builtins / builtins - definitions . h <nl> namespace internal { <nl> \ <nl> / * Interpreter * / \ <nl> ASM ( InterpreterEntryTrampoline ) \ <nl> - ASM ( InterpreterPushArgsAndCall ) \ <nl> - ASM ( InterpreterPushArgsAndCallFunction ) \ <nl> - ASM ( InterpreterPushArgsAndCallWithFinalSpread ) \ <nl> - ASM ( InterpreterPushArgsAndTailCall ) \ <nl> - ASM ( InterpreterPushArgsAndTailCallFunction ) \ <nl> - ASM ( InterpreterPushArgsAndConstruct ) \ <nl> - ASM ( InterpreterPushArgsAndConstructFunction ) \ <nl> - ASM ( InterpreterPushArgsAndConstructArray ) \ <nl> - ASM ( InterpreterPushArgsAndConstructWithFinalSpread ) \ <nl> + ASM ( InterpreterPushArgsThenCall ) \ <nl> + ASM ( InterpreterPushUndefinedAndArgsThenCall ) \ <nl> + ASM ( InterpreterPushArgsThenCallFunction ) \ <nl> + ASM ( InterpreterPushUndefinedAndArgsThenCallFunction ) \ <nl> + ASM ( InterpreterPushArgsThenCallWithFinalSpread ) \ <nl> + ASM ( InterpreterPushArgsThenTailCall ) \ <nl> + ASM ( InterpreterPushArgsThenTailCallFunction ) \ <nl> + ASM ( InterpreterPushArgsThenConstruct ) \ <nl> + ASM ( InterpreterPushArgsThenConstructFunction ) \ <nl> + ASM ( InterpreterPushArgsThenConstructArray ) \ <nl> + ASM ( InterpreterPushArgsThenConstructWithFinalSpread ) \ <nl> ASM ( InterpreterEnterBytecodeAdvance ) \ <nl> ASM ( InterpreterEnterBytecodeDispatch ) \ <nl> ASM ( InterpreterOnStackReplacement ) \ <nl> mmm a / src / builtins / builtins - interpreter - gen . cc <nl> ppp b / src / builtins / builtins - interpreter - gen . cc <nl> <nl> namespace v8 { <nl> namespace internal { <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndCall ( MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndCallImpl ( <nl> - masm , TailCallMode : : kDisallow , InterpreterPushArgsMode : : kOther ) ; <nl> + void Builtins : : Generate_InterpreterPushArgsThenCall ( MacroAssembler * masm ) { <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kAny , TailCallMode : : kDisallow , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallFunction ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallFunction ( <nl> MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndCallImpl ( <nl> - masm , TailCallMode : : kDisallow , InterpreterPushArgsMode : : kJSFunction ) ; <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kAny , TailCallMode : : kDisallow , <nl> + InterpreterPushArgsMode : : kJSFunction ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallWithFinalSpread ( <nl> + void Builtins : : Generate_InterpreterPushUndefinedAndArgsThenCall ( <nl> MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndCallImpl ( <nl> - masm , TailCallMode : : kDisallow , InterpreterPushArgsMode : : kWithFinalSpread ) ; <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kNullOrUndefined , TailCallMode : : kDisallow , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndTailCall ( MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndCallImpl ( <nl> - masm , TailCallMode : : kAllow , InterpreterPushArgsMode : : kOther ) ; <nl> + void Builtins : : Generate_InterpreterPushUndefinedAndArgsThenCallFunction ( <nl> + MacroAssembler * masm ) { <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kNullOrUndefined , TailCallMode : : kDisallow , <nl> + InterpreterPushArgsMode : : kJSFunction ) ; <nl> + } <nl> + <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallWithFinalSpread ( <nl> + MacroAssembler * masm ) { <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kAny , TailCallMode : : kDisallow , <nl> + InterpreterPushArgsMode : : kWithFinalSpread ) ; <nl> + } <nl> + <nl> + void Builtins : : Generate_InterpreterPushArgsThenTailCall ( MacroAssembler * masm ) { <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kAny , TailCallMode : : kAllow , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndTailCallFunction ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenTailCallFunction ( <nl> MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndCallImpl ( <nl> - masm , TailCallMode : : kAllow , InterpreterPushArgsMode : : kJSFunction ) ; <nl> + return Generate_InterpreterPushArgsThenCallImpl ( <nl> + masm , ConvertReceiverMode : : kAny , TailCallMode : : kAllow , <nl> + InterpreterPushArgsMode : : kJSFunction ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstruct ( MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstruct ( MacroAssembler * masm ) { <nl> + return Generate_InterpreterPushArgsThenConstructImpl ( <nl> masm , InterpreterPushArgsMode : : kOther ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructWithFinalSpread ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructWithFinalSpread ( <nl> MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndConstructImpl ( <nl> + return Generate_InterpreterPushArgsThenConstructImpl ( <nl> masm , InterpreterPushArgsMode : : kWithFinalSpread ) ; <nl> } <nl> <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructFunction ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructFunction ( <nl> MacroAssembler * masm ) { <nl> - return Generate_InterpreterPushArgsAndConstructImpl ( <nl> + return Generate_InterpreterPushArgsThenConstructImpl ( <nl> masm , InterpreterPushArgsMode : : kJSFunction ) ; <nl> } <nl> <nl> mmm a / src / builtins / builtins - interpreter . cc <nl> ppp b / src / builtins / builtins - interpreter . cc <nl> <nl> namespace v8 { <nl> namespace internal { <nl> <nl> - Handle < Code > Builtins : : InterpreterPushArgsAndCall ( <nl> - TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> + Handle < Code > Builtins : : InterpreterPushArgsThenCall ( <nl> + ConvertReceiverMode receiver_mode , TailCallMode tail_call_mode , <nl> + InterpreterPushArgsMode mode ) { <nl> switch ( mode ) { <nl> case InterpreterPushArgsMode : : kJSFunction : <nl> if ( tail_call_mode = = TailCallMode : : kDisallow ) { <nl> - return InterpreterPushArgsAndCallFunction ( ) ; <nl> + switch ( receiver_mode ) { <nl> + case ConvertReceiverMode : : kNullOrUndefined : <nl> + return InterpreterPushUndefinedAndArgsThenCallFunction ( ) ; <nl> + case ConvertReceiverMode : : kNotNullOrUndefined : <nl> + case ConvertReceiverMode : : kAny : <nl> + return InterpreterPushArgsThenCallFunction ( ) ; <nl> + } <nl> } else { <nl> - return InterpreterPushArgsAndTailCallFunction ( ) ; <nl> + CHECK_EQ ( receiver_mode , ConvertReceiverMode : : kAny ) ; <nl> + return InterpreterPushArgsThenTailCallFunction ( ) ; <nl> } <nl> case InterpreterPushArgsMode : : kWithFinalSpread : <nl> CHECK ( tail_call_mode = = TailCallMode : : kDisallow ) ; <nl> - return InterpreterPushArgsAndCallWithFinalSpread ( ) ; <nl> + return InterpreterPushArgsThenCallWithFinalSpread ( ) ; <nl> case InterpreterPushArgsMode : : kOther : <nl> if ( tail_call_mode = = TailCallMode : : kDisallow ) { <nl> - return InterpreterPushArgsAndCall ( ) ; <nl> + switch ( receiver_mode ) { <nl> + case ConvertReceiverMode : : kNullOrUndefined : <nl> + return InterpreterPushUndefinedAndArgsThenCall ( ) ; <nl> + case ConvertReceiverMode : : kNotNullOrUndefined : <nl> + case ConvertReceiverMode : : kAny : <nl> + return InterpreterPushArgsThenCall ( ) ; <nl> + } <nl> } else { <nl> - return InterpreterPushArgsAndTailCall ( ) ; <nl> + CHECK_EQ ( receiver_mode , ConvertReceiverMode : : kAny ) ; <nl> + return InterpreterPushArgsThenTailCall ( ) ; <nl> } <nl> } <nl> UNREACHABLE ( ) ; <nl> return Handle < Code > : : null ( ) ; <nl> } <nl> <nl> - Handle < Code > Builtins : : InterpreterPushArgsAndConstruct ( <nl> + Handle < Code > Builtins : : InterpreterPushArgsThenConstruct ( <nl> InterpreterPushArgsMode mode ) { <nl> switch ( mode ) { <nl> case InterpreterPushArgsMode : : kJSFunction : <nl> - return InterpreterPushArgsAndConstructFunction ( ) ; <nl> + return InterpreterPushArgsThenConstructFunction ( ) ; <nl> case InterpreterPushArgsMode : : kWithFinalSpread : <nl> - return InterpreterPushArgsAndConstructWithFinalSpread ( ) ; <nl> + return InterpreterPushArgsThenConstructWithFinalSpread ( ) ; <nl> case InterpreterPushArgsMode : : kOther : <nl> - return InterpreterPushArgsAndConstruct ( ) ; <nl> + return InterpreterPushArgsThenConstruct ( ) ; <nl> } <nl> UNREACHABLE ( ) ; <nl> return Handle < Code > : : null ( ) ; <nl> mmm a / src / builtins / builtins . h <nl> ppp b / src / builtins / builtins . h <nl> class Builtins { <nl> Handle < Code > NonPrimitiveToPrimitive ( <nl> ToPrimitiveHint hint = ToPrimitiveHint : : kDefault ) ; <nl> Handle < Code > OrdinaryToPrimitive ( OrdinaryToPrimitiveHint hint ) ; <nl> - Handle < Code > InterpreterPushArgsAndCall ( TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) ; <nl> - Handle < Code > InterpreterPushArgsAndConstruct ( InterpreterPushArgsMode mode ) ; <nl> + Handle < Code > InterpreterPushArgsThenCall ( ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , <nl> + InterpreterPushArgsMode mode ) ; <nl> + Handle < Code > InterpreterPushArgsThenConstruct ( InterpreterPushArgsMode mode ) ; <nl> Handle < Code > NewFunctionContext ( ScopeType scope_type ) ; <nl> Handle < Code > NewCloneShallowArray ( AllocationSiteMode allocation_mode ) ; <nl> Handle < Code > NewCloneShallowObject ( int length ) ; <nl> class Builtins { <nl> static void Generate_CallForwardVarargs ( MacroAssembler * masm , <nl> Handle < Code > code ) ; <nl> <nl> - static void Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) ; <nl> + static void Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) ; <nl> <nl> - static void Generate_InterpreterPushArgsAndConstructImpl ( <nl> + static void Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) ; <nl> <nl> # define DECLARE_ASM ( Name , . . . ) \ <nl> mmm a / src / builtins / ia32 / builtins - ia32 . cc <nl> ppp b / src / builtins / ia32 / builtins - ia32 . cc <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - eax : the number of arguments ( not including the receiver ) <nl> / / - - ebx : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> / / Pop return address to allow tail - call after pushing arguments . <nl> __ Pop ( edx ) ; <nl> <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ sub ( ecx , Immediate ( 1 ) ) ; / / Subtract one for receiver . <nl> + } <nl> + <nl> / / Find the address of the last argument . <nl> __ shl ( ecx , kPointerSizeLog2 ) ; <nl> __ neg ( ecx ) ; <nl> namespace { <nl> / / This function modified start_addr , and only reads the contents of num_args <nl> / / register . scratch1 and scratch2 are used as temporary registers . Their <nl> / / original values are restored after the use . <nl> - void Generate_InterpreterPushArgsAndReturnAddress ( <nl> + void Generate_InterpreterPushZeroAndArgsAndReturnAddress ( <nl> MacroAssembler * masm , Register num_args , Register start_addr , <nl> - Register scratch1 , Register scratch2 , bool receiver_in_args , <nl> - int num_slots_above_ret_addr , Label * stack_overflow ) { <nl> + Register scratch1 , Register scratch2 , int num_slots_above_ret_addr , <nl> + Label * stack_overflow ) { <nl> / / We have to move return address and the temporary registers above it <nl> / / before we can copy arguments onto the stack . To achieve this : <nl> / / Step 1 : Increment the stack pointer by num_args + 1 ( for receiver ) . <nl> void Generate_InterpreterPushArgsAndReturnAddress ( <nl> / / | | | return addr | ( 2 ) <nl> / / | | | arg N | ( 3 ) <nl> / / | scratch1 | < - - esp | . . . . | <nl> - / / | . . . . | | arg 0 | <nl> + / / | . . . . | | arg 1 | <nl> / / | scratch - n | | arg 0 | <nl> / / | return addr | | receiver slot | <nl> <nl> void Generate_InterpreterPushArgsAndReturnAddress ( <nl> } <nl> <nl> / / Step 3 copy arguments to correct locations . <nl> - if ( receiver_in_args ) { <nl> - __ mov ( scratch1 , num_args ) ; <nl> - __ add ( scratch1 , Immediate ( 1 ) ) ; <nl> - } else { <nl> - / / Slot meant for receiver contains return address . Reset it so that <nl> - / / we will not incorrectly interpret return address as an object . <nl> - __ mov ( Operand ( esp , num_args , times_pointer_size , <nl> - ( num_slots_above_ret_addr + 1 ) * kPointerSize ) , <nl> - Immediate ( 0 ) ) ; <nl> - __ mov ( scratch1 , num_args ) ; <nl> - } <nl> + / / Slot meant for receiver contains return address . Reset it so that <nl> + / / we will not incorrectly interpret return address as an object . <nl> + __ mov ( Operand ( esp , num_args , times_pointer_size , <nl> + ( num_slots_above_ret_addr + 1 ) * kPointerSize ) , <nl> + Immediate ( 0 ) ) ; <nl> + __ mov ( scratch1 , num_args ) ; <nl> <nl> Label loop_header , loop_check ; <nl> __ jmp ( & loop_check ) ; <nl> void Generate_InterpreterPushArgsAndReturnAddress ( <nl> } / / end anonymous namespace <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - eax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> / / Push arguments and move return address to the top of stack . <nl> / / The eax register is readonly . The ecx register will be modified . The edx <nl> / / and edi registers will be modified but restored to their original values . <nl> - Generate_InterpreterPushArgsAndReturnAddress ( masm , eax , ecx , edx , edi , false , <nl> - 2 , & stack_overflow ) ; <nl> + Generate_InterpreterPushZeroAndArgsAndReturnAddress ( masm , eax , ecx , edx , edi , <nl> + 2 , & stack_overflow ) ; <nl> <nl> / / Restore edi and edx <nl> __ Pop ( edx ) ; <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - eax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / Push arguments and move return address to the top of stack . <nl> / / The eax register is readonly . The ecx register will be modified . The edx <nl> / / and edi registers will be modified but restored to their original values . <nl> - Generate_InterpreterPushArgsAndReturnAddress ( masm , eax , ecx , edx , edi , true , <nl> - 1 , & stack_overflow ) ; <nl> + Generate_InterpreterPushZeroAndArgsAndReturnAddress ( masm , eax , ecx , edx , edi , <nl> + 1 , & stack_overflow ) ; <nl> <nl> / / Restore edx . <nl> __ Pop ( edx ) ; <nl> mmm a / src / builtins / mips / builtins - mips . cc <nl> ppp b / src / builtins / mips / builtins - mips . cc <nl> static void Generate_StackOverflowCheck ( MacroAssembler * masm , Register num_args , <nl> <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> Register num_args , Register index , <nl> - Register scratch , Register scratch2 , <nl> - Label * stack_overflow ) { <nl> - Generate_StackOverflowCheck ( masm , num_args , scratch , scratch2 , <nl> - stack_overflow ) ; <nl> - <nl> + Register scratch , Register scratch2 ) { <nl> / / Find the address of the last argument . <nl> __ mov ( scratch2 , num_args ) ; <nl> __ sll ( scratch2 , scratch2 , kPointerSizeLog2 ) ; <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : the number of arguments ( not including the receiver ) <nl> / / - - a2 : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> <nl> __ Addu ( t0 , a0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> <nl> + Generate_StackOverflowCheck ( masm , t0 , t4 , t1 , & stack_overflow ) ; <nl> + <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ mov ( t0 , a0 ) ; / / No receiver . <nl> + } <nl> + <nl> / / This function modifies a2 , t4 and t1 . <nl> - Generate_InterpreterPushArgs ( masm , t0 , a2 , t4 , t1 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , t0 , a2 , t4 , t1 ) ; <nl> <nl> / / Call the target . <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> / / Push a slot for the receiver . <nl> __ push ( zero_reg ) ; <nl> <nl> + Generate_StackOverflowCheck ( masm , a0 , t1 , t0 , & stack_overflow ) ; <nl> + <nl> / / This function modified t4 , t1 and t0 . <nl> - Generate_InterpreterPushArgs ( masm , a0 , t4 , t1 , t0 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , a0 , t4 , t1 , t0 ) ; <nl> <nl> __ AssertUndefinedOrAllocationSite ( a2 , t0 ) ; <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Label stack_overflow ; <nl> <nl> - __ Addu ( t0 , a0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> + / / Push a slot for the receiver . <nl> + __ push ( zero_reg ) ; <nl> + <nl> + Generate_StackOverflowCheck ( masm , a0 , t1 , t4 , & stack_overflow ) ; <nl> <nl> - / / This function modifies a3 , t4 , and t1 . <nl> - Generate_InterpreterPushArgs ( masm , t0 , a3 , t1 , t4 , & stack_overflow ) ; <nl> + / / This function modifies a3 , t1 , and t4 . <nl> + Generate_InterpreterPushArgs ( masm , a0 , a3 , t1 , t4 ) ; <nl> <nl> / / ArrayConstructor stub expects constructor in a3 . Set it here . <nl> __ mov ( a3 , a1 ) ; <nl> mmm a / src / builtins / mips64 / builtins - mips64 . cc <nl> ppp b / src / builtins / mips64 / builtins - mips64 . cc <nl> static void Generate_StackOverflowCheck ( MacroAssembler * masm , Register num_args , <nl> <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> Register num_args , Register index , <nl> - Register scratch , Register scratch2 , <nl> - Label * stack_overflow ) { <nl> - / / Generate_StackOverflowCheck ( masm , num_args , scratch , scratch2 , <nl> - / / stack_overflow ) ; <nl> - <nl> + Register scratch , Register scratch2 ) { <nl> / / Find the address of the last argument . <nl> __ mov ( scratch2 , num_args ) ; <nl> __ dsll ( scratch2 , scratch2 , kPointerSizeLog2 ) ; <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : the number of arguments ( not including the receiver ) <nl> / / - - a2 : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> <nl> __ Daddu ( a3 , a0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ Dsubu ( a3 , a3 , Operand ( 1 ) ) ; / / Subtract one for receiver . <nl> + } <nl> + <nl> + Generate_StackOverflowCheck ( masm , a3 , a4 , t0 , & stack_overflow ) ; <nl> + <nl> / / This function modifies a2 , t0 and a4 . <nl> - Generate_InterpreterPushArgs ( masm , a3 , a2 , a4 , t0 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , a3 , a2 , a4 , t0 ) ; <nl> <nl> / / Call the target . <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> / / Push a slot for the receiver . <nl> __ push ( zero_reg ) ; <nl> <nl> + Generate_StackOverflowCheck ( masm , a0 , a5 , t0 , & stack_overflow ) ; <nl> + <nl> / / This function modifies t0 , a4 and a5 . <nl> - Generate_InterpreterPushArgs ( masm , a0 , a4 , a5 , t0 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , a0 , a4 , a5 , t0 ) ; <nl> <nl> __ AssertUndefinedOrAllocationSite ( a2 , t0 ) ; <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - a0 : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Label stack_overflow ; <nl> <nl> - __ Daddu ( a4 , a0 , Operand ( 1 ) ) ; / / Add one for receiver . <nl> + / / Push a slot for the receiver . <nl> + __ push ( zero_reg ) ; <nl> + <nl> + Generate_StackOverflowCheck ( masm , a4 , a5 , a6 , & stack_overflow ) ; <nl> <nl> / / This function modifies a3 , a5 and a6 . <nl> - Generate_InterpreterPushArgs ( masm , a4 , a3 , a5 , a6 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgs ( masm , a4 , a3 , a5 , a6 ) ; <nl> <nl> / / ArrayConstructor stub expects constructor in a3 . Set it here . <nl> __ mov ( a3 , a1 ) ; <nl> mmm a / src / builtins / ppc / builtins - ppc . cc <nl> ppp b / src / builtins / ppc / builtins - ppc . cc <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> MacroAssembler * masm , TailCallMode tail_call_mode , <nl> InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r3 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r3 : argument count ( not including receiver ) <nl> mmm a / src / builtins / s390 / builtins - s390 . cc <nl> ppp b / src / builtins / s390 / builtins - s390 . cc <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> MacroAssembler * masm , TailCallMode tail_call_mode , <nl> InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r2 : argument count ( not including receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - r2 : argument count ( not including receiver ) <nl> mmm a / src / builtins / x64 / builtins - x64 . cc <nl> ppp b / src / builtins / x64 / builtins - x64 . cc <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> - MacroAssembler * masm , TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> + MacroAssembler * masm , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - rax : the number of arguments ( not including the receiver ) <nl> / / - - rbx : the address of the first argument to be pushed . Subsequent <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> / / Pop return address to allow tail - call after pushing arguments . <nl> __ PopReturnAddressTo ( kScratchRegister ) ; <nl> <nl> + / / Push " undefined " as the receiver arg if we need to . <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + __ PushRoot ( Heap : : kUndefinedValueRootIndex ) ; <nl> + __ subp ( rcx , Immediate ( 1 ) ) ; / / Subtract one for receiver . <nl> + } <nl> + <nl> / / rbx and rdx will be modified . <nl> Generate_InterpreterPushArgs ( masm , rcx , rbx , rdx ) ; <nl> <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> __ PushReturnAddressFrom ( kScratchRegister ) ; / / Re - push return address . <nl> <nl> if ( mode = = InterpreterPushArgsMode : : kJSFunction ) { <nl> - __ Jump ( masm - > isolate ( ) - > builtins ( ) - > CallFunction ( ConvertReceiverMode : : kAny , <nl> + __ Jump ( masm - > isolate ( ) - > builtins ( ) - > CallFunction ( receiver_mode , <nl> tail_call_mode ) , <nl> RelocInfo : : CODE_TARGET ) ; <nl> } else if ( mode = = InterpreterPushArgsMode : : kWithFinalSpread ) { <nl> __ Jump ( masm - > isolate ( ) - > builtins ( ) - > CallWithSpread ( ) , <nl> RelocInfo : : CODE_TARGET ) ; <nl> } else { <nl> - __ Jump ( masm - > isolate ( ) - > builtins ( ) - > Call ( ConvertReceiverMode : : kAny , <nl> - tail_call_mode ) , <nl> + __ Jump ( masm - > isolate ( ) - > builtins ( ) - > Call ( receiver_mode , tail_call_mode ) , <nl> RelocInfo : : CODE_TARGET ) ; <nl> } <nl> <nl> void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - rax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - rax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> <nl> / / Number of values to be pushed . <nl> __ Move ( r8 , rax ) ; <nl> - __ addp ( r8 , Immediate ( 1 ) ) ; / / Add one for receiver . <nl> <nl> / / Add a stack check before pushing arguments . <nl> Generate_StackOverflowCheck ( masm , r8 , rdi , & stack_overflow ) ; <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / Pop return address to allow tail - call after pushing arguments . <nl> __ PopReturnAddressTo ( kScratchRegister ) ; <nl> <nl> + / / Push slot for the receiver to be constructed . <nl> + __ Push ( Immediate ( 0 ) ) ; <nl> + <nl> / / rcx and rdi will be modified . <nl> Generate_InterpreterPushArgs ( masm , r8 , rcx , rdi ) ; <nl> <nl> mmm a / src / builtins / x87 / builtins - x87 . cc <nl> ppp b / src / builtins / x87 / builtins - x87 . cc <nl> static void Generate_InterpreterPushArgs ( MacroAssembler * masm , <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndCallImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenCallImpl ( <nl> MacroAssembler * masm , TailCallMode tail_call_mode , <nl> InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> namespace { <nl> / / This function modified start_addr , and only reads the contents of num_args <nl> / / register . scratch1 and scratch2 are used as temporary registers . Their <nl> / / original values are restored after the use . <nl> - void Generate_InterpreterPushArgsAndReturnAddress ( <nl> + void Generate_InterpreterPushArgsThenReturnAddress ( <nl> MacroAssembler * masm , Register num_args , Register start_addr , <nl> Register scratch1 , Register scratch2 , bool receiver_in_args , <nl> int num_slots_above_ret_addr , Label * stack_overflow ) { <nl> void Generate_InterpreterPushArgsAndReturnAddress ( <nl> } / / end anonymous namespace <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructImpl ( <nl> MacroAssembler * masm , InterpreterPushArgsMode mode ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - eax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> / / Push arguments and move return address to the top of stack . <nl> / / The eax register is readonly . The ecx register will be modified . The edx <nl> / / and edi registers will be modified but restored to their original values . <nl> - Generate_InterpreterPushArgsAndReturnAddress ( masm , eax , ecx , edx , edi , false , <nl> - 2 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgsThenReturnAddress ( masm , eax , ecx , edx , edi , false , <nl> + 2 , & stack_overflow ) ; <nl> <nl> / / Restore edi and edx <nl> __ Pop ( edx ) ; <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructImpl ( <nl> } <nl> <nl> / / static <nl> - void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> + void Builtins : : Generate_InterpreterPushArgsThenConstructArray ( <nl> MacroAssembler * masm ) { <nl> / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> / / - - eax : the number of arguments ( not including the receiver ) <nl> void Builtins : : Generate_InterpreterPushArgsAndConstructArray ( <nl> / / Push arguments and move return address to the top of stack . <nl> / / The eax register is readonly . The ecx register will be modified . The edx <nl> / / and edi registers will be modified but restored to their original values . <nl> - Generate_InterpreterPushArgsAndReturnAddress ( masm , eax , ecx , edx , edi , true , <nl> - 1 , & stack_overflow ) ; <nl> + Generate_InterpreterPushArgsThenReturnAddress ( masm , eax , ecx , edx , edi , true , <nl> + 1 , & stack_overflow ) ; <nl> <nl> / / Restore edx . <nl> __ Pop ( edx ) ; <nl> mmm a / src / code - factory . cc <nl> ppp b / src / code - factory . cc <nl> Callable CodeFactory : : ConstructFunction ( Isolate * isolate ) { <nl> } <nl> <nl> / / static <nl> - Callable CodeFactory : : InterpreterPushArgsAndCall ( Isolate * isolate , <nl> - TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) { <nl> - return Callable ( <nl> - isolate - > builtins ( ) - > InterpreterPushArgsAndCall ( tail_call_mode , mode ) , <nl> - InterpreterPushArgsAndCallDescriptor ( isolate ) ) ; <nl> + Callable CodeFactory : : InterpreterPushArgsThenCall ( <nl> + Isolate * isolate , ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , InterpreterPushArgsMode mode ) { <nl> + return Callable ( isolate - > builtins ( ) - > InterpreterPushArgsThenCall ( <nl> + receiver_mode , tail_call_mode , mode ) , <nl> + InterpreterPushArgsThenCallDescriptor ( isolate ) ) ; <nl> } <nl> <nl> / / static <nl> - Callable CodeFactory : : InterpreterPushArgsAndConstruct ( <nl> + Callable CodeFactory : : InterpreterPushArgsThenConstruct ( <nl> Isolate * isolate , InterpreterPushArgsMode mode ) { <nl> - return Callable ( isolate - > builtins ( ) - > InterpreterPushArgsAndConstruct ( mode ) , <nl> - InterpreterPushArgsAndConstructDescriptor ( isolate ) ) ; <nl> + return Callable ( isolate - > builtins ( ) - > InterpreterPushArgsThenConstruct ( mode ) , <nl> + InterpreterPushArgsThenConstructDescriptor ( isolate ) ) ; <nl> } <nl> <nl> / / static <nl> - Callable CodeFactory : : InterpreterPushArgsAndConstructArray ( Isolate * isolate ) { <nl> - return Callable ( isolate - > builtins ( ) - > InterpreterPushArgsAndConstructArray ( ) , <nl> - InterpreterPushArgsAndConstructArrayDescriptor ( isolate ) ) ; <nl> + Callable CodeFactory : : InterpreterPushArgsThenConstructArray ( Isolate * isolate ) { <nl> + return Callable ( isolate - > builtins ( ) - > InterpreterPushArgsThenConstructArray ( ) , <nl> + InterpreterPushArgsThenConstructArrayDescriptor ( isolate ) ) ; <nl> } <nl> <nl> / / static <nl> mmm a / src / code - factory . h <nl> ppp b / src / code - factory . h <nl> class V8_EXPORT_PRIVATE CodeFactory final { <nl> static Callable HasProperty ( Isolate * isolate ) ; <nl> static Callable ForInFilter ( Isolate * isolate ) ; <nl> <nl> - static Callable InterpreterPushArgsAndCall ( Isolate * isolate , <nl> - TailCallMode tail_call_mode , <nl> - InterpreterPushArgsMode mode ) ; <nl> - static Callable InterpreterPushArgsAndConstruct ( Isolate * isolate , <nl> - InterpreterPushArgsMode mode ) ; <nl> - static Callable InterpreterPushArgsAndConstructArray ( Isolate * isolate ) ; <nl> + static Callable InterpreterPushArgsThenCall ( Isolate * isolate , <nl> + ConvertReceiverMode receiver_mode , <nl> + TailCallMode tail_call_mode , <nl> + InterpreterPushArgsMode mode ) ; <nl> + static Callable InterpreterPushArgsThenConstruct ( <nl> + Isolate * isolate , InterpreterPushArgsMode mode ) ; <nl> + static Callable InterpreterPushArgsThenConstructArray ( Isolate * isolate ) ; <nl> static Callable InterpreterCEntry ( Isolate * isolate , int result_size = 1 ) ; <nl> static Callable InterpreterOnStackReplacement ( Isolate * isolate ) ; <nl> <nl> mmm a / src / compiler / bytecode - graph - builder . cc <nl> ppp b / src / compiler / bytecode - graph - builder . cc <nl> void BytecodeGraphBuilder : : VisitCreateObjectLiteral ( ) { <nl> } <nl> <nl> Node * const * BytecodeGraphBuilder : : GetCallArgumentsFromRegister ( <nl> - Node * callee , interpreter : : Register receiver , size_t arity ) { <nl> - Node * * all = local_zone ( ) - > NewArray < Node * > ( static_cast < int > ( arity ) ) ; <nl> + Node * callee , Node * receiver , interpreter : : Register first_arg , <nl> + int arg_count ) { <nl> + / / The arity of the Call node - - includes the callee , receiver and function <nl> + / / arguments . <nl> + int arity = 2 + arg_count ; <nl> + <nl> + Node * * all = local_zone ( ) - > NewArray < Node * > ( static_cast < size_t > ( arity ) ) ; <nl> + <nl> all [ 0 ] = callee ; <nl> - all [ 1 ] = environment ( ) - > LookupRegister ( receiver ) ; <nl> - int receiver_index = receiver . index ( ) ; <nl> - for ( int i = 2 ; i < static_cast < int > ( arity ) ; + + i ) { <nl> - all [ i ] = environment ( ) - > LookupRegister ( <nl> - interpreter : : Register ( receiver_index + i - 1 ) ) ; <nl> + all [ 1 ] = receiver ; <nl> + <nl> + / / The function arguments are in consecutive registers . <nl> + int arg_base = first_arg . index ( ) ; <nl> + for ( int i = 0 ; i < arg_count ; + + i ) { <nl> + all [ 2 + i ] = <nl> + environment ( ) - > LookupRegister ( interpreter : : Register ( arg_base + i ) ) ; <nl> } <nl> + <nl> return all ; <nl> } <nl> <nl> Node * BytecodeGraphBuilder : : ProcessCallArguments ( const Operator * call_op , <nl> Node * const * args , <nl> - size_t arg_count ) { <nl> - return MakeNode ( call_op , static_cast < int > ( arg_count ) , args , false ) ; <nl> + int arg_count ) { <nl> + return MakeNode ( call_op , arg_count , args , false ) ; <nl> } <nl> <nl> Node * BytecodeGraphBuilder : : ProcessCallArguments ( const Operator * call_op , <nl> Node * callee , <nl> interpreter : : Register receiver , <nl> - size_t arg_count ) { <nl> - return ProcessCallArguments ( <nl> - call_op , GetCallArgumentsFromRegister ( callee , receiver , arg_count ) , <nl> - arg_count ) ; <nl> + size_t reg_count ) { <nl> + Node * receiver_node = environment ( ) - > LookupRegister ( receiver ) ; <nl> + / / The receiver is followed by the arguments in the consecutive registers . <nl> + DCHECK_GE ( reg_count , 1 ) ; <nl> + interpreter : : Register first_arg = interpreter : : Register ( receiver . index ( ) + 1 ) ; <nl> + int arg_count = static_cast < int > ( reg_count ) - 1 ; <nl> + <nl> + Node * const * call_args = <nl> + GetCallArgumentsFromRegister ( callee , receiver_node , first_arg , arg_count ) ; <nl> + return ProcessCallArguments ( call_op , call_args , 2 + arg_count ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : BuildCall ( TailCallMode tail_call_mode , <nl> - ConvertReceiverMode receiver_hint , <nl> + ConvertReceiverMode receiver_mode , <nl> Node * const * args , size_t arg_count , <nl> int slot_id ) { <nl> + DCHECK_EQ ( interpreter : : Bytecodes : : GetReceiverMode ( <nl> + bytecode_iterator ( ) . current_bytecode ( ) ) , <nl> + receiver_mode ) ; <nl> PrepareEagerCheckpoint ( ) ; <nl> <nl> / / Slot index of 0 is used indicate no feedback slot is available . Assert <nl> void BytecodeGraphBuilder : : BuildCall ( TailCallMode tail_call_mode , <nl> <nl> float const frequency = ComputeCallFrequency ( slot_id ) ; <nl> const Operator * call = javascript ( ) - > Call ( arg_count , frequency , feedback , <nl> - receiver_hint , tail_call_mode ) ; <nl> - Node * value = ProcessCallArguments ( call , args , arg_count ) ; <nl> + receiver_mode , tail_call_mode ) ; <nl> + Node * value = ProcessCallArguments ( call , args , static_cast < int > ( arg_count ) ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : BuildCallVarArgs ( TailCallMode tail_call_mode , <nl> - ConvertReceiverMode receiver_hint ) { <nl> + ConvertReceiverMode receiver_mode ) { <nl> + DCHECK_EQ ( interpreter : : Bytecodes : : GetReceiverMode ( <nl> + bytecode_iterator ( ) . current_bytecode ( ) ) , <nl> + receiver_mode ) ; <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> - interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register first_reg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 3 ) ; <nl> - BuildCall ( tail_call_mode , receiver_hint , <nl> - GetCallArgumentsFromRegister ( callee , receiver , arg_count + 1 ) , <nl> - arg_count + 1 , slot_id ) ; <nl> + <nl> + Node * receiver_node ; <nl> + interpreter : : Register first_arg ; <nl> + int arg_count ; <nl> + <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + / / The receiver is implicit ( and undefined ) , the arguments are in <nl> + / / consecutive registers . <nl> + receiver_node = jsgraph ( ) - > UndefinedConstant ( ) ; <nl> + first_arg = first_reg ; <nl> + arg_count = static_cast < int > ( reg_count ) ; <nl> + } else { <nl> + / / The receiver is the first register , followed by the arguments in the <nl> + / / consecutive registers . <nl> + DCHECK_GE ( reg_count , 1 ) ; <nl> + receiver_node = environment ( ) - > LookupRegister ( first_reg ) ; <nl> + first_arg = interpreter : : Register ( first_reg . index ( ) + 1 ) ; <nl> + arg_count = static_cast < int > ( reg_count ) - 1 ; <nl> + } <nl> + <nl> + Node * const * call_args = <nl> + GetCallArgumentsFromRegister ( callee , receiver_node , first_arg , arg_count ) ; <nl> + BuildCall ( tail_call_mode , receiver_mode , call_args , <nl> + static_cast < size_t > ( 2 + arg_count ) , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCall ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallAnyReceiver ( ) { <nl> BuildCallVarArgs ( TailCallMode : : kDisallow , ConvertReceiverMode : : kAny ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCall0 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallProperty ( ) { <nl> + BuildCallVarArgs ( TailCallMode : : kDisallow , <nl> + ConvertReceiverMode : : kNotNullOrUndefined ) ; <nl> + } <nl> + <nl> + void BytecodeGraphBuilder : : VisitCallProperty0 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> Node * receiver = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 2 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kAny , <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> { callee , receiver } , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCall1 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallProperty1 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> Node * receiver = <nl> void BytecodeGraphBuilder : : VisitCall1 ( ) { <nl> Node * arg0 = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 2 ) ) ; <nl> int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 3 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kAny , <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> { callee , receiver , arg0 } , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCall2 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallProperty2 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> Node * receiver = <nl> void BytecodeGraphBuilder : : VisitCall2 ( ) { <nl> Node * arg1 = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 3 ) ) ; <nl> int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 4 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kAny , <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> { callee , receiver , arg0 , arg1 } , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCallProperty ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallUndefinedReceiver ( ) { <nl> BuildCallVarArgs ( TailCallMode : : kDisallow , <nl> - ConvertReceiverMode : : kNotNullOrUndefined ) ; <nl> + ConvertReceiverMode : : kNullOrUndefined ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCallProperty0 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallUndefinedReceiver0 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> - Node * receiver = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> - int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 2 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> + Node * receiver = jsgraph ( ) - > UndefinedConstant ( ) ; <nl> + int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 1 ) ; <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNullOrUndefined , <nl> { callee , receiver } , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCallProperty1 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallUndefinedReceiver1 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> - Node * receiver = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> + Node * receiver = jsgraph ( ) - > UndefinedConstant ( ) ; <nl> Node * arg0 = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 2 ) ) ; <nl> - int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 3 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> + environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> + int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 2 ) ; <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNullOrUndefined , <nl> { callee , receiver , arg0 } , slot_id ) ; <nl> } <nl> <nl> - void BytecodeGraphBuilder : : VisitCallProperty2 ( ) { <nl> + void BytecodeGraphBuilder : : VisitCallUndefinedReceiver2 ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> - Node * receiver = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> + Node * receiver = jsgraph ( ) - > UndefinedConstant ( ) ; <nl> Node * arg0 = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 2 ) ) ; <nl> + environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ) ; <nl> Node * arg1 = <nl> - environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 3 ) ) ; <nl> - int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 4 ) ; <nl> - BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNotNullOrUndefined , <nl> + environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 2 ) ) ; <nl> + int const slot_id = bytecode_iterator ( ) . GetIndexOperand ( 3 ) ; <nl> + BuildCall ( TailCallMode : : kDisallow , ConvertReceiverMode : : kNullOrUndefined , <nl> { callee , receiver , arg0 , arg1 } , slot_id ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitCallWithSpread ( ) { <nl> Node * callee = <nl> environment ( ) - > LookupRegister ( bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ) ; <nl> interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> const Operator * call = <nl> - javascript ( ) - > CallWithSpread ( static_cast < int > ( arg_count + 1 ) ) ; <nl> + javascript ( ) - > CallWithSpread ( static_cast < int > ( reg_count + 1 ) ) ; <nl> <nl> - Node * value = ProcessCallArguments ( call , callee , receiver , arg_count + 1 ) ; <nl> + Node * value = ProcessCallArguments ( call , callee , receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitCallJSRuntime ( ) { <nl> Node * callee = <nl> BuildLoadNativeContextField ( bytecode_iterator ( ) . GetIndexOperand ( 0 ) ) ; <nl> interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> <nl> / / Create node to perform the JS runtime call . <nl> - const Operator * call = javascript ( ) - > Call ( arg_count + 1 ) ; <nl> - Node * value = ProcessCallArguments ( call , callee , receiver , arg_count + 1 ) ; <nl> + const Operator * call = javascript ( ) - > Call ( reg_count + 1 ) ; <nl> + Node * value = ProcessCallArguments ( call , callee , receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> Node * BytecodeGraphBuilder : : ProcessCallRuntimeArguments ( <nl> - const Operator * call_runtime_op , interpreter : : Register first_arg , <nl> - size_t arity ) { <nl> - Node * * all = local_zone ( ) - > NewArray < Node * > ( arity ) ; <nl> - int first_arg_index = first_arg . index ( ) ; <nl> - for ( int i = 0 ; i < static_cast < int > ( arity ) ; + + i ) { <nl> + const Operator * call_runtime_op , interpreter : : Register receiver , <nl> + size_t reg_count ) { <nl> + int arg_count = static_cast < int > ( reg_count ) ; <nl> + / / arity is args . <nl> + int arity = arg_count ; <nl> + Node * * all = local_zone ( ) - > NewArray < Node * > ( static_cast < size_t > ( arity ) ) ; <nl> + int first_arg_index = receiver . index ( ) ; <nl> + for ( int i = 0 ; i < static_cast < int > ( reg_count ) ; + + i ) { <nl> all [ i ] = environment ( ) - > LookupRegister ( <nl> interpreter : : Register ( first_arg_index + i ) ) ; <nl> } <nl> - Node * value = MakeNode ( call_runtime_op , static_cast < int > ( arity ) , all , false ) ; <nl> + Node * value = MakeNode ( call_runtime_op , arity , all , false ) ; <nl> return value ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitCallRuntime ( ) { <nl> PrepareEagerCheckpoint ( ) ; <nl> Runtime : : FunctionId functionId = bytecode_iterator ( ) . GetRuntimeIdOperand ( 0 ) ; <nl> - interpreter : : Register first_arg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> <nl> / / Create node to perform the runtime call . <nl> - const Operator * call = javascript ( ) - > CallRuntime ( functionId , arg_count ) ; <nl> - Node * value = ProcessCallRuntimeArguments ( call , first_arg , arg_count ) ; <nl> + const Operator * call = javascript ( ) - > CallRuntime ( functionId , reg_count ) ; <nl> + Node * value = ProcessCallRuntimeArguments ( call , receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitCallRuntimeForPair ( ) { <nl> PrepareEagerCheckpoint ( ) ; <nl> Runtime : : FunctionId functionId = bytecode_iterator ( ) . GetRuntimeIdOperand ( 0 ) ; <nl> - interpreter : : Register first_arg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> interpreter : : Register first_return = <nl> bytecode_iterator ( ) . GetRegisterOperand ( 3 ) ; <nl> <nl> / / Create node to perform the runtime call . <nl> - const Operator * call = javascript ( ) - > CallRuntime ( functionId , arg_count ) ; <nl> - Node * return_pair = ProcessCallRuntimeArguments ( call , first_arg , arg_count ) ; <nl> + const Operator * call = javascript ( ) - > CallRuntime ( functionId , reg_count ) ; <nl> + Node * return_pair = ProcessCallRuntimeArguments ( call , receiver , reg_count ) ; <nl> environment ( ) - > BindRegistersToProjections ( first_return , return_pair , <nl> Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> Node * BytecodeGraphBuilder : : ProcessConstructWithSpreadArguments ( <nl> const Operator * op , Node * callee , Node * new_target , <nl> - interpreter : : Register first_arg , size_t arity ) { <nl> - Node * * all = local_zone ( ) - > NewArray < Node * > ( arity ) ; <nl> + interpreter : : Register receiver , size_t reg_count ) { <nl> + int arg_count = static_cast < int > ( reg_count ) ; <nl> + / / arity is args + callee and new target . <nl> + int arity = arg_count + 2 ; <nl> + Node * * all = local_zone ( ) - > NewArray < Node * > ( static_cast < size_t > ( arity ) ) ; <nl> all [ 0 ] = callee ; <nl> - int first_arg_index = first_arg . index ( ) ; <nl> - for ( int i = 1 ; i < static_cast < int > ( arity ) - 1 ; + + i ) { <nl> - all [ i ] = environment ( ) - > LookupRegister ( <nl> - interpreter : : Register ( first_arg_index + i - 1 ) ) ; <nl> + int first_arg_index = receiver . index ( ) ; <nl> + for ( int i = 0 ; i < arg_count ; + + i ) { <nl> + all [ 1 + i ] = environment ( ) - > LookupRegister ( <nl> + interpreter : : Register ( first_arg_index + i ) ) ; <nl> } <nl> all [ arity - 1 ] = new_target ; <nl> - Node * value = MakeNode ( op , static_cast < int > ( arity ) , all , false ) ; <nl> + Node * value = MakeNode ( op , arity , all , false ) ; <nl> return value ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitConstructWithSpread ( ) { <nl> PrepareEagerCheckpoint ( ) ; <nl> interpreter : : Register callee_reg = bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ; <nl> - interpreter : : Register first_arg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> <nl> Node * new_target = environment ( ) - > LookupAccumulator ( ) ; <nl> Node * callee = environment ( ) - > LookupRegister ( callee_reg ) ; <nl> <nl> const Operator * op = <nl> - javascript ( ) - > ConstructWithSpread ( static_cast < int > ( arg_count ) + 2 ) ; <nl> + javascript ( ) - > ConstructWithSpread ( static_cast < uint32_t > ( reg_count + 2 ) ) ; <nl> Node * value = ProcessConstructWithSpreadArguments ( op , callee , new_target , <nl> - first_arg , arg_count + 2 ) ; <nl> + receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitInvokeIntrinsic ( ) { <nl> PrepareEagerCheckpoint ( ) ; <nl> Runtime : : FunctionId functionId = bytecode_iterator ( ) . GetIntrinsicIdOperand ( 0 ) ; <nl> - interpreter : : Register first_arg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> <nl> / / Create node to perform the runtime call . Turbofan will take care of the <nl> / / lowering . <nl> - const Operator * call = javascript ( ) - > CallRuntime ( functionId , arg_count ) ; <nl> - Node * value = ProcessCallRuntimeArguments ( call , first_arg , arg_count ) ; <nl> + const Operator * call = javascript ( ) - > CallRuntime ( functionId , reg_count ) ; <nl> + Node * value = ProcessCallRuntimeArguments ( call , receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> Node * BytecodeGraphBuilder : : ProcessConstructArguments ( <nl> const Operator * call_new_op , Node * callee , Node * new_target , <nl> - interpreter : : Register first_arg , size_t arity ) { <nl> - Node * * all = local_zone ( ) - > NewArray < Node * > ( arity ) ; <nl> + interpreter : : Register receiver , size_t reg_count ) { <nl> + int arg_count = static_cast < int > ( reg_count ) ; <nl> + / / arity is args + callee and new target . <nl> + int arity = arg_count + 2 ; <nl> + Node * * all = local_zone ( ) - > NewArray < Node * > ( static_cast < size_t > ( arity ) ) ; <nl> all [ 0 ] = callee ; <nl> - int first_arg_index = first_arg . index ( ) ; <nl> - for ( int i = 1 ; i < static_cast < int > ( arity ) - 1 ; + + i ) { <nl> - all [ i ] = environment ( ) - > LookupRegister ( <nl> - interpreter : : Register ( first_arg_index + i - 1 ) ) ; <nl> + int first_arg_index = receiver . index ( ) ; <nl> + for ( int i = 0 ; i < arg_count ; + + i ) { <nl> + all [ 1 + i ] = environment ( ) - > LookupRegister ( <nl> + interpreter : : Register ( first_arg_index + i ) ) ; <nl> } <nl> all [ arity - 1 ] = new_target ; <nl> - Node * value = MakeNode ( call_new_op , static_cast < int > ( arity ) , all , false ) ; <nl> + Node * value = MakeNode ( call_new_op , arity , all , false ) ; <nl> return value ; <nl> } <nl> <nl> void BytecodeGraphBuilder : : VisitConstruct ( ) { <nl> PrepareEagerCheckpoint ( ) ; <nl> interpreter : : Register callee_reg = bytecode_iterator ( ) . GetRegisterOperand ( 0 ) ; <nl> - interpreter : : Register first_arg = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> - size_t arg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> + interpreter : : Register receiver = bytecode_iterator ( ) . GetRegisterOperand ( 1 ) ; <nl> + size_t reg_count = bytecode_iterator ( ) . GetRegisterCountOperand ( 2 ) ; <nl> / / Slot index of 0 is used indicate no feedback slot is available . Assert <nl> / / the assumption that slot index 0 is never a valid feedback slot . <nl> STATIC_ASSERT ( FeedbackVector : : kReservedIndexCount > 0 ) ; <nl> void BytecodeGraphBuilder : : VisitConstruct ( ) { <nl> <nl> float const frequency = ComputeCallFrequency ( slot_id ) ; <nl> const Operator * call = javascript ( ) - > Construct ( <nl> - static_cast < int > ( arg_count ) + 2 , frequency , feedback ) ; <nl> - Node * value = ProcessConstructArguments ( call , callee , new_target , first_arg , <nl> - arg_count + 2 ) ; <nl> + static_cast < uint32_t > ( reg_count + 2 ) , frequency , feedback ) ; <nl> + Node * value = <nl> + ProcessConstructArguments ( call , callee , new_target , receiver , reg_count ) ; <nl> environment ( ) - > BindAccumulator ( value , Environment : : kAttachFrameState ) ; <nl> } <nl> <nl> mmm a / src / compiler / bytecode - graph - builder . h <nl> ppp b / src / compiler / bytecode - graph - builder . h <nl> class BytecodeGraphBuilder { <nl> <nl> Node * * EnsureInputBufferSize ( int size ) ; <nl> <nl> - Node * const * GetCallArgumentsFromRegister ( Node * callee , <nl> + Node * const * GetCallArgumentsFromRegister ( Node * callee , Node * receiver , <nl> interpreter : : Register first_arg , <nl> - size_t arity ) ; <nl> + int arg_count ) ; <nl> Node * ProcessCallArguments ( const Operator * call_op , Node * const * args , <nl> - size_t arg_count ) ; <nl> + int arg_count ) ; <nl> Node * ProcessCallArguments ( const Operator * call_op , Node * callee , <nl> - interpreter : : Register receiver , size_t arity ) ; <nl> + interpreter : : Register receiver , size_t reg_count ) ; <nl> Node * ProcessConstructArguments ( const Operator * call_new_op , Node * callee , <nl> Node * new_target , <nl> - interpreter : : Register first_arg , <nl> - size_t arity ) ; <nl> + interpreter : : Register receiver , <nl> + size_t reg_count ) ; <nl> Node * ProcessConstructWithSpreadArguments ( const Operator * op , Node * callee , <nl> Node * new_target , <nl> - interpreter : : Register first_arg , <nl> - size_t arity ) ; <nl> + interpreter : : Register receiver , <nl> + size_t reg_count ) ; <nl> Node * ProcessCallRuntimeArguments ( const Operator * call_runtime_op , <nl> - interpreter : : Register first_arg , <nl> - size_t arity ) ; <nl> + interpreter : : Register receiver , <nl> + size_t reg_count ) ; <nl> <nl> / / Prepare information for eager deoptimization . This information is carried <nl> / / by dedicated { Checkpoint } nodes that are wired into the effect chain . <nl> class BytecodeGraphBuilder { <nl> void BuildLdaLookupGlobalSlot ( TypeofMode typeof_mode ) ; <nl> void BuildStaLookupSlot ( LanguageMode language_mode ) ; <nl> void BuildCallVarArgs ( TailCallMode tail_call_mode , <nl> - ConvertReceiverMode receiver_hint ) ; <nl> - void BuildCall ( TailCallMode tail_call_mode , ConvertReceiverMode receiver_hint , <nl> + ConvertReceiverMode receiver_mode ) ; <nl> + void BuildCall ( TailCallMode tail_call_mode , ConvertReceiverMode receiver_mode , <nl> Node * const * args , size_t arg_count , int slot_id ) ; <nl> - void BuildCall ( TailCallMode tail_call_mode , ConvertReceiverMode receiver_hint , <nl> + void BuildCall ( TailCallMode tail_call_mode , ConvertReceiverMode receiver_mode , <nl> std : : initializer_list < Node * > args , int slot_id ) { <nl> - BuildCall ( tail_call_mode , receiver_hint , args . begin ( ) , args . size ( ) , <nl> + BuildCall ( tail_call_mode , receiver_mode , args . begin ( ) , args . size ( ) , <nl> slot_id ) ; <nl> } <nl> void BuildBinaryOp ( const Operator * op ) ; <nl> mmm a / src / ia32 / interface - descriptors - ia32 . cc <nl> ppp b / src / ia32 / interface - descriptors - ia32 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> edx , / / target to the call . It is checked to be Array function . <nl> mmm a / src / interface - descriptors . cc <nl> ppp b / src / interface - descriptors . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformIndependent ( <nl> machine_types ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformIndependent ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformIndependent ( <nl> CallInterfaceDescriptorData * data ) { <nl> / / kNumberOfArguments , kFirstArgument , kFunction <nl> MachineType machine_types [ ] = { MachineType : : Int32 ( ) , MachineType : : Pointer ( ) , <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformIndependent ( <nl> machine_types ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformIndependent ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformIndependent ( <nl> CallInterfaceDescriptorData * data ) { <nl> / / kNumberOfArguments , kNewTarget , kConstructor , kFeedbackElement , <nl> / / kFirstArgument <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformIndependent ( <nl> machine_types ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> InitializePlatformIndependent ( CallInterfaceDescriptorData * data ) { <nl> / / kNumberOfArguments , kFunction , kFeedbackElement , kFirstArgument <nl> MachineType machine_types [ ] = { MachineType : : Int32 ( ) , MachineType : : AnyTagged ( ) , <nl> mmm a / src / interface - descriptors . h <nl> ppp b / src / interface - descriptors . h <nl> class PlatformInterfaceDescriptor ; <nl> V ( GrowArrayElements ) \ <nl> V ( NewArgumentsElements ) \ <nl> V ( InterpreterDispatch ) \ <nl> - V ( InterpreterPushArgsAndCall ) \ <nl> - V ( InterpreterPushArgsAndConstruct ) \ <nl> - V ( InterpreterPushArgsAndConstructArray ) \ <nl> + V ( InterpreterPushArgsThenCall ) \ <nl> + V ( InterpreterPushArgsThenConstruct ) \ <nl> + V ( InterpreterPushArgsThenConstructArray ) \ <nl> V ( InterpreterCEntry ) \ <nl> V ( ResumeGenerator ) \ <nl> V ( FrameDropperTrampoline ) \ <nl> class V8_EXPORT_PRIVATE InterpreterDispatchDescriptor <nl> CallInterfaceDescriptor ) <nl> } ; <nl> <nl> - class InterpreterPushArgsAndCallDescriptor : public CallInterfaceDescriptor { <nl> + class InterpreterPushArgsThenCallDescriptor : public CallInterfaceDescriptor { <nl> public : <nl> DEFINE_PARAMETERS ( kNumberOfArguments , kFirstArgument , kFunction ) <nl> DECLARE_DESCRIPTOR_WITH_CUSTOM_FUNCTION_TYPE ( <nl> - InterpreterPushArgsAndCallDescriptor , CallInterfaceDescriptor ) <nl> + InterpreterPushArgsThenCallDescriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> - <nl> - class InterpreterPushArgsAndConstructDescriptor <nl> + class InterpreterPushArgsThenConstructDescriptor <nl> : public CallInterfaceDescriptor { <nl> public : <nl> DEFINE_PARAMETERS ( kNumberOfArguments , kNewTarget , kConstructor , <nl> kFeedbackElement , kFirstArgument ) <nl> DECLARE_DESCRIPTOR_WITH_CUSTOM_FUNCTION_TYPE ( <nl> - InterpreterPushArgsAndConstructDescriptor , CallInterfaceDescriptor ) <nl> + InterpreterPushArgsThenConstructDescriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> - class InterpreterPushArgsAndConstructArrayDescriptor <nl> + class InterpreterPushArgsThenConstructArrayDescriptor <nl> : public CallInterfaceDescriptor { <nl> public : <nl> DEFINE_PARAMETERS ( kNumberOfArguments , kFunction , kFeedbackElement , <nl> kFirstArgument ) <nl> DECLARE_DESCRIPTOR_WITH_CUSTOM_FUNCTION_TYPE ( <nl> - InterpreterPushArgsAndConstructArrayDescriptor , CallInterfaceDescriptor ) <nl> + InterpreterPushArgsThenConstructArrayDescriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> class InterpreterCEntryDescriptor : public CallInterfaceDescriptor { <nl> mmm a / src / interpreter / bytecode - array - builder . cc <nl> ppp b / src / interpreter / bytecode - array - builder . cc <nl> BytecodeArrayBuilder & BytecodeArrayBuilder : : MarkTryEnd ( int handler_id ) { <nl> return * this ; <nl> } <nl> <nl> - BytecodeArrayBuilder & BytecodeArrayBuilder : : Call ( Register callable , <nl> - RegisterList args , <nl> - int feedback_slot , <nl> - Call : : CallType call_type , <nl> - TailCallMode tail_call_mode ) { <nl> - if ( tail_call_mode = = TailCallMode : : kDisallow ) { <nl> - if ( call_type = = Call : : NAMED_PROPERTY_CALL | | <nl> - call_type = = Call : : KEYED_PROPERTY_CALL ) { <nl> - if ( args . register_count ( ) = = 1 ) { <nl> - OutputCallProperty0 ( callable , args [ 0 ] , feedback_slot ) ; <nl> - } else if ( args . register_count ( ) = = 2 ) { <nl> - OutputCallProperty1 ( callable , args [ 0 ] , args [ 1 ] , feedback_slot ) ; <nl> - } else if ( args . register_count ( ) = = 3 ) { <nl> - OutputCallProperty2 ( callable , args [ 0 ] , args [ 1 ] , args [ 2 ] , feedback_slot ) ; <nl> - } else { <nl> - OutputCallProperty ( callable , args , args . register_count ( ) , <nl> - feedback_slot ) ; <nl> - } <nl> - } else { <nl> - if ( args . register_count ( ) = = 1 ) { <nl> - OutputCall0 ( callable , args [ 0 ] , feedback_slot ) ; <nl> - } else if ( args . register_count ( ) = = 2 ) { <nl> - OutputCall1 ( callable , args [ 0 ] , args [ 1 ] , feedback_slot ) ; <nl> - } else if ( args . register_count ( ) = = 3 ) { <nl> - OutputCall2 ( callable , args [ 0 ] , args [ 1 ] , args [ 2 ] , feedback_slot ) ; <nl> - } else { <nl> - OutputCall ( callable , args , args . register_count ( ) , feedback_slot ) ; <nl> - } <nl> - } <nl> + BytecodeArrayBuilder & BytecodeArrayBuilder : : CallProperty ( Register callable , <nl> + RegisterList args , <nl> + int feedback_slot ) { <nl> + if ( args . register_count ( ) = = 1 ) { <nl> + OutputCallProperty0 ( callable , args [ 0 ] , feedback_slot ) ; <nl> + } else if ( args . register_count ( ) = = 2 ) { <nl> + OutputCallProperty1 ( callable , args [ 0 ] , args [ 1 ] , feedback_slot ) ; <nl> + } else if ( args . register_count ( ) = = 3 ) { <nl> + OutputCallProperty2 ( callable , args [ 0 ] , args [ 1 ] , args [ 2 ] , feedback_slot ) ; <nl> + } else { <nl> + OutputCallProperty ( callable , args , args . register_count ( ) , feedback_slot ) ; <nl> + } <nl> + return * this ; <nl> + } <nl> + <nl> + BytecodeArrayBuilder & BytecodeArrayBuilder : : CallUndefinedReceiver ( <nl> + Register callable , RegisterList args , int feedback_slot ) { <nl> + if ( args . register_count ( ) = = 0 ) { <nl> + OutputCallUndefinedReceiver0 ( callable , feedback_slot ) ; <nl> + } else if ( args . register_count ( ) = = 1 ) { <nl> + OutputCallUndefinedReceiver1 ( callable , args [ 0 ] , feedback_slot ) ; <nl> + } else if ( args . register_count ( ) = = 2 ) { <nl> + OutputCallUndefinedReceiver2 ( callable , args [ 0 ] , args [ 1 ] , feedback_slot ) ; <nl> } else { <nl> - DCHECK ( tail_call_mode = = TailCallMode : : kAllow ) ; <nl> - OutputTailCall ( callable , args , args . register_count ( ) , feedback_slot ) ; <nl> + OutputCallUndefinedReceiver ( callable , args , args . register_count ( ) , <nl> + feedback_slot ) ; <nl> } <nl> return * this ; <nl> } <nl> <nl> + BytecodeArrayBuilder & BytecodeArrayBuilder : : CallAnyReceiver ( Register callable , <nl> + RegisterList args , <nl> + int feedback_slot ) { <nl> + OutputCallAnyReceiver ( callable , args , args . register_count ( ) , feedback_slot ) ; <nl> + return * this ; <nl> + } <nl> + <nl> + BytecodeArrayBuilder & BytecodeArrayBuilder : : TailCall ( Register callable , <nl> + RegisterList args , <nl> + int feedback_slot ) { <nl> + OutputTailCall ( callable , args , args . register_count ( ) , feedback_slot ) ; <nl> + return * this ; <nl> + } <nl> + <nl> BytecodeArrayBuilder & BytecodeArrayBuilder : : CallWithSpread ( Register callable , <nl> RegisterList args ) { <nl> OutputCallWithSpread ( callable , args , args . register_count ( ) ) ; <nl> mmm a / src / interpreter / bytecode - array - builder . h <nl> ppp b / src / interpreter / bytecode - array - builder . h <nl> class V8_EXPORT_PRIVATE BytecodeArrayBuilder final <nl> / / Pop the current context and replace with | context | . <nl> BytecodeArrayBuilder & PopContext ( Register context ) ; <nl> <nl> - / / Call a JS function . The JSFunction or Callable to be called should be in <nl> - / / | callable | . The arguments should be in | args | , with the receiver in <nl> - / / | args [ 0 ] | . The call type of the expression is in | call_type | . Type feedback <nl> - / / is recorded in the | feedback_slot | in the type feedback vector . <nl> - BytecodeArrayBuilder & Call ( <nl> - Register callable , RegisterList args , int feedback_slot , <nl> - Call : : CallType call_type , <nl> - TailCallMode tail_call_mode = TailCallMode : : kDisallow ) ; <nl> + / / Call a JS function which is known to be a property of a JS object . The <nl> + / / JSFunction or Callable to be called should be in | callable | . The arguments <nl> + / / should be in | args | , with the receiver in | args [ 0 ] | . The call type of the <nl> + / / expression is in | call_type | . Type feedback is recorded in the <nl> + / / | feedback_slot | in the type feedback vector . <nl> + BytecodeArrayBuilder & CallProperty ( Register callable , RegisterList args , <nl> + int feedback_slot ) ; <nl> + <nl> + / / Call a JS function with an known undefined receiver . The JSFunction or <nl> + / / Callable to be called should be in | callable | . The arguments should be in <nl> + / / | args | , with no receiver as it is implicitly set to undefined . Type <nl> + / / feedback is recorded in the | feedback_slot | in the type feedback vector . <nl> + BytecodeArrayBuilder & CallUndefinedReceiver ( Register callable , <nl> + RegisterList args , <nl> + int feedback_slot ) ; <nl> + <nl> + / / Call a JS function with an any receiver , possibly ( but not necessarily ) <nl> + / / undefined . The JSFunction or Callable to be called should be in | callable | . <nl> + / / The arguments should be in | args | , with the receiver in | args [ 0 ] | . Type <nl> + / / feedback is recorded in the | feedback_slot | in the type feedback vector . <nl> + BytecodeArrayBuilder & CallAnyReceiver ( Register callable , RegisterList args , <nl> + int feedback_slot ) ; <nl> + <nl> + / / Tail call into a JS function . The JSFunction or Callable to be called <nl> + / / should be in | callable | . The arguments should be in | args | , with the <nl> + / / receiver in | args [ 0 ] | . Type feedback is recorded in the | feedback_slot | in <nl> + / / the type feedback vector . <nl> + BytecodeArrayBuilder & TailCall ( Register callable , RegisterList args , <nl> + int feedback_slot ) ; <nl> <nl> / / Call a JS function . The JSFunction or Callable to be called should be in <nl> / / | callable | , the receiver in | args [ 0 ] | and the arguments in | args [ 1 ] | <nl> mmm a / src / interpreter / bytecode - generator . cc <nl> ppp b / src / interpreter / bytecode - generator . cc <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> Register callee = register_allocator ( ) - > NewRegister ( ) ; <nl> RegisterList args = register_allocator ( ) - > NewGrowableRegisterList ( ) ; <nl> <nl> + bool implicit_undefined_receiver = false ; <nl> + bool is_tail_call = ( expr - > tail_call_mode ( ) = = TailCallMode : : kAllow ) ; <nl> + / / When a call contains a spread , a Call AST node is only created if there is <nl> + / / exactly one spread , and it is the last argument . <nl> + bool is_spread_call = expr - > only_last_arg_is_spread ( ) ; <nl> + <nl> / / TODO ( petermarshall ) : We have a lot of call bytecodes that are very similar , <nl> / / see if we can reduce the number by adding a separate argument which <nl> / / specifies the call type ( e . g . , property , spread , tailcall , etc . ) . <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> } <nl> case Call : : GLOBAL_CALL : { <nl> / / Receiver is undefined for global calls . <nl> - BuildPushUndefinedIntoRegisterList ( & args ) ; <nl> + if ( ! is_tail_call & & ! is_spread_call ) { <nl> + implicit_undefined_receiver = true ; <nl> + } else { <nl> + / / TODO ( leszeks ) : There ' s no special bytecode for tail calls or spread <nl> + / / calls with an undefined receiver , so just push undefined ourselves . <nl> + BuildPushUndefinedIntoRegisterList ( & args ) ; <nl> + } <nl> / / Load callee as a global variable . <nl> VariableProxy * proxy = callee_expr - > AsVariableProxy ( ) ; <nl> BuildVariableLoadForAccumulatorValue ( proxy - > var ( ) , <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> DCHECK ( Register : : AreContiguous ( callee , receiver ) ) ; <nl> RegisterList result_pair ( callee . index ( ) , 2 ) ; <nl> USE ( receiver ) ; <nl> + <nl> Variable * variable = callee_expr - > AsVariableProxy ( ) - > var ( ) ; <nl> builder ( ) <nl> - > LoadLiteral ( variable - > raw_name ( ) ) <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> break ; <nl> } <nl> case Call : : OTHER_CALL : { <nl> - BuildPushUndefinedIntoRegisterList ( & args ) ; <nl> + / / Receiver is undefined for other calls . <nl> + if ( ! is_tail_call & & ! is_spread_call ) { <nl> + implicit_undefined_receiver = true ; <nl> + } else { <nl> + / / TODO ( leszeks ) : There ' s no special bytecode for tail calls or spread <nl> + / / calls with an undefined receiver , so just push undefined ourselves . <nl> + BuildPushUndefinedIntoRegisterList ( & args ) ; <nl> + } <nl> VisitForRegisterValue ( callee_expr , callee ) ; <nl> break ; <nl> } <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> / / Evaluate all arguments to the function call and store in sequential args <nl> / / registers . <nl> VisitArguments ( expr - > arguments ( ) , & args ) ; <nl> - CHECK_EQ ( expr - > arguments ( ) - > length ( ) + 1 , args . register_count ( ) ) ; <nl> + int reciever_arg_count = implicit_undefined_receiver ? 0 : 1 ; <nl> + CHECK_EQ ( reciever_arg_count + expr - > arguments ( ) - > length ( ) , <nl> + args . register_count ( ) ) ; <nl> <nl> / / Resolve callee for a potential direct eval call . This block will mutate the <nl> / / callee value . <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> / / Set up arguments for ResolvePossiblyDirectEval by copying callee , source <nl> / / strings and function closure , and loading language and <nl> / / position . <nl> + Register first_arg = args [ reciever_arg_count ] ; <nl> RegisterList runtime_call_args = register_allocator ( ) - > NewRegisterList ( 6 ) ; <nl> builder ( ) <nl> - > MoveRegister ( callee , runtime_call_args [ 0 ] ) <nl> - . MoveRegister ( args [ 1 ] , runtime_call_args [ 1 ] ) <nl> + . MoveRegister ( first_arg , runtime_call_args [ 1 ] ) <nl> . MoveRegister ( Register : : function_closure ( ) , runtime_call_args [ 2 ] ) <nl> . LoadLiteral ( Smi : : FromInt ( language_mode ( ) ) ) <nl> . StoreAccumulatorInRegister ( runtime_call_args [ 3 ] ) <nl> void BytecodeGenerator : : VisitCall ( Call * expr ) { <nl> <nl> builder ( ) - > SetExpressionPosition ( expr ) ; <nl> <nl> - / / When a call contains a spread , a Call AST node is only created if there is <nl> - / / exactly one spread , and it is the last argument . <nl> - if ( expr - > only_last_arg_is_spread ( ) ) { <nl> - DCHECK_EQ ( TailCallMode : : kDisallow , expr - > tail_call_mode ( ) ) ; <nl> + int const feedback_slot_index = feedback_index ( expr - > CallFeedbackICSlot ( ) ) ; <nl> + <nl> + if ( is_spread_call ) { <nl> + DCHECK ( ! is_tail_call ) ; <nl> + DCHECK ( ! implicit_undefined_receiver ) ; <nl> builder ( ) - > CallWithSpread ( callee , args ) ; <nl> + } else if ( is_tail_call ) { <nl> + DCHECK ( ! implicit_undefined_receiver ) ; <nl> + builder ( ) - > TailCall ( callee , args , feedback_slot_index ) ; <nl> + } else if ( call_type = = Call : : NAMED_PROPERTY_CALL | | <nl> + call_type = = Call : : KEYED_PROPERTY_CALL ) { <nl> + DCHECK ( ! implicit_undefined_receiver ) ; <nl> + builder ( ) - > CallProperty ( callee , args , feedback_slot_index ) ; <nl> + } else if ( implicit_undefined_receiver ) { <nl> + builder ( ) - > CallUndefinedReceiver ( callee , args , feedback_slot_index ) ; <nl> } else { <nl> - int const feedback_slot_index = feedback_index ( expr - > CallFeedbackICSlot ( ) ) ; <nl> - builder ( ) - > Call ( callee , args , feedback_slot_index , call_type , <nl> - expr - > tail_call_mode ( ) ) ; <nl> + builder ( ) - > CallAnyReceiver ( callee , args , feedback_slot_index ) ; <nl> } <nl> } <nl> <nl> void BytecodeGenerator : : VisitCallRuntime ( CallRuntime * expr ) { <nl> if ( expr - > is_jsruntime ( ) ) { <nl> RegisterList args = register_allocator ( ) - > NewGrowableRegisterList ( ) ; <nl> / / Allocate a register for the receiver and load it with undefined . <nl> + / / TODO ( leszeks ) : If CallJSRuntime always has an undefined receiver , use the <nl> + / / same mechanism as CallUndefinedReceiver . <nl> BuildPushUndefinedIntoRegisterList ( & args ) ; <nl> VisitArguments ( expr - > arguments ( ) , & args ) ; <nl> builder ( ) - > CallJSRuntime ( expr - > context_index ( ) , args ) ; <nl> void BytecodeGenerator : : VisitGetIterator ( GetIterator * expr ) { <nl> builder ( ) - > JumpIfNull ( & async_iterator_null ) ; <nl> <nl> / / Let iterator be Call ( method , obj ) <nl> - builder ( ) - > StoreAccumulatorInRegister ( method ) . Call ( <nl> - method , args , feedback_index ( async_call_slot ) , <nl> - Call : : NAMED_PROPERTY_CALL ) ; <nl> + builder ( ) - > StoreAccumulatorInRegister ( method ) . CallProperty ( <nl> + method , args , feedback_index ( async_call_slot ) ) ; <nl> <nl> / / If Type ( iterator ) is not Object , throw a TypeError exception . <nl> builder ( ) - > JumpIfJSReceiver ( & done ) ; <nl> void BytecodeGenerator : : VisitGetIterator ( GetIterator * expr ) { <nl> . StoreAccumulatorInRegister ( method ) ; <nl> <nl> / / Let syncIterator be Call ( syncMethod , obj ) <nl> - builder ( ) - > Call ( method , args , feedback_index ( call_slot ) , <nl> - Call : : NAMED_PROPERTY_CALL ) ; <nl> + builder ( ) - > CallProperty ( method , args , feedback_index ( call_slot ) ) ; <nl> <nl> / / Return CreateAsyncFromSyncIterator ( syncIterator ) <nl> / / alias ` method ` register as it ' s no longer used <nl> void BytecodeGenerator : : VisitGetIterator ( GetIterator * expr ) { <nl> . StoreAccumulatorInRegister ( method ) ; <nl> <nl> / / Let iterator be Call ( method , obj ) . <nl> - builder ( ) - > Call ( method , args , feedback_index ( call_slot ) , <nl> - Call : : NAMED_PROPERTY_CALL ) ; <nl> + builder ( ) - > CallProperty ( method , args , feedback_index ( call_slot ) ) ; <nl> <nl> / / If Type ( iterator ) is not Object , throw a TypeError exception . <nl> BytecodeLabel no_type_error ; <nl> mmm a / src / interpreter / bytecodes . cc <nl> ppp b / src / interpreter / bytecodes . cc <nl> bool Bytecodes : : IsStarLookahead ( Bytecode bytecode , OperandScale operand_scale ) { <nl> case Bytecode : : kInc : <nl> case Bytecode : : kDec : <nl> case Bytecode : : kTypeOf : <nl> - case Bytecode : : kCall : <nl> + case Bytecode : : kCallAnyReceiver : <nl> case Bytecode : : kCallProperty : <nl> + case Bytecode : : kCallProperty0 : <nl> + case Bytecode : : kCallProperty1 : <nl> + case Bytecode : : kCallProperty2 : <nl> + case Bytecode : : kCallUndefinedReceiver : <nl> + case Bytecode : : kCallUndefinedReceiver0 : <nl> + case Bytecode : : kCallUndefinedReceiver1 : <nl> + case Bytecode : : kCallUndefinedReceiver2 : <nl> case Bytecode : : kConstruct : <nl> case Bytecode : : kConstructWithSpread : <nl> return true ; <nl> mmm a / src / interpreter / bytecodes . h <nl> ppp b / src / interpreter / bytecodes . h <nl> namespace interpreter { <nl> V ( GetSuperConstructor , AccumulatorUse : : kRead , OperandType : : kRegOut ) \ <nl> \ <nl> / * Call operations * / \ <nl> - V ( Call , AccumulatorUse : : kWrite , OperandType : : kReg , OperandType : : kRegList , \ <nl> - OperandType : : kRegCount , OperandType : : kIdx ) \ <nl> - V ( Call0 , AccumulatorUse : : kWrite , OperandType : : kReg , OperandType : : kReg , \ <nl> - OperandType : : kIdx ) \ <nl> - V ( Call1 , AccumulatorUse : : kWrite , OperandType : : kReg , OperandType : : kReg , \ <nl> - OperandType : : kReg , OperandType : : kIdx ) \ <nl> - V ( Call2 , AccumulatorUse : : kWrite , OperandType : : kReg , OperandType : : kReg , \ <nl> - OperandType : : kReg , OperandType : : kReg , OperandType : : kIdx ) \ <nl> + V ( CallAnyReceiver , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> + OperandType : : kRegList , OperandType : : kRegCount , OperandType : : kIdx ) \ <nl> V ( CallProperty , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> OperandType : : kRegList , OperandType : : kRegCount , OperandType : : kIdx ) \ <nl> V ( CallProperty0 , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> namespace interpreter { <nl> V ( CallProperty2 , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> OperandType : : kReg , OperandType : : kReg , OperandType : : kReg , \ <nl> OperandType : : kIdx ) \ <nl> + V ( CallUndefinedReceiver , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> + OperandType : : kRegList , OperandType : : kRegCount , OperandType : : kIdx ) \ <nl> + V ( CallUndefinedReceiver0 , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> + OperandType : : kIdx ) \ <nl> + V ( CallUndefinedReceiver1 , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> + OperandType : : kReg , OperandType : : kIdx ) \ <nl> + V ( CallUndefinedReceiver2 , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> + OperandType : : kReg , OperandType : : kReg , OperandType : : kIdx ) \ <nl> V ( CallWithSpread , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> OperandType : : kRegList , OperandType : : kRegCount ) \ <nl> V ( TailCall , AccumulatorUse : : kWrite , OperandType : : kReg , \ <nl> enum class Bytecode : uint8_t { <nl> <nl> class V8_EXPORT_PRIVATE Bytecodes final { <nl> public : <nl> - / / The maximum number of operands a bytecode may have . <nl> + / / The maximum number of operands a bytecode may have . <nl> static const int kMaxOperands = 5 ; <nl> <nl> / / Returns string representation of | bytecode | . <nl> class V8_EXPORT_PRIVATE Bytecodes final { <nl> <nl> / / Returns true if the bytecode is a call or a constructor call . <nl> static constexpr bool IsCallOrConstruct ( Bytecode bytecode ) { <nl> - return bytecode = = Bytecode : : kCall | | bytecode = = Bytecode : : kCallProperty | | <nl> - bytecode = = Bytecode : : kCall0 | | <nl> + return bytecode = = Bytecode : : kCallAnyReceiver | | <nl> + bytecode = = Bytecode : : kCallProperty | | <nl> bytecode = = Bytecode : : kCallProperty0 | | <nl> - bytecode = = Bytecode : : kCall1 | | <nl> bytecode = = Bytecode : : kCallProperty1 | | <nl> - bytecode = = Bytecode : : kCall2 | | <nl> bytecode = = Bytecode : : kCallProperty2 | | <nl> + bytecode = = Bytecode : : kCallUndefinedReceiver | | <nl> + bytecode = = Bytecode : : kCallUndefinedReceiver0 | | <nl> + bytecode = = Bytecode : : kCallUndefinedReceiver1 | | <nl> + bytecode = = Bytecode : : kCallUndefinedReceiver2 | | <nl> bytecode = = Bytecode : : kTailCall | | <nl> bytecode = = Bytecode : : kConstruct | | <nl> bytecode = = Bytecode : : kCallWithSpread | | <nl> class V8_EXPORT_PRIVATE Bytecodes final { <nl> / / through the bytecode ' s handler . <nl> static bool MakesCallAlongCriticalPath ( Bytecode bytecode ) ; <nl> <nl> + / / Returns the receiver mode of the given call bytecode . <nl> + static ConvertReceiverMode GetReceiverMode ( Bytecode bytecode ) { <nl> + DCHECK ( IsCallOrConstruct ( bytecode ) ) ; <nl> + switch ( bytecode ) { <nl> + case Bytecode : : kCallProperty : <nl> + case Bytecode : : kCallProperty0 : <nl> + case Bytecode : : kCallProperty1 : <nl> + case Bytecode : : kCallProperty2 : <nl> + return ConvertReceiverMode : : kNotNullOrUndefined ; <nl> + case Bytecode : : kCallUndefinedReceiver : <nl> + case Bytecode : : kCallUndefinedReceiver0 : <nl> + case Bytecode : : kCallUndefinedReceiver1 : <nl> + case Bytecode : : kCallUndefinedReceiver2 : <nl> + return ConvertReceiverMode : : kNullOrUndefined ; <nl> + case Bytecode : : kCallAnyReceiver : <nl> + case Bytecode : : kTailCall : <nl> + case Bytecode : : kConstruct : <nl> + case Bytecode : : kCallWithSpread : <nl> + case Bytecode : : kConstructWithSpread : <nl> + case Bytecode : : kInvokeIntrinsic : <nl> + case Bytecode : : kCallJSRuntime : <nl> + return ConvertReceiverMode : : kAny ; <nl> + default : <nl> + UNREACHABLE ( ) ; <nl> + return ConvertReceiverMode : : kAny ; <nl> + } <nl> + } <nl> + <nl> / / Returns true if the bytecode is a debug break . <nl> static bool IsDebugBreak ( Bytecode bytecode ) ; <nl> <nl> mmm a / src / interpreter / interpreter - assembler . cc <nl> ppp b / src / interpreter / interpreter - assembler . cc <nl> Node * InterpreterAssembler : : IncrementCallCount ( Node * feedback_vector , <nl> SKIP_WRITE_BARRIER ) ; <nl> } <nl> <nl> - Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> - Node * first_arg , Node * arg_count , <nl> - Node * slot_id , <nl> - Node * feedback_vector , <nl> - TailCallMode tail_call_mode ) { <nl> + Node * InterpreterAssembler : : CallJSWithFeedback ( <nl> + compiler : : Node * function , compiler : : Node * context , <nl> + compiler : : Node * first_arg , compiler : : Node * arg_count , <nl> + compiler : : Node * slot_id , compiler : : Node * feedback_vector , <nl> + ConvertReceiverMode receiver_mode , TailCallMode tail_call_mode ) { <nl> / / Static checks to assert it is safe to examine the type feedback element . <nl> / / We don ' t know that we have a weak cell . We might have a private symbol <nl> / / or an AllocationSite , but the memory is safe to examine . <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> / / to be a pointer . <nl> DCHECK ( Bytecodes : : MakesCallAlongCriticalPath ( bytecode_ ) ) ; <nl> DCHECK ( Bytecodes : : IsCallOrConstruct ( bytecode_ ) ) ; <nl> + DCHECK_EQ ( Bytecodes : : GetReceiverMode ( bytecode_ ) , receiver_mode ) ; <nl> + <nl> STATIC_ASSERT ( WeakCell : : kSize > = kPointerSize ) ; <nl> STATIC_ASSERT ( AllocationSite : : kTransitionInfoOffset = = <nl> WeakCell : : kValueOffset & & <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> IncrementCallCount ( feedback_vector , slot_id ) ; <nl> <nl> / / Call using call function builtin . <nl> - Callable callable = CodeFactory : : InterpreterPushArgsAndCall ( <nl> - isolate ( ) , tail_call_mode , InterpreterPushArgsMode : : kJSFunction ) ; <nl> + Callable callable = CodeFactory : : InterpreterPushArgsThenCall ( <nl> + isolate ( ) , receiver_mode , tail_call_mode , <nl> + InterpreterPushArgsMode : : kJSFunction ) ; <nl> Node * code_target = HeapConstant ( callable . code ( ) ) ; <nl> Node * ret_value = CallStub ( callable . descriptor ( ) , code_target , context , <nl> arg_count , first_arg , function ) ; <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> GotoIfNot ( IsAllocationSiteMap ( LoadMap ( feedback_element ) ) , <nl> & check_initialized ) ; <nl> <nl> - / / If it is not the Array ( ) function , mark megamorphic . <nl> - Node * context_slot = LoadContextElement ( LoadNativeContext ( context ) , <nl> - Context : : ARRAY_FUNCTION_INDEX ) ; <nl> - Node * is_array_function = WordEqual ( context_slot , function ) ; <nl> - GotoIfNot ( is_array_function , & mark_megamorphic ) ; <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + / / For undefined receivers ( mostly global calls ) , do an additional check <nl> + / / for the monomorphic Array function , which would otherwise appear <nl> + / / megamorphic . <nl> <nl> - / / It is a monomorphic Array function . Increment the call count . <nl> - IncrementCallCount ( feedback_vector , slot_id ) ; <nl> + / / If it is not the Array ( ) function , mark megamorphic . <nl> + Node * context_slot = LoadContextElement ( LoadNativeContext ( context ) , <nl> + Context : : ARRAY_FUNCTION_INDEX ) ; <nl> + Node * is_array_function = WordEqual ( context_slot , function ) ; <nl> + GotoIfNot ( is_array_function , & mark_megamorphic ) ; <nl> <nl> - / / Call ArrayConstructorStub . <nl> - Callable callable_call = <nl> - CodeFactory : : InterpreterPushArgsAndConstructArray ( isolate ( ) ) ; <nl> - Node * code_target_call = HeapConstant ( callable_call . code ( ) ) ; <nl> - Node * ret_value = <nl> - CallStub ( callable_call . descriptor ( ) , code_target_call , context , <nl> - arg_count , function , feedback_element , first_arg ) ; <nl> - return_value . Bind ( ret_value ) ; <nl> - Goto ( & end ) ; <nl> + / / It is a monomorphic Array function . Increment the call count . <nl> + IncrementCallCount ( feedback_vector , slot_id ) ; <nl> + <nl> + / / Call ArrayConstructorStub . <nl> + Callable callable_call = <nl> + CodeFactory : : InterpreterPushArgsThenConstructArray ( isolate ( ) ) ; <nl> + Node * code_target_call = HeapConstant ( callable_call . code ( ) ) ; <nl> + Node * ret_value = <nl> + CallStub ( callable_call . descriptor ( ) , code_target_call , context , <nl> + arg_count , function , feedback_element , first_arg ) ; <nl> + return_value . Bind ( ret_value ) ; <nl> + Goto ( & end ) ; <nl> + <nl> + } else { <nl> + Goto ( & mark_megamorphic ) ; <nl> + } <nl> <nl> Bind ( & check_initialized ) ; <nl> { <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> HeapConstant ( FeedbackVector : : UninitializedSentinel ( isolate ( ) ) ) ) ; <nl> GotoIfNot ( is_uninitialized , & mark_megamorphic ) ; <nl> <nl> - Comment ( " handle_unitinitialized " ) ; <nl> + Comment ( " handle_uninitialized " ) ; <nl> / / If it is not a JSFunction mark it as megamorphic . <nl> Node * is_smi = TaggedIsSmi ( function ) ; <nl> GotoIf ( is_smi , & mark_megamorphic ) ; <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> IncrementCallCount ( feedback_vector , slot_id ) ; <nl> <nl> / / Call using call builtin . <nl> - Callable callable_call = CodeFactory : : InterpreterPushArgsAndCall ( <nl> - isolate ( ) , tail_call_mode , InterpreterPushArgsMode : : kOther ) ; <nl> + Callable callable_call = CodeFactory : : InterpreterPushArgsThenCall ( <nl> + isolate ( ) , receiver_mode , tail_call_mode , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> Node * code_target_call = HeapConstant ( callable_call . code ( ) ) ; <nl> Node * ret_value = CallStub ( callable_call . descriptor ( ) , code_target_call , <nl> context , arg_count , first_arg , function ) ; <nl> Node * InterpreterAssembler : : CallJSWithFeedback ( Node * function , Node * context , <nl> <nl> Node * InterpreterAssembler : : CallJS ( Node * function , Node * context , <nl> Node * first_arg , Node * arg_count , <nl> + ConvertReceiverMode receiver_mode , <nl> TailCallMode tail_call_mode ) { <nl> DCHECK ( Bytecodes : : MakesCallAlongCriticalPath ( bytecode_ ) ) ; <nl> DCHECK ( Bytecodes : : IsCallOrConstruct ( bytecode_ ) ) ; <nl> - Callable callable = CodeFactory : : InterpreterPushArgsAndCall ( <nl> - isolate ( ) , tail_call_mode , InterpreterPushArgsMode : : kOther ) ; <nl> + DCHECK_EQ ( Bytecodes : : GetReceiverMode ( bytecode_ ) , receiver_mode ) ; <nl> + Callable callable = CodeFactory : : InterpreterPushArgsThenCall ( <nl> + isolate ( ) , receiver_mode , tail_call_mode , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> Node * code_target = HeapConstant ( callable . code ( ) ) ; <nl> <nl> return CallStub ( callable . descriptor ( ) , code_target , context , arg_count , <nl> Node * InterpreterAssembler : : CallJS ( Node * function , Node * context , <nl> Node * InterpreterAssembler : : CallJSWithSpread ( Node * function , Node * context , <nl> Node * first_arg , Node * arg_count ) { <nl> DCHECK ( Bytecodes : : MakesCallAlongCriticalPath ( bytecode_ ) ) ; <nl> - Callable callable = CodeFactory : : InterpreterPushArgsAndCall ( <nl> - isolate ( ) , TailCallMode : : kDisallow , <nl> + DCHECK_EQ ( Bytecodes : : GetReceiverMode ( bytecode_ ) , ConvertReceiverMode : : kAny ) ; <nl> + Callable callable = CodeFactory : : InterpreterPushArgsThenCall ( <nl> + isolate ( ) , ConvertReceiverMode : : kAny , TailCallMode : : kDisallow , <nl> InterpreterPushArgsMode : : kWithFinalSpread ) ; <nl> Node * code_target = HeapConstant ( callable . code ( ) ) ; <nl> <nl> Node * InterpreterAssembler : : Construct ( Node * constructor , Node * context , <nl> { <nl> Comment ( " call using ConstructFunction " ) ; <nl> IncrementCallCount ( feedback_vector , slot_id ) ; <nl> - Callable callable_function = CodeFactory : : InterpreterPushArgsAndConstruct ( <nl> + Callable callable_function = CodeFactory : : InterpreterPushArgsThenConstruct ( <nl> isolate ( ) , InterpreterPushArgsMode : : kJSFunction ) ; <nl> return_value . Bind ( CallStub ( callable_function . descriptor ( ) , <nl> HeapConstant ( callable_function . code ( ) ) , context , <nl> Node * InterpreterAssembler : : Construct ( Node * constructor , Node * context , <nl> Bind ( & call_construct ) ; <nl> { <nl> Comment ( " call using Construct builtin " ) ; <nl> - Callable callable = CodeFactory : : InterpreterPushArgsAndConstruct ( <nl> + Callable callable = CodeFactory : : InterpreterPushArgsThenConstruct ( <nl> isolate ( ) , InterpreterPushArgsMode : : kOther ) ; <nl> Node * code_target = HeapConstant ( callable . code ( ) ) ; <nl> return_value . Bind ( CallStub ( callable . descriptor ( ) , code_target , context , <nl> Node * InterpreterAssembler : : ConstructWithSpread ( Node * constructor , <nl> DCHECK ( Bytecodes : : MakesCallAlongCriticalPath ( bytecode_ ) ) ; <nl> Variable return_value ( this , MachineRepresentation : : kTagged ) ; <nl> Comment ( " call using ConstructWithSpread " ) ; <nl> - Callable callable = CodeFactory : : InterpreterPushArgsAndConstruct ( <nl> + Callable callable = CodeFactory : : InterpreterPushArgsThenConstruct ( <nl> isolate ( ) , InterpreterPushArgsMode : : kWithFinalSpread ) ; <nl> Node * code_target = HeapConstant ( callable . code ( ) ) ; <nl> return_value . Bind ( CallStub ( callable . descriptor ( ) , code_target , context , <nl> mmm a / src / interpreter / interpreter - assembler . h <nl> ppp b / src / interpreter / interpreter - assembler . h <nl> class V8_EXPORT_PRIVATE InterpreterAssembler : public CodeStubAssembler { <nl> compiler : : Node * IncrementCallCount ( compiler : : Node * feedback_vector , <nl> compiler : : Node * slot_id ) ; <nl> <nl> - / / Call JSFunction or Callable | function | with | arg_count | <nl> - / / arguments ( not including receiver ) and the first argument <nl> - / / located at | first_arg | . Type feedback is collected in the <nl> - / / slot at index | slot_id | . <nl> - compiler : : Node * CallJSWithFeedback ( compiler : : Node * function , <nl> - compiler : : Node * context , <nl> - compiler : : Node * first_arg , <nl> - compiler : : Node * arg_count , <nl> - compiler : : Node * slot_id , <nl> - compiler : : Node * feedback_vector , <nl> - TailCallMode tail_call_mode ) ; <nl> - <nl> - / / Call JSFunction or Callable | function | with | arg_count | <nl> - / / arguments ( not including receiver ) and the first argument <nl> - / / located at | first_arg | . <nl> + / / Call JSFunction or Callable | function | with | arg_count | arguments ( not <nl> + / / including receiver ) and the first argument located at | first_arg | . Type <nl> + / / feedback is collected in the slot at index | slot_id | . <nl> + / / <nl> + / / If the | receiver_mode | is kNullOrUndefined , then the receiver is implicitly <nl> + / / undefined and | first_arg | is the first parameter . Otherwise , | first_arg | is <nl> + / / the receiver and it is converted according to | receiver_mode | . <nl> + compiler : : Node * CallJSWithFeedback ( <nl> + compiler : : Node * function , compiler : : Node * context , <nl> + compiler : : Node * first_arg , compiler : : Node * arg_count , <nl> + compiler : : Node * slot_id , compiler : : Node * feedback_vector , <nl> + ConvertReceiverMode receiver_mode , TailCallMode tail_call_mode ) ; <nl> + <nl> + / / Call JSFunction or Callable | function | with | arg_count | arguments ( not <nl> + / / including receiver ) and the first argument located at | first_arg | , possibly <nl> + / / including the receiver depending on | receiver_mode | . <nl> compiler : : Node * CallJS ( compiler : : Node * function , compiler : : Node * context , <nl> compiler : : Node * first_arg , compiler : : Node * arg_count , <nl> + ConvertReceiverMode receiver_mode , <nl> TailCallMode tail_call_mode ) ; <nl> <nl> / / Call JSFunction or Callable | function | with | arg_count | <nl> mmm a / src / interpreter / interpreter - generator . cc <nl> ppp b / src / interpreter / interpreter - generator . cc <nl> class InterpreterGenerator { <nl> void DoKeyedStoreIC ( Callable ic , InterpreterAssembler * assembler ) ; <nl> <nl> / / Generates code to perform a JS call that collects type feedback . <nl> - void DoJSCall ( InterpreterAssembler * assembler , TailCallMode tail_call_mode ) ; <nl> + void DoJSCall ( InterpreterAssembler * assembler , <nl> + ConvertReceiverMode receiver_mode , TailCallMode tail_call_mode ) ; <nl> <nl> / / Generates code to perform a JS call with a known number of arguments that <nl> / / collects type feedback . <nl> - void DoJSCallN ( InterpreterAssembler * assembler , int n ) ; <nl> + void DoJSCallN ( InterpreterAssembler * assembler , int n , <nl> + ConvertReceiverMode receiver_mode ) ; <nl> <nl> / / Generates code to perform delete via function_id . <nl> void DoDelete ( Runtime : : FunctionId function_id , <nl> void InterpreterGenerator : : DoGetSuperConstructor ( <nl> } <nl> <nl> void InterpreterGenerator : : DoJSCall ( InterpreterAssembler * assembler , <nl> + ConvertReceiverMode receiver_mode , <nl> TailCallMode tail_call_mode ) { <nl> Node * function_reg = __ BytecodeOperandReg ( 0 ) ; <nl> Node * function = __ LoadRegister ( function_reg ) ; <nl> - Node * receiver_reg = __ BytecodeOperandReg ( 1 ) ; <nl> - Node * receiver_arg = __ RegisterLocation ( receiver_reg ) ; <nl> - Node * receiver_args_count = __ BytecodeOperandCount ( 2 ) ; <nl> - Node * receiver_count = __ Int32Constant ( 1 ) ; <nl> - Node * args_count = __ Int32Sub ( receiver_args_count , receiver_count ) ; <nl> + Node * first_arg_reg = __ BytecodeOperandReg ( 1 ) ; <nl> + Node * first_arg = __ RegisterLocation ( first_arg_reg ) ; <nl> + Node * arg_list_count = __ BytecodeOperandCount ( 2 ) ; <nl> + Node * args_count ; <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + / / The receiver is implied , so it is not in the argument list . <nl> + args_count = arg_list_count ; <nl> + } else { <nl> + / / Subtract the receiver from the argument count . <nl> + Node * receiver_count = __ Int32Constant ( 1 ) ; <nl> + args_count = __ Int32Sub ( arg_list_count , receiver_count ) ; <nl> + } <nl> Node * slot_id = __ BytecodeOperandIdx ( 3 ) ; <nl> Node * feedback_vector = __ LoadFeedbackVector ( ) ; <nl> Node * context = __ GetContext ( ) ; <nl> Node * result = <nl> - __ CallJSWithFeedback ( function , context , receiver_arg , args_count , <nl> - slot_id , feedback_vector , tail_call_mode ) ; <nl> + __ CallJSWithFeedback ( function , context , first_arg , args_count , slot_id , <nl> + feedback_vector , receiver_mode , tail_call_mode ) ; <nl> __ SetAccumulator ( result ) ; <nl> __ Dispatch ( ) ; <nl> } <nl> <nl> void InterpreterGenerator : : DoJSCallN ( InterpreterAssembler * assembler , <nl> - int arg_count ) { <nl> - const int kReceiverOperandIndex = 1 ; <nl> - const int kReceiverOperandCount = 1 ; <nl> + int arg_count , <nl> + ConvertReceiverMode receiver_mode ) { <nl> + / / Indices and counts of operands on the bytecode . <nl> + const int kFirstArgumentOperandIndex = 1 ; <nl> + const int kReceiverOperandCount = <nl> + ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) ? 0 : 1 ; <nl> const int kSlotOperandIndex = <nl> - kReceiverOperandIndex + kReceiverOperandCount + arg_count ; <nl> - const int kBoilerplatParameterCount = 7 ; <nl> + kFirstArgumentOperandIndex + kReceiverOperandCount + arg_count ; <nl> + / / Indices and counts of parameters to the call stub . <nl> + const int kBoilerplateParameterCount = 7 ; <nl> const int kReceiverParameterIndex = 5 ; <nl> + const int kReceiverParameterCount = 1 ; <nl> + / / Only used in a DCHECK . <nl> + USE ( kReceiverParameterCount ) ; <nl> <nl> Node * function_reg = __ BytecodeOperandReg ( 0 ) ; <nl> Node * function = __ LoadRegister ( function_reg ) ; <nl> - std : : array < Node * , Bytecodes : : kMaxOperands + kBoilerplatParameterCount > temp ; <nl> + std : : array < Node * , Bytecodes : : kMaxOperands + kBoilerplateParameterCount > temp ; <nl> Callable call_ic = CodeFactory : : CallIC ( isolate_ ) ; <nl> temp [ 0 ] = __ HeapConstant ( call_ic . code ( ) ) ; <nl> temp [ 1 ] = function ; <nl> temp [ 2 ] = __ Int32Constant ( arg_count ) ; <nl> temp [ 3 ] = __ BytecodeOperandIdxInt32 ( kSlotOperandIndex ) ; <nl> temp [ 4 ] = __ LoadFeedbackVector ( ) ; <nl> - for ( int i = 0 ; i < ( arg_count + kReceiverOperandCount ) ; + + i ) { <nl> - Node * reg = __ BytecodeOperandReg ( i + kReceiverOperandIndex ) ; <nl> - temp [ kReceiverParameterIndex + i ] = __ LoadRegister ( reg ) ; <nl> + <nl> + int parameter_index = kReceiverParameterIndex ; <nl> + if ( receiver_mode = = ConvertReceiverMode : : kNullOrUndefined ) { <nl> + / / The first argument parameter ( the receiver ) is implied to be undefined . <nl> + Node * undefined_value = <nl> + __ HeapConstant ( isolate_ - > factory ( ) - > undefined_value ( ) ) ; <nl> + temp [ parameter_index + + ] = undefined_value ; <nl> + } <nl> + / / The bytecode argument operands are copied into the remaining argument <nl> + / / parameters . <nl> + for ( int i = 0 ; i < ( kReceiverOperandCount + arg_count ) ; + + i ) { <nl> + Node * reg = __ BytecodeOperandReg ( kFirstArgumentOperandIndex + i ) ; <nl> + temp [ parameter_index + + ] = __ LoadRegister ( reg ) ; <nl> } <nl> - temp [ kReceiverParameterIndex + arg_count + kReceiverOperandCount ] = <nl> - __ GetContext ( ) ; <nl> + <nl> + DCHECK_EQ ( parameter_index , <nl> + kReceiverParameterIndex + kReceiverParameterCount + arg_count ) ; <nl> + temp [ parameter_index ] = __ GetContext ( ) ; <nl> + <nl> Node * result = __ CallStubN ( call_ic . descriptor ( ) , 1 , <nl> - arg_count + kBoilerplatParameterCount , & temp [ 0 ] ) ; <nl> + arg_count + kBoilerplateParameterCount , & temp [ 0 ] ) ; <nl> __ SetAccumulator ( result ) ; <nl> __ Dispatch ( ) ; <nl> } <nl> void InterpreterGenerator : : DoJSCallN ( InterpreterAssembler * assembler , <nl> / / Call a JSfunction or Callable in | callable | with the | receiver | and <nl> / / | arg_count | arguments in subsequent registers . Collect type feedback <nl> / / into | feedback_slot_id | <nl> - void InterpreterGenerator : : DoCall ( InterpreterAssembler * assembler ) { <nl> - DoJSCall ( assembler , TailCallMode : : kDisallow ) ; <nl> + void InterpreterGenerator : : DoCallAnyReceiver ( InterpreterAssembler * assembler ) { <nl> + DoJSCall ( assembler , ConvertReceiverMode : : kAny , TailCallMode : : kDisallow ) ; <nl> + } <nl> + <nl> + void InterpreterGenerator : : DoCallProperty ( InterpreterAssembler * assembler ) { <nl> + DoJSCall ( assembler , ConvertReceiverMode : : kNotNullOrUndefined , <nl> + TailCallMode : : kDisallow ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCall0 ( InterpreterAssembler * assembler ) { <nl> - DoJSCallN ( assembler , 0 ) ; <nl> + void InterpreterGenerator : : DoCallProperty0 ( InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 0 , ConvertReceiverMode : : kNotNullOrUndefined ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCall1 ( InterpreterAssembler * assembler ) { <nl> - DoJSCallN ( assembler , 1 ) ; <nl> + void InterpreterGenerator : : DoCallProperty1 ( InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 1 , ConvertReceiverMode : : kNotNullOrUndefined ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCall2 ( InterpreterAssembler * assembler ) { <nl> - DoJSCallN ( assembler , 2 ) ; <nl> + void InterpreterGenerator : : DoCallProperty2 ( InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 2 , ConvertReceiverMode : : kNotNullOrUndefined ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCallProperty ( InterpreterAssembler * assembler ) { <nl> - / / Same as Call <nl> - UNREACHABLE ( ) ; <nl> + void InterpreterGenerator : : DoCallUndefinedReceiver ( <nl> + InterpreterAssembler * assembler ) { <nl> + DoJSCall ( assembler , ConvertReceiverMode : : kNullOrUndefined , <nl> + TailCallMode : : kDisallow ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCallProperty0 ( InterpreterAssembler * assembler ) { <nl> - / / Same as Call0 <nl> - UNREACHABLE ( ) ; <nl> + void InterpreterGenerator : : DoCallUndefinedReceiver0 ( <nl> + InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 0 , ConvertReceiverMode : : kNullOrUndefined ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCallProperty1 ( InterpreterAssembler * assembler ) { <nl> - / / Same as Call1 <nl> - UNREACHABLE ( ) ; <nl> + void InterpreterGenerator : : DoCallUndefinedReceiver1 ( <nl> + InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 1 , ConvertReceiverMode : : kNullOrUndefined ) ; <nl> } <nl> <nl> - void InterpreterGenerator : : DoCallProperty2 ( InterpreterAssembler * assembler ) { <nl> - / / Same as Call2 <nl> - UNREACHABLE ( ) ; <nl> + void InterpreterGenerator : : DoCallUndefinedReceiver2 ( <nl> + InterpreterAssembler * assembler ) { <nl> + DoJSCallN ( assembler , 2 , ConvertReceiverMode : : kNullOrUndefined ) ; <nl> } <nl> <nl> / / TailCall < callable > < receiver > < arg_count > < feedback_slot_id > <nl> void InterpreterGenerator : : DoCallProperty2 ( InterpreterAssembler * assembler ) { <nl> / / | arg_count | arguments in subsequent registers . Collect type feedback <nl> / / into | feedback_slot_id | <nl> void InterpreterGenerator : : DoTailCall ( InterpreterAssembler * assembler ) { <nl> - DoJSCall ( assembler , TailCallMode : : kAllow ) ; <nl> + DoJSCall ( assembler , ConvertReceiverMode : : kAny , TailCallMode : : kAllow ) ; <nl> } <nl> <nl> / / CallRuntime < function_id > < first_arg > < arg_count > <nl> void InterpreterGenerator : : DoCallJSRuntime ( InterpreterAssembler * assembler ) { <nl> <nl> / / Call the function . <nl> Node * result = __ CallJS ( function , context , first_arg , args_count , <nl> - TailCallMode : : kDisallow ) ; <nl> + ConvertReceiverMode : : kAny , TailCallMode : : kDisallow ) ; <nl> __ SetAccumulator ( result ) ; <nl> __ Dispatch ( ) ; <nl> } <nl> mmm a / src / interpreter / interpreter - intrinsics - generator . cc <nl> ppp b / src / interpreter / interpreter - intrinsics - generator . cc <nl> Node * IntrinsicsGenerator : : Call ( Node * args_reg , Node * arg_count , <nl> } <nl> <nl> Node * result = __ CallJS ( function , context , receiver_arg , target_args_count , <nl> - TailCallMode : : kDisallow ) ; <nl> + ConvertReceiverMode : : kAny , TailCallMode : : kDisallow ) ; <nl> return result ; <nl> } <nl> <nl> mmm a / src / interpreter / setup - interpreter - internal . cc <nl> ppp b / src / interpreter / setup - interpreter - internal . cc <nl> void SetupInterpreter : : InstallBytecodeHandlers ( Interpreter * interpreter ) { <nl> bool SetupInterpreter : : ReuseExistingHandler ( Address * dispatch_table , <nl> Bytecode bytecode , <nl> OperandScale operand_scale ) { <nl> - size_t index = Interpreter : : GetDispatchTableIndex ( bytecode , operand_scale ) ; <nl> - switch ( bytecode ) { <nl> - case Bytecode : : kCallProperty : <nl> - case Bytecode : : kCallProperty0 : <nl> - case Bytecode : : kCallProperty1 : <nl> - case Bytecode : : kCallProperty2 : { <nl> - const int offset = static_cast < int > ( Bytecode : : kCallProperty ) - <nl> - static_cast < int > ( Bytecode : : kCall ) ; <nl> - STATIC_ASSERT ( offset = = static_cast < int > ( Bytecode : : kCallProperty0 ) - <nl> - static_cast < int > ( Bytecode : : kCall0 ) ) ; <nl> - STATIC_ASSERT ( offset = = static_cast < int > ( Bytecode : : kCallProperty1 ) - <nl> - static_cast < int > ( Bytecode : : kCall1 ) ) ; <nl> - STATIC_ASSERT ( offset = = static_cast < int > ( Bytecode : : kCallProperty2 ) - <nl> - static_cast < int > ( Bytecode : : kCall2 ) ) ; <nl> - CHECK_LT ( offset , index ) ; <nl> - dispatch_table [ index ] = dispatch_table [ index - offset ] ; <nl> - return true ; <nl> - break ; <nl> - } <nl> - default : <nl> - return false ; <nl> - } <nl> + / / TODO ( leszeks ) : reuse Lda [ Immutable ] [ Current ] ContextSlot <nl> + return false ; <nl> } <nl> <nl> / / static <nl> mmm a / src / mips / interface - descriptors - mips . cc <nl> ppp b / src / mips / interface - descriptors - mips . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> a1 , / / the target to call verified to be Array function <nl> mmm a / src / mips64 / interface - descriptors - mips64 . cc <nl> ppp b / src / mips64 / interface - descriptors - mips64 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> a0 , / / argument count ( not including receiver ) <nl> a1 , / / the target to call verified to be Array function <nl> mmm a / src / ppc / interface - descriptors - ppc . cc <nl> ppp b / src / ppc / interface - descriptors - ppc . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r3 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r3 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r3 , / / argument count ( not including receiver ) <nl> r4 , / / target to call checked to be Array function <nl> mmm a / src / s390 / interface - descriptors - s390 . cc <nl> ppp b / src / s390 / interface - descriptors - s390 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r2 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r2 , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> r2 , / / argument count ( not including receiver ) <nl> r3 , / / target to call checked to be Array function <nl> mmm a / src / x64 / interface - descriptors - x64 . cc <nl> ppp b / src / x64 / interface - descriptors - x64 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> rax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> rax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> rax , / / argument count ( not including receiver ) <nl> rdx , / / target to the call . It is checked to be Array function . <nl> mmm a / src / x87 / interface - descriptors - x87 . cc <nl> ppp b / src / x87 / interface - descriptors - x87 . cc <nl> void InterpreterDispatchDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenCallDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndCallDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> + void InterpreterPushArgsThenConstructDescriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> void InterpreterPushArgsAndConstructDescriptor : : InitializePlatformSpecific ( <nl> data - > InitializePlatformSpecific ( arraysize ( registers ) , registers ) ; <nl> } <nl> <nl> - void InterpreterPushArgsAndConstructArrayDescriptor : : InitializePlatformSpecific ( <nl> - CallInterfaceDescriptorData * data ) { <nl> + void InterpreterPushArgsThenConstructArrayDescriptor : : <nl> + InitializePlatformSpecific ( CallInterfaceDescriptorData * data ) { <nl> Register registers [ ] = { <nl> eax , / / argument count ( not including receiver ) <nl> edx , / / target to the call . It is checked to be Array function . <nl> mmm a / test / cctest / interpreter / bytecode_expectations / CallGlobal . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / CallGlobal . golden <nl> snippet : " <nl> function f ( ) { return t ( ) ; } <nl> f ( ) ; <nl> " <nl> - frame size : 2 <nl> + frame size : 1 <nl> parameter count : 1 <nl> - bytecode array length : 14 <nl> + bytecode array length : 10 <nl> bytecodes : [ <nl> / * 27 E > * / B ( StackCheck ) , <nl> - / * 32 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 1 ) , <nl> - B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> + / * 32 S > * / B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> B ( Star ) , R ( 0 ) , <nl> - / * 39 E > * / B ( Call0 ) , R ( 0 ) , R ( 1 ) , U8 ( 2 ) , <nl> + / * 39 E > * / B ( CallUndefinedReceiver0 ) , R ( 0 ) , U8 ( 2 ) , <nl> / * 44 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> snippet : " <nl> function f ( ) { return t ( 1 , 2 , 3 ) ; } <nl> f ( ) ; <nl> " <nl> - frame size : 5 <nl> + frame size : 4 <nl> parameter count : 1 <nl> - bytecode array length : 27 <nl> + bytecode array length : 24 <nl> bytecodes : [ <nl> / * 34 E > * / B ( StackCheck ) , <nl> - / * 39 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 1 ) , <nl> - B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> + / * 39 S > * / B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> B ( Star ) , R ( 0 ) , <nl> B ( LdaSmi ) , I8 ( 1 ) , <nl> - B ( Star ) , R ( 2 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> B ( LdaSmi ) , I8 ( 2 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaSmi ) , I8 ( 3 ) , <nl> - B ( Star ) , R ( 4 ) , <nl> - / * 46 E > * / B ( Call ) , R ( 0 ) , R ( 1 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 3 ) , <nl> + / * 46 E > * / B ( CallUndefinedReceiver ) , R ( 0 ) , R ( 1 ) , U8 ( 3 ) , U8 ( 2 ) , <nl> / * 58 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> mmm a / test / cctest / interpreter / bytecode_expectations / CallLookupSlot . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / CallLookupSlot . golden <nl> wrap : yes <nl> snippet : " <nl> g = function ( ) { } ; eval ( ' ' ) ; return g ( ) ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 81 <nl> + bytecode array length : 73 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> / * 30 E > * / B ( StackCheck ) , <nl> / * 34 S > * / B ( CreateClosure ) , U8 ( 0 ) , U8 ( 2 ) , U8 ( 2 ) , <nl> / * 36 E > * / B ( StaLookupSlotSloppy ) , U8 ( 1 ) , <nl> - / * 52 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 52 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 2 ) , U8 ( 5 ) , U8 ( 1 ) , <nl> + / * 52 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 2 ) , U8 ( 5 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 3 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 30 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 52 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 52 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 3 ) , <nl> - / * 62 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 69 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 1 ) , U8 ( 9 ) , U8 ( 1 ) , <nl> + / * 52 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 3 ) , <nl> + / * 62 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 1 ) , U8 ( 9 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 69 E > * / B ( Call0 ) , R ( 1 ) , R ( 2 ) , U8 ( 7 ) , <nl> + / * 69 E > * / B ( CallUndefinedReceiver0 ) , R ( 1 ) , U8 ( 7 ) , <nl> / * 74 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> mmm a / test / cctest / interpreter / bytecode_expectations / ClassAndSuperClass . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / ClassAndSuperClass . golden <nl> snippet : " <nl> " <nl> frame size : 6 <nl> parameter count : 1 <nl> - bytecode array length : 33 <nl> + bytecode array length : 34 <nl> bytecodes : [ <nl> B ( Mov ) , R ( closure ) , R ( 0 ) , <nl> / * 99 E > * / B ( StackCheck ) , <nl> bytecodes : [ <nl> B ( Mov ) , R ( this ) , R ( 3 ) , <nl> B ( CallRuntime ) , U16 ( Runtime : : kLoadFromSuper ) , R ( 3 ) , U8 ( 3 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 117 E > * / B ( Call0 ) , R ( 1 ) , R ( this ) , U8 ( 2 ) , <nl> + / * 117 E > * / B ( CallAnyReceiver ) , R ( 1 ) , R ( this ) , U8 ( 1 ) , U8 ( 2 ) , <nl> / * 126 E > * / B ( AddSmi ) , I8 ( 1 ) , U8 ( 8 ) , <nl> / * 131 S > * / B ( Return ) , <nl> ] <nl> mmm a / test / cctest / interpreter / bytecode_expectations / ContextVariables . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / ContextVariables . golden <nl> handlers : [ <nl> snippet : " <nl> var a ; ( function ( ) { a = 2 ; } ) ( ) ; return a ; <nl> " <nl> - frame size : 3 <nl> + frame size : 2 <nl> parameter count : 1 <nl> - bytecode array length : 21 <nl> + bytecode array length : 17 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 1 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> / * 30 E > * / B ( StackCheck ) , <nl> - / * 41 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> + / * 41 S > * / B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 64 E > * / B ( Call0 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> + / * 64 E > * / B ( CallUndefinedReceiver0 ) , R ( 1 ) , U8 ( 2 ) , <nl> / * 68 S > * / B ( LdaCurrentContextSlot ) , U8 ( 4 ) , <nl> / * 78 S > * / B ( Return ) , <nl> ] <nl> snippet : " <nl> var b = 100 ; <nl> return b <nl> " <nl> - frame size : 3 <nl> + frame size : 2 <nl> parameter count : 1 <nl> - bytecode array length : 791 <nl> + bytecode array length : 787 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 254 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> / * 3421 E > * / B ( StaCurrentContextSlot ) , U8 ( 254 ) , <nl> / * 3435 S > * / B ( LdaZero ) , <nl> / * 3435 E > * / B ( StaCurrentContextSlot ) , U8 ( 255 ) , <nl> - / * 3438 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> + / * 3438 S > * / B ( LdaGlobal ) , U8 ( 0 ) , U8 ( 4 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 3438 E > * / B ( Call0 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> + / * 3438 E > * / B ( CallUndefinedReceiver0 ) , R ( 1 ) , U8 ( 2 ) , <nl> / * 3454 S > * / B ( LdaSmi ) , I8 ( 100 ) , <nl> / * 3454 E > * / B ( Wide ) , B ( StaCurrentContextSlot ) , U16 ( 256 ) , <nl> / * 3459 S > * / B ( Wide ) , B ( LdaCurrentContextSlot ) , U16 ( 256 ) , <nl> mmm a / test / cctest / interpreter / bytecode_expectations / DeclareGlobals . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / DeclareGlobals . golden <nl> snippet : " <nl> " <nl> frame size : 4 <nl> parameter count : 1 <nl> - bytecode array length : 31 <nl> + bytecode array length : 27 <nl> bytecodes : [ <nl> B ( LdaConstant ) , U8 ( 0 ) , <nl> B ( Star ) , R ( 1 ) , <nl> bytecodes : [ <nl> B ( Mov ) , R ( closure ) , R ( 3 ) , <nl> B ( CallRuntime ) , U16 ( Runtime : : kDeclareGlobalsForInterpreter ) , R ( 1 ) , U8 ( 3 ) , <nl> / * 0 E > * / B ( StackCheck ) , <nl> - / * 16 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - B ( LdaGlobal ) , U8 ( 1 ) , U8 ( 2 ) , <nl> + / * 16 S > * / B ( LdaGlobal ) , U8 ( 1 ) , U8 ( 2 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 16 E > * / B ( Call0 ) , R ( 1 ) , R ( 2 ) , U8 ( 5 ) , <nl> + / * 16 E > * / B ( CallUndefinedReceiver0 ) , R ( 1 ) , U8 ( 5 ) , <nl> B ( Star ) , R ( 0 ) , <nl> / * 20 S > * / B ( Return ) , <nl> ] <nl> mmm a / test / cctest / interpreter / bytecode_expectations / Eval . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / Eval . golden <nl> wrap : yes <nl> snippet : " <nl> return eval ( ' 1 ; ' ) ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 62 <nl> + bytecode array length : 58 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( StaCurrentContextSlot ) , U8 ( 5 ) , <nl> / * 30 E > * / B ( StackCheck ) , <nl> - / * 34 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 41 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 34 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 30 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 41 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 41 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 41 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 53 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> mmm a / test / cctest / interpreter / bytecode_expectations / FunctionLiterals . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / FunctionLiterals . golden <nl> handlers : [ <nl> snippet : " <nl> return ( function ( ) { } ) ( ) <nl> " <nl> - frame size : 2 <nl> + frame size : 1 <nl> parameter count : 1 <nl> - bytecode array length : 15 <nl> + bytecode array length : 11 <nl> bytecodes : [ <nl> / * 30 E > * / B ( StackCheck ) , <nl> - / * 34 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 1 ) , <nl> - B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> + / * 34 S > * / B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> B ( Star ) , R ( 0 ) , <nl> - / * 56 E > * / B ( Call0 ) , R ( 0 ) , R ( 1 ) , U8 ( 2 ) , <nl> + / * 56 E > * / B ( CallUndefinedReceiver0 ) , R ( 0 ) , U8 ( 2 ) , <nl> / * 59 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> handlers : [ <nl> snippet : " <nl> return ( function ( x ) { return x ; } ) ( 1 ) <nl> " <nl> - frame size : 3 <nl> + frame size : 2 <nl> parameter count : 1 <nl> - bytecode array length : 20 <nl> + bytecode array length : 16 <nl> bytecodes : [ <nl> / * 30 E > * / B ( StackCheck ) , <nl> - / * 34 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 1 ) , <nl> - B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> + / * 34 S > * / B ( CreateClosure ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 2 ) , <nl> B ( Star ) , R ( 0 ) , <nl> B ( LdaSmi ) , I8 ( 1 ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 67 E > * / B ( Call1 ) , R ( 0 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 1 ) , <nl> + / * 67 E > * / B ( CallUndefinedReceiver1 ) , R ( 0 ) , R ( 1 ) , U8 ( 2 ) , <nl> / * 71 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> mmm a / test / cctest / interpreter / bytecode_expectations / LookupSlot . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / LookupSlot . golden <nl> test function name : f <nl> snippet : " <nl> eval ( ' var x = 10 ; ' ) ; return x ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 66 <nl> + bytecode array length : 62 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( StaCurrentContextSlot ) , U8 ( 5 ) , <nl> / * 10 E > * / B ( StackCheck ) , <nl> - / * 14 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 14 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 14 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 10 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 14 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 14 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 14 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 35 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 2 ) , U8 ( 6 ) , U8 ( 1 ) , <nl> / * 45 S > * / B ( Return ) , <nl> ] <nl> handlers : [ <nl> snippet : " <nl> eval ( ' var x = 10 ; ' ) ; return typeof x ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 67 <nl> + bytecode array length : 63 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( StaCurrentContextSlot ) , U8 ( 5 ) , <nl> / * 10 E > * / B ( StackCheck ) , <nl> - / * 14 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 14 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 14 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 10 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 14 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 14 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 14 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 35 S > * / B ( LdaLookupGlobalSlotInsideTypeof ) , U8 ( 2 ) , U8 ( 6 ) , U8 ( 1 ) , <nl> B ( TypeOf ) , <nl> / * 52 S > * / B ( Return ) , <nl> handlers : [ <nl> snippet : " <nl> x = 20 ; return eval ( ' ' ) ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 66 <nl> + bytecode array length : 62 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> / * 10 E > * / B ( StackCheck ) , <nl> / * 14 S > * / B ( LdaSmi ) , I8 ( 20 ) , <nl> / * 16 E > * / B ( StaLookupSlotSloppy ) , U8 ( 0 ) , <nl> - / * 22 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 29 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 1 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 22 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 1 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 2 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 10 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 29 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 29 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 29 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 39 S > * / B ( Return ) , <nl> ] <nl> constant pool : [ <nl> snippet : " <nl> } <nl> f ( ) ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 66 <nl> + bytecode array length : 62 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( StaCurrentContextSlot ) , U8 ( 5 ) , <nl> / * 38 E > * / B ( StackCheck ) , <nl> - / * 44 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 44 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 44 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 38 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 44 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 44 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 44 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 66 S > * / B ( LdaLookupContextSlot ) , U8 ( 2 ) , U8 ( 6 ) , U8 ( 1 ) , <nl> / * 76 S > * / B ( Return ) , <nl> ] <nl> snippet : " <nl> } <nl> f ( ) ; <nl> " <nl> - frame size : 10 <nl> + frame size : 9 <nl> parameter count : 1 <nl> - bytecode array length : 66 <nl> + bytecode array length : 62 <nl> bytecodes : [ <nl> B ( CreateFunctionContext ) , U8 ( 3 ) , <nl> B ( PushContext ) , R ( 0 ) , <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( StaCurrentContextSlot ) , U8 ( 5 ) , <nl> / * 34 E > * / B ( StackCheck ) , <nl> - / * 40 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 2 ) , <nl> - / * 40 E > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> + / * 40 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 0 ) , U8 ( 4 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 1 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 3 ) , <nl> + B ( Star ) , R ( 2 ) , <nl> B ( LdaZero ) , <nl> - B ( Star ) , R ( 7 ) , <nl> + B ( Star ) , R ( 6 ) , <nl> B ( LdaSmi ) , I8 ( 34 ) , <nl> - B ( Star ) , R ( 8 ) , <nl> + B ( Star ) , R ( 7 ) , <nl> B ( LdaSmi ) , I8 ( 40 ) , <nl> - B ( Star ) , R ( 9 ) , <nl> - B ( Mov ) , R ( 1 ) , R ( 4 ) , <nl> - B ( Mov ) , R ( 3 ) , R ( 5 ) , <nl> - B ( Mov ) , R ( closure ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 4 ) , U8 ( 6 ) , <nl> + B ( Star ) , R ( 8 ) , <nl> + B ( Mov ) , R ( 1 ) , R ( 3 ) , <nl> + B ( Mov ) , R ( 2 ) , R ( 4 ) , <nl> + B ( Mov ) , R ( closure ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kResolvePossiblyDirectEval ) , R ( 3 ) , U8 ( 6 ) , <nl> B ( Star ) , R ( 1 ) , <nl> - / * 40 E > * / B ( Call1 ) , R ( 1 ) , R ( 2 ) , R ( 3 ) , U8 ( 2 ) , <nl> + / * 40 E > * / B ( CallUndefinedReceiver1 ) , R ( 1 ) , R ( 2 ) , U8 ( 2 ) , <nl> / * 62 S > * / B ( LdaLookupGlobalSlot ) , U8 ( 2 ) , U8 ( 6 ) , U8 ( 1 ) , <nl> / * 72 S > * / B ( Return ) , <nl> ] <nl> mmm a / test / cctest / interpreter / bytecode_expectations / Modules . golden <nl> ppp b / test / cctest / interpreter / bytecode_expectations / Modules . golden <nl> snippet : " <nl> " <nl> frame size : 10 <nl> parameter count : 2 <nl> - bytecode array length : 213 <nl> + bytecode array length : 205 <nl> bytecodes : [ <nl> B ( Ldar ) , R ( new_target ) , <nl> B ( JumpIfUndefined ) , U8 ( 27 ) , <nl> bytecodes : [ <nl> / * 64 S > * / B ( Return ) , <nl> B ( Ldar ) , R ( 6 ) , <nl> / * 0 E > * / B ( Throw ) , <nl> - / * 32 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 5 ) , <nl> - / * 32 E > * / B ( LdaModuleVariable ) , I8 ( - 1 ) , U8 ( 0 ) , <nl> + / * 32 S > * / B ( LdaModuleVariable ) , I8 ( - 1 ) , U8 ( 0 ) , <nl> B ( JumpIfNotHole ) , U8 ( 11 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kThrowReferenceError ) , R ( 6 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kThrowReferenceError ) , R ( 5 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 4 ) , <nl> B ( LdaSmi ) , I8 ( 42 ) , <nl> - B ( Star ) , R ( 6 ) , <nl> - / * 32 E > * / B ( Call1 ) , R ( 4 ) , R ( 5 ) , R ( 6 ) , U8 ( 2 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + / * 32 E > * / B ( CallUndefinedReceiver1 ) , R ( 4 ) , R ( 5 ) , U8 ( 2 ) , <nl> B ( Ldar ) , R ( closure ) , <nl> B ( CreateBlockContext ) , U8 ( 2 ) , <nl> B ( PushContext ) , R ( 1 ) , <nl> bytecodes : [ <nl> B ( StaCurrentContextSlot ) , U8 ( 4 ) , <nl> / * 47 S > * / B ( LdaUndefined ) , <nl> / * 47 E > * / B ( StaCurrentContextSlot ) , U8 ( 4 ) , <nl> - / * 52 S > * / B ( LdaUndefined ) , <nl> - B ( Star ) , R ( 5 ) , <nl> - / * 52 E > * / B ( LdaModuleVariable ) , I8 ( - 1 ) , U8 ( 1 ) , <nl> + / * 52 S > * / B ( LdaModuleVariable ) , I8 ( - 1 ) , U8 ( 1 ) , <nl> B ( JumpIfNotHole ) , U8 ( 11 ) , <nl> B ( LdaConstant ) , U8 ( 1 ) , <nl> - B ( Star ) , R ( 6 ) , <nl> - B ( CallRuntime ) , U16 ( Runtime : : kThrowReferenceError ) , R ( 6 ) , U8 ( 1 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + B ( CallRuntime ) , U16 ( Runtime : : kThrowReferenceError ) , R ( 5 ) , U8 ( 1 ) , <nl> B ( Star ) , R ( 4 ) , <nl> B ( LdaSmi ) , I8 ( 42 ) , <nl> - B ( Star ) , R ( 6 ) , <nl> - / * 52 E > * / B ( Call1 ) , R ( 4 ) , R ( 5 ) , R ( 6 ) , U8 ( 4 ) , <nl> + B ( Star ) , R ( 5 ) , <nl> + / * 52 E > * / B ( CallUndefinedReceiver1 ) , R ( 4 ) , R ( 5 ) , U8 ( 4 ) , <nl> B ( StaContextSlot ) , R ( 1 ) , U8 ( 6 ) , U8 ( 0 ) , <nl> B ( PopContext ) , R ( 1 ) , <nl> B ( LdaCurrentContextSlot ) , U8 ( 6 ) , <nl> mmm a / test / cctest / interpreter / test - interpreter . cc <nl> ppp b / test / cctest / interpreter / test - interpreter . cc <nl> static void TestInterpreterCall ( TailCallMode tail_call_mode ) { <nl> . StoreAccumulatorInRegister ( reg ) <nl> . MoveRegister ( builder . Receiver ( ) , args [ 0 ] ) ; <nl> <nl> - builder . Call ( reg , args , call_slot_index , Call : : GLOBAL_CALL , tail_call_mode ) ; <nl> + if ( tail_call_mode = = TailCallMode : : kAllow ) { <nl> + builder . TailCall ( reg , args , call_slot_index ) ; <nl> + } else { <nl> + builder . CallProperty ( reg , args , call_slot_index ) ; <nl> + } <nl> <nl> builder . Return ( ) ; <nl> ast_factory . Internalize ( isolate ) ; <nl> static void TestInterpreterCall ( TailCallMode tail_call_mode ) { <nl> builder . LoadNamedProperty ( builder . Receiver ( ) , name , slot_index ) <nl> . StoreAccumulatorInRegister ( reg ) <nl> . MoveRegister ( builder . Receiver ( ) , args [ 0 ] ) ; <nl> - builder . Call ( reg , args , call_slot_index , Call : : GLOBAL_CALL , tail_call_mode ) ; <nl> + if ( tail_call_mode = = TailCallMode : : kAllow ) { <nl> + builder . TailCall ( reg , args , call_slot_index ) ; <nl> + } else { <nl> + builder . CallProperty ( reg , args , call_slot_index ) ; <nl> + } <nl> builder . Return ( ) ; <nl> ast_factory . Internalize ( isolate ) ; <nl> Handle < BytecodeArray > bytecode_array = builder . ToBytecodeArray ( isolate ) ; <nl> static void TestInterpreterCall ( TailCallMode tail_call_mode ) { <nl> . LoadLiteral ( Smi : : FromInt ( 11 ) ) <nl> . StoreAccumulatorInRegister ( args [ 2 ] ) ; <nl> <nl> - builder . Call ( reg , args , call_slot_index , Call : : GLOBAL_CALL , tail_call_mode ) ; <nl> + if ( tail_call_mode = = TailCallMode : : kAllow ) { <nl> + builder . TailCall ( reg , args , call_slot_index ) ; <nl> + } else { <nl> + builder . CallProperty ( reg , args , call_slot_index ) ; <nl> + } <nl> <nl> builder . Return ( ) ; <nl> <nl> static void TestInterpreterCall ( TailCallMode tail_call_mode ) { <nl> . LoadLiteral ( ast_factory . NewString ( ast_factory . GetOneByteString ( " j " ) ) ) <nl> . StoreAccumulatorInRegister ( args [ 10 ] ) ; <nl> <nl> - builder . Call ( reg , args , call_slot_index , Call : : GLOBAL_CALL , tail_call_mode ) ; <nl> + if ( tail_call_mode = = TailCallMode : : kAllow ) { <nl> + builder . TailCall ( reg , args , call_slot_index ) ; <nl> + } else { <nl> + builder . CallProperty ( reg , args , call_slot_index ) ; <nl> + } <nl> <nl> builder . Return ( ) ; <nl> <nl> mmm a / test / unittests / interpreter / bytecode - array - builder - unittest . cc <nl> ppp b / test / unittests / interpreter / bytecode - array - builder - unittest . cc <nl> TEST_F ( BytecodeArrayBuilderTest , AllBytecodesGenerated ) { <nl> Register reg ( 0 ) ; <nl> Register other ( reg . index ( ) + 1 ) ; <nl> Register wide ( 128 ) ; <nl> - RegisterList reg_list ; <nl> - RegisterList single ( 0 , 1 ) , pair ( 0 , 2 ) , triple ( 0 , 3 ) ; <nl> + RegisterList reg_list ( 0 , 10 ) ; <nl> + RegisterList empty , single ( 0 , 1 ) , pair ( 0 , 2 ) , triple ( 0 , 3 ) ; <nl> <nl> / / Emit argument creation operations . <nl> builder . CreateArguments ( CreateArgumentsType : : kMappedArguments ) <nl> TEST_F ( BytecodeArrayBuilderTest , AllBytecodesGenerated ) { <nl> builder . CreateObjectLiteral ( 0 , 0 , 0 , reg ) ; <nl> <nl> / / Call operations . <nl> - builder . Call ( reg , reg_list , 1 , Call : : GLOBAL_CALL ) <nl> - . Call ( reg , single , 1 , Call : : GLOBAL_CALL ) <nl> - . Call ( reg , pair , 1 , Call : : GLOBAL_CALL ) <nl> - . Call ( reg , triple , 1 , Call : : GLOBAL_CALL ) <nl> - . Call ( reg , reg_list , 1 , Call : : NAMED_PROPERTY_CALL , <nl> - TailCallMode : : kDisallow ) <nl> - . Call ( reg , single , 1 , Call : : NAMED_PROPERTY_CALL ) <nl> - . Call ( reg , pair , 1 , Call : : NAMED_PROPERTY_CALL ) <nl> - . Call ( reg , triple , 1 , Call : : NAMED_PROPERTY_CALL ) <nl> - . Call ( reg , reg_list , 1 , Call : : GLOBAL_CALL , TailCallMode : : kAllow ) <nl> + builder . CallAnyReceiver ( reg , reg_list , 1 ) <nl> + . CallProperty ( reg , reg_list , 1 ) <nl> + . CallProperty ( reg , single , 1 ) <nl> + . CallProperty ( reg , pair , 1 ) <nl> + . CallProperty ( reg , triple , 1 ) <nl> + . CallUndefinedReceiver ( reg , reg_list , 1 ) <nl> + . CallUndefinedReceiver ( reg , empty , 1 ) <nl> + . CallUndefinedReceiver ( reg , single , 1 ) <nl> + . CallUndefinedReceiver ( reg , pair , 1 ) <nl> + . TailCall ( reg , reg_list , 1 ) <nl> . CallRuntime ( Runtime : : kIsArray , reg ) <nl> . CallRuntimeForPair ( Runtime : : kLoadLookupSlotForCall , reg_list , pair ) <nl> . CallJSRuntime ( Context : : SPREAD_ITERABLE_INDEX , reg_list ) <nl> mmm a / test / unittests / interpreter / bytecode - decoder - unittest . cc <nl> ppp b / test / unittests / interpreter / bytecode - decoder - unittest . cc <nl> TEST ( BytecodeDecoder , DecodeBytecodeAndOperands ) { <nl> " LdaSmi . ExtraWide [ - 100000 ] " } , <nl> { { B ( Star ) , R8 ( 5 ) } , 2 , 0 , " Star r5 " } , <nl> { { B ( Wide ) , B ( Star ) , R16 ( 136 ) } , 4 , 0 , " Star . Wide r136 " } , <nl> - { { B ( Wide ) , B ( Call ) , R16 ( 134 ) , R16 ( 135 ) , U16 ( 10 ) , U16 ( 177 ) } , <nl> + { { B ( Wide ) , B ( CallAnyReceiver ) , R16 ( 134 ) , R16 ( 135 ) , U16 ( 10 ) , U16 ( 177 ) } , <nl> 10 , <nl> 0 , <nl> - " Call . Wide r134 , r135 - r144 , [ 177 ] " } , <nl> + " CallAnyReceiver . Wide r134 , r135 - r144 , [ 177 ] " } , <nl> { { B ( ForInPrepare ) , R8 ( 10 ) , R8 ( 11 ) } , <nl> 3 , <nl> 0 , <nl> mmm a / test / unittests / interpreter / interpreter - assembler - unittest . cc <nl> ppp b / test / unittests / interpreter / interpreter - assembler - unittest . cc <nl> TARGET_TEST_F ( InterpreterAssemblerTest , CallRuntime ) { <nl> } <nl> <nl> TARGET_TEST_F ( InterpreterAssemblerTest , CallJS ) { <nl> - TailCallMode tail_call_modes [ ] = { TailCallMode : : kDisallow , <nl> - TailCallMode : : kAllow } ; <nl> - TRACED_FOREACH ( TailCallMode , tail_call_mode , tail_call_modes ) { <nl> - TRACED_FOREACH ( interpreter : : Bytecode , bytecode , kBytecodes ) { <nl> - if ( Bytecodes : : IsCallOrConstruct ( bytecode ) ) { <nl> - InterpreterAssemblerTestState state ( this , bytecode ) ; <nl> - InterpreterAssemblerForTest m ( & state , bytecode ) ; <nl> - Callable builtin = CodeFactory : : InterpreterPushArgsAndCall ( <nl> - isolate ( ) , tail_call_mode , InterpreterPushArgsMode : : kOther ) ; <nl> - Node * function = m . IntPtrConstant ( 0 ) ; <nl> - Node * first_arg = m . IntPtrConstant ( 1 ) ; <nl> - Node * arg_count = m . Int32Constant ( 2 ) ; <nl> - Node * context = m . IntPtrConstant ( 3 ) ; <nl> - Node * call_js = <nl> - m . CallJS ( function , context , first_arg , arg_count , tail_call_mode ) ; <nl> - EXPECT_THAT ( call_js , <nl> - IsCall ( _ , IsHeapConstant ( builtin . code ( ) ) , arg_count , <nl> - first_arg , function , context , _ , _ ) ) ; <nl> - } <nl> + TRACED_FOREACH ( interpreter : : Bytecode , bytecode , kBytecodes ) { <nl> + if ( Bytecodes : : IsCallOrConstruct ( bytecode ) & & <nl> + bytecode ! = Bytecode : : kCallWithSpread ) { <nl> + InterpreterAssemblerTestState state ( this , bytecode ) ; <nl> + InterpreterAssemblerForTest m ( & state , bytecode ) ; <nl> + ConvertReceiverMode receiver_mode = Bytecodes : : GetReceiverMode ( bytecode ) ; <nl> + TailCallMode tail_call_mode = ( bytecode = = Bytecode : : kTailCall ) <nl> + ? TailCallMode : : kAllow <nl> + : TailCallMode : : kDisallow ; <nl> + <nl> + Callable builtin = CodeFactory : : InterpreterPushArgsThenCall ( <nl> + isolate ( ) , receiver_mode , tail_call_mode , <nl> + InterpreterPushArgsMode : : kOther ) ; <nl> + Node * function = m . IntPtrConstant ( 0 ) ; <nl> + Node * first_arg = m . IntPtrConstant ( 1 ) ; <nl> + Node * arg_count = m . Int32Constant ( 2 ) ; <nl> + Node * context = m . IntPtrConstant ( 3 ) ; <nl> + Node * call_js = m . CallJS ( function , context , first_arg , arg_count , <nl> + receiver_mode , tail_call_mode ) ; <nl> + EXPECT_THAT ( call_js , IsCall ( _ , IsHeapConstant ( builtin . code ( ) ) , arg_count , <nl> + first_arg , function , context , _ , _ ) ) ; <nl> } <nl> } <nl> } <nl>
[ ignition ] Add call bytecodes for undefined receiver
v8/v8
751e89359123df4f6e5f0b28b89fcdf63ed16a77
2017-04-10T15:30:11Z
mmm a / HISTORY . md <nl> ppp b / HISTORY . md <nl> <nl> * Block - based table index now contains exact highest key in the file , rather than an upper bound . This may improve Get ( ) and iterator Seek ( ) performance in some situations , especially when direct IO is enabled and block cache is disabled . A setting BlockBasedTableOptions : : index_shortening is introduced to control this behavior . Set it to kShortenSeparatorsAndSuccessor to get the old behavior . <nl> * When reading from option file / string / map , customized envs can be filled according to object registry . <nl> * Improve range scan performance when using explicit user readahead by not creating new table readers for every iterator . <nl> + * Add index type BlockBasedTableOptions : : IndexType : : kBinarySearchWithFirstKey . It significantly reduces read amplification in some setups , especially for iterator seeks . It ' s not fully implemented yet : IO errors are not handled right . <nl> <nl> # # # Public API Change <nl> * Change the behavior of OptimizeForPointLookup ( ) : move away from hash - based block - based - table index , and use whole key memtable filtering . <nl> mmm a / db / db_iterator_test . cc <nl> ppp b / db / db_iterator_test . cc <nl> TEST_P ( DBIteratorTest , DBIteratorBoundOptimizationTest ) { <nl> ASSERT_EQ ( upper_bound_hits , 1 ) ; <nl> } <nl> } <nl> + <nl> + / / Enable kBinarySearchWithFirstKey , do some iterator operations and check that <nl> + / / they don ' t do unnecessary block reads . <nl> + TEST_P ( DBIteratorTest , IndexWithFirstKey ) { <nl> + for ( int tailing = 0 ; tailing < 2 ; + + tailing ) { <nl> + SCOPED_TRACE ( " tailing = " + std : : to_string ( tailing ) ) ; <nl> + Options options = CurrentOptions ( ) ; <nl> + options . env = env_ ; <nl> + options . create_if_missing = true ; <nl> + options . prefix_extractor = nullptr ; <nl> + options . merge_operator = MergeOperators : : CreateStringAppendOperator ( ) ; <nl> + options . statistics = rocksdb : : CreateDBStatistics ( ) ; <nl> + Statistics * stats = options . statistics . get ( ) ; <nl> + BlockBasedTableOptions table_options ; <nl> + table_options . index_type = <nl> + BlockBasedTableOptions : : IndexType : : kBinarySearchWithFirstKey ; <nl> + table_options . index_shortening = <nl> + BlockBasedTableOptions : : IndexShorteningMode : : kNoShortening ; <nl> + table_options . flush_block_policy_factory = <nl> + std : : make_shared < FlushBlockEveryKeyPolicyFactory > ( ) ; <nl> + table_options . block_cache = NewLRUCache ( 1000 ) ; / / fits all blocks <nl> + options . table_factory . reset ( NewBlockBasedTableFactory ( table_options ) ) ; <nl> + <nl> + DestroyAndReopen ( options ) ; <nl> + ASSERT_OK ( Merge ( " a1 " , " x1 " ) ) ; <nl> + ASSERT_OK ( Merge ( " b1 " , " y1 " ) ) ; <nl> + ASSERT_OK ( Merge ( " c0 " , " z1 " ) ) ; <nl> + ASSERT_OK ( Flush ( ) ) ; <nl> + ASSERT_OK ( Merge ( " a2 " , " x2 " ) ) ; <nl> + ASSERT_OK ( Merge ( " b2 " , " y2 " ) ) ; <nl> + ASSERT_OK ( Merge ( " c0 " , " z2 " ) ) ; <nl> + ASSERT_OK ( Flush ( ) ) ; <nl> + ASSERT_OK ( Merge ( " a3 " , " x3 " ) ) ; <nl> + ASSERT_OK ( Merge ( " b3 " , " y3 " ) ) ; <nl> + ASSERT_OK ( Merge ( " c3 " , " z3 " ) ) ; <nl> + ASSERT_OK ( Flush ( ) ) ; <nl> + <nl> + / / Block cache is not important for this test . <nl> + / / We use BLOCK_CACHE_DATA_ * counters just because they ' re the most readily <nl> + / / available way of counting block accesses . <nl> + <nl> + ReadOptions ropt ; <nl> + ropt . tailing = tailing ; <nl> + std : : unique_ptr < Iterator > iter ( NewIterator ( ropt ) ) ; <nl> + <nl> + iter - > Seek ( " b10 " ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( " b2 " , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( " y2 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 1 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( " b3 " , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( " y3 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 2 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + iter - > Seek ( " c0 " ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( " c0 " , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( " z1 , z2 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 4 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( " c3 " , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( " z3 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 5 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + iter . reset ( ) ; <nl> + <nl> + / / Enable iterate_upper_bound and check that iterator is not trying to read <nl> + / / blocks that are fully above upper bound . <nl> + std : : string ub = " b3 " ; <nl> + Slice ub_slice ( ub ) ; <nl> + ropt . iterate_upper_bound = & ub_slice ; <nl> + iter . reset ( NewIterator ( ropt ) ) ; <nl> + <nl> + iter - > Seek ( " b2 " ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( " b2 " , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( " y2 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 1 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 5 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_FALSE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( 1 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 5 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_P ( DBIteratorTest , IndexWithFirstKeyGet ) { <nl> + Options options = CurrentOptions ( ) ; <nl> + options . env = env_ ; <nl> + options . create_if_missing = true ; <nl> + options . prefix_extractor = nullptr ; <nl> + options . merge_operator = MergeOperators : : CreateStringAppendOperator ( ) ; <nl> + options . statistics = rocksdb : : CreateDBStatistics ( ) ; <nl> + Statistics * stats = options . statistics . get ( ) ; <nl> + BlockBasedTableOptions table_options ; <nl> + table_options . index_type = <nl> + BlockBasedTableOptions : : IndexType : : kBinarySearchWithFirstKey ; <nl> + table_options . index_shortening = <nl> + BlockBasedTableOptions : : IndexShorteningMode : : kNoShortening ; <nl> + table_options . flush_block_policy_factory = <nl> + std : : make_shared < FlushBlockEveryKeyPolicyFactory > ( ) ; <nl> + table_options . block_cache = NewLRUCache ( 1000 ) ; / / fits all blocks <nl> + options . table_factory . reset ( NewBlockBasedTableFactory ( table_options ) ) ; <nl> + <nl> + DestroyAndReopen ( options ) ; <nl> + ASSERT_OK ( Merge ( " a " , " x1 " ) ) ; <nl> + ASSERT_OK ( Merge ( " c " , " y1 " ) ) ; <nl> + ASSERT_OK ( Merge ( " e " , " z1 " ) ) ; <nl> + ASSERT_OK ( Flush ( ) ) ; <nl> + ASSERT_OK ( Merge ( " c " , " y2 " ) ) ; <nl> + ASSERT_OK ( Merge ( " e " , " z2 " ) ) ; <nl> + ASSERT_OK ( Flush ( ) ) ; <nl> + <nl> + / / Get ( ) between blocks shouldn ' t read any blocks . <nl> + ASSERT_EQ ( " NOT_FOUND " , Get ( " b " ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Get ( ) of an existing key shouldn ' t read any unnecessary blocks when there ' s <nl> + / / only one key per block . <nl> + <nl> + ASSERT_EQ ( " y1 , y2 " , Get ( " c " ) ) ; <nl> + EXPECT_EQ ( 2 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + ASSERT_EQ ( " x1 " , Get ( " a " ) ) ; <nl> + EXPECT_EQ ( 3 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + EXPECT_EQ ( std : : vector < std : : string > ( { " NOT_FOUND " , " z1 , z2 " } ) , <nl> + MultiGet ( { " b " , " e " } ) ) ; <nl> + } <nl> + <nl> / / TODO ( 3 . 13 ) : fix the issue of Seek ( ) + Prev ( ) which might not necessary <nl> / / return the biggest key which is smaller than the seek key . <nl> TEST_P ( DBIteratorTest , PrevAfterAndNextAfterMerge ) { <nl> mmm a / include / rocksdb / table . h <nl> ppp b / include / rocksdb / table . h <nl> struct BlockBasedTableOptions { <nl> enum IndexType : char { <nl> / / A space efficient index block that is optimized for <nl> / / binary - search - based index . <nl> - kBinarySearch , <nl> + kBinarySearch = 0x00 , <nl> <nl> / / The hash index , if enabled , will do the hash lookup when <nl> / / ` Options . prefix_extractor ` is provided . <nl> - kHashSearch , <nl> + kHashSearch = 0x01 , <nl> <nl> / / A two - level index implementation . Both levels are binary search indexes . <nl> - kTwoLevelIndexSearch , <nl> + kTwoLevelIndexSearch = 0x02 , <nl> + <nl> + / / Like kBinarySearch , but index also contains first key of each block . <nl> + / / This allows iterators to defer reading the block until it ' s actually <nl> + / / needed . May significantly reduce read amplification of short range scans . <nl> + / / Without it , iterator seek usually reads one block from each level - 0 file <nl> + / / and from each level , which may be expensive . <nl> + / / Works best in combination with : <nl> + / / - IndexShorteningMode : : kNoShortening , <nl> + / / - custom FlushBlockPolicy to cut blocks at some meaningful boundaries , <nl> + / / e . g . when prefix changes . <nl> + / / Makes the index significantly bigger ( 2x or more ) , especially when keys <nl> + / / are long . <nl> + / / <nl> + / / IO errors are not handled correctly in this mode right now : if an error <nl> + / / happens when lazily reading a block in value ( ) , value ( ) returns empty <nl> + / / slice , and you need to call Valid ( ) / status ( ) afterwards . <nl> + / / TODO ( kolmike ) : Fix it . <nl> + kBinarySearchWithFirstKey = 0x03 , <nl> } ; <nl> <nl> IndexType index_type = kBinarySearch ; <nl> mmm a / java / rocksjni / portal . h <nl> ppp b / java / rocksjni / portal . h <nl> class IndexTypeJni { <nl> return 0x0 ; <nl> case rocksdb : : BlockBasedTableOptions : : IndexType : : kHashSearch : <nl> return 0x1 ; <nl> - case rocksdb : : BlockBasedTableOptions : : IndexType : : kTwoLevelIndexSearch : <nl> + case rocksdb : : BlockBasedTableOptions : : IndexType : : kTwoLevelIndexSearch : <nl> return 0x2 ; <nl> + case rocksdb : : BlockBasedTableOptions : : IndexType : : kBinarySearchWithFirstKey : <nl> + return 0x3 ; <nl> default : <nl> return 0x7F ; / / undefined <nl> } <nl> class IndexTypeJni { <nl> return rocksdb : : BlockBasedTableOptions : : IndexType : : kHashSearch ; <nl> case 0x2 : <nl> return rocksdb : : BlockBasedTableOptions : : IndexType : : kTwoLevelIndexSearch ; <nl> + case 0x3 : <nl> + return rocksdb : : BlockBasedTableOptions : : IndexType : : <nl> + kBinarySearchWithFirstKey ; <nl> default : <nl> / / undefined / default <nl> return rocksdb : : BlockBasedTableOptions : : IndexType : : kBinarySearch ; <nl> mmm a / options / options_helper . cc <nl> ppp b / options / options_helper . cc <nl> std : : unordered_map < std : : string , BlockBasedTableOptions : : IndexType > <nl> { " kBinarySearch " , BlockBasedTableOptions : : IndexType : : kBinarySearch } , <nl> { " kHashSearch " , BlockBasedTableOptions : : IndexType : : kHashSearch } , <nl> { " kTwoLevelIndexSearch " , <nl> - BlockBasedTableOptions : : IndexType : : kTwoLevelIndexSearch } } ; <nl> + BlockBasedTableOptions : : IndexType : : kTwoLevelIndexSearch } , <nl> + { " kBinarySearchWithFirstKey " , <nl> + BlockBasedTableOptions : : IndexType : : kBinarySearchWithFirstKey } } ; <nl> <nl> std : : unordered_map < std : : string , BlockBasedTableOptions : : DataBlockIndexType > <nl> OptionsHelper : : block_base_table_data_block_index_type_string_map = { <nl> mmm a / table / block_based / block . cc <nl> ppp b / table / block_based / block . cc <nl> bool IndexBlockIter : : ParseNextIndexKey ( ) { <nl> } <nl> / / else we are in the middle of a restart interval and the restart_index_ <nl> / / thus has not changed <nl> - if ( value_delta_encoded_ ) { <nl> - assert ( value_length = = 0 ) ; <nl> + if ( value_delta_encoded_ | | global_seqno_state_ ! = nullptr ) { <nl> DecodeCurrentValue ( shared ) ; <nl> } <nl> return true ; <nl> bool IndexBlockIter : : ParseNextIndexKey ( ) { <nl> / / Otherwise the format is delta - size = block handle size - size of last block <nl> / / handle . <nl> void IndexBlockIter : : DecodeCurrentValue ( uint32_t shared ) { <nl> - assert ( value_delta_encoded_ ) ; <nl> - const char * limit = data_ + restarts_ ; <nl> - if ( shared = = 0 ) { <nl> - uint64_t o , s ; <nl> - const char * newp = GetVarint64Ptr ( value_ . data ( ) , limit , & o ) ; <nl> - assert ( newp ) ; <nl> - newp = GetVarint64Ptr ( newp , limit , & s ) ; <nl> - assert ( newp ) ; <nl> - decoded_value_ = BlockHandle ( o , s ) ; <nl> - value_ = Slice ( value_ . data ( ) , newp - value_ . data ( ) ) ; <nl> - } else { <nl> - uint64_t next_value_base = <nl> - decoded_value_ . offset ( ) + decoded_value_ . size ( ) + kBlockTrailerSize ; <nl> - int64_t delta ; <nl> - const char * newp = GetVarsignedint64Ptr ( value_ . data ( ) , limit , & delta ) ; <nl> - decoded_value_ = <nl> - BlockHandle ( next_value_base , decoded_value_ . size ( ) + delta ) ; <nl> - value_ = Slice ( value_ . data ( ) , newp - value_ . data ( ) ) ; <nl> + Slice v ( value_ . data ( ) , data_ + restarts_ - value_ . data ( ) ) ; <nl> + / / Delta encoding is used if ` shared ` ! = 0 . <nl> + Status decode_s __attribute__ ( ( __unused__ ) ) = decoded_value_ . DecodeFrom ( <nl> + & v , have_first_key_ , <nl> + ( value_delta_encoded_ & & shared ) ? & decoded_value_ . handle : nullptr ) ; <nl> + assert ( decode_s . ok ( ) ) ; <nl> + value_ = Slice ( value_ . data ( ) , v . data ( ) - value_ . data ( ) ) ; <nl> + <nl> + if ( global_seqno_state_ ! = nullptr ) { <nl> + / / Overwrite sequence number the same way as in DataBlockIter . <nl> + <nl> + IterKey & first_internal_key = global_seqno_state_ - > first_internal_key ; <nl> + first_internal_key . SetInternalKey ( decoded_value_ . first_internal_key , <nl> + / * copy * / true ) ; <nl> + <nl> + assert ( GetInternalKeySeqno ( first_internal_key . GetInternalKey ( ) ) = = 0 ) ; <nl> + <nl> + ValueType value_type = ExtractValueType ( first_internal_key . GetKey ( ) ) ; <nl> + assert ( value_type = = ValueType : : kTypeValue | | <nl> + value_type = = ValueType : : kTypeMerge | | <nl> + value_type = = ValueType : : kTypeDeletion | | <nl> + value_type = = ValueType : : kTypeRangeDeletion ) ; <nl> + <nl> + first_internal_key . UpdateInternalKey ( global_seqno_state_ - > global_seqno , <nl> + value_type ) ; <nl> + decoded_value_ . first_internal_key = first_internal_key . GetKey ( ) ; <nl> } <nl> } <nl> <nl> Block : : Block ( BlockContents & & contents , SequenceNumber _global_seqno , <nl> } <nl> } <nl> <nl> - template < > <nl> - DataBlockIter * Block : : NewIterator ( const Comparator * cmp , const Comparator * ucmp , <nl> - DataBlockIter * iter , Statistics * stats , <nl> - bool / * total_order_seek * / , <nl> - bool / * key_includes_seq * / , <nl> - bool / * value_is_full * / , <nl> - bool block_contents_pinned , <nl> - BlockPrefixIndex * / * prefix_index * / ) { <nl> + DataBlockIter * Block : : NewDataIterator ( const Comparator * cmp , <nl> + const Comparator * ucmp , <nl> + DataBlockIter * iter , Statistics * stats , <nl> + bool block_contents_pinned ) { <nl> DataBlockIter * ret_iter ; <nl> if ( iter ! = nullptr ) { <nl> ret_iter = iter ; <nl> DataBlockIter * Block : : NewIterator ( const Comparator * cmp , const Comparator * ucmp , <nl> return ret_iter ; <nl> } <nl> <nl> - template < > <nl> - IndexBlockIter * Block : : NewIterator ( const Comparator * cmp , <nl> - const Comparator * ucmp , IndexBlockIter * iter , <nl> - Statistics * / * stats * / , bool total_order_seek , <nl> - bool key_includes_seq , bool value_is_full , <nl> - bool block_contents_pinned , <nl> - BlockPrefixIndex * prefix_index ) { <nl> + IndexBlockIter * Block : : NewIndexIterator ( <nl> + const Comparator * cmp , const Comparator * ucmp , IndexBlockIter * iter , <nl> + Statistics * / * stats * / , bool total_order_seek , bool have_first_key , <nl> + bool key_includes_seq , bool value_is_full , bool block_contents_pinned , <nl> + BlockPrefixIndex * prefix_index ) { <nl> IndexBlockIter * ret_iter ; <nl> if ( iter ! = nullptr ) { <nl> ret_iter = iter ; <nl> IndexBlockIter * Block : : NewIterator ( const Comparator * cmp , <nl> BlockPrefixIndex * prefix_index_ptr = <nl> total_order_seek ? nullptr : prefix_index ; <nl> ret_iter - > Initialize ( cmp , ucmp , data_ , restart_offset_ , num_restarts_ , <nl> - prefix_index_ptr , key_includes_seq , value_is_full , <nl> - block_contents_pinned , <nl> - nullptr / * data_block_hash_index * / ) ; <nl> + global_seqno_ , prefix_index_ptr , have_first_key , <nl> + key_includes_seq , value_is_full , <nl> + block_contents_pinned ) ; <nl> } <nl> <nl> return ret_iter ; <nl> mmm a / table / block_based / block . h <nl> ppp b / table / block_based / block . h <nl> class Block { <nl> / / If iter is null , return new Iterator <nl> / / If iter is not null , update this one and return it as Iterator * <nl> / / <nl> - / / key_includes_seq , default true , means that the keys are in internal key <nl> - / / format . <nl> - / / value_is_full , default true , means that no delta encoding is <nl> - / / applied to values . <nl> - / / <nl> - / / NewIterator < DataBlockIter > <nl> - / / Same as above but also updates read_amp_bitmap_ if it is not nullptr . <nl> - / / <nl> - / / NewIterator < IndexBlockIter > <nl> - / / If ` prefix_index ` is not nullptr this block will do hash lookup for the key <nl> - / / prefix . If total_order_seek is true , prefix_index_ is ignored . <nl> + / / Updates read_amp_bitmap_ if it is not nullptr . <nl> / / <nl> / / If ` block_contents_pinned ` is true , the caller will guarantee that when <nl> / / the cleanup functions are transferred from the iterator to other <nl> class Block { <nl> / / NOTE : for the hash based lookup , if a key prefix doesn ' t match any key , <nl> / / the iterator will simply be set as " invalid " , rather than returning <nl> / / the key that is just pass the target key . <nl> - template < typename TBlockIter > <nl> - TBlockIter * NewIterator ( <nl> - const Comparator * comparator , const Comparator * user_comparator , <nl> - TBlockIter * iter = nullptr , Statistics * stats = nullptr , <nl> - bool total_order_seek = true , bool key_includes_seq = true , <nl> - bool value_is_full = true , bool block_contents_pinned = false , <nl> - BlockPrefixIndex * prefix_index = nullptr ) ; <nl> + <nl> + DataBlockIter * NewDataIterator ( const Comparator * comparator , <nl> + const Comparator * user_comparator , <nl> + DataBlockIter * iter = nullptr , <nl> + Statistics * stats = nullptr , <nl> + bool block_contents_pinned = false ) ; <nl> + <nl> + / / key_includes_seq , default true , means that the keys are in internal key <nl> + / / format . <nl> + / / value_is_full , default true , means that no delta encoding is <nl> + / / applied to values . <nl> + / / <nl> + / / If ` prefix_index ` is not nullptr this block will do hash lookup for the key <nl> + / / prefix . If total_order_seek is true , prefix_index_ is ignored . <nl> + / / <nl> + / / ` have_first_key ` controls whether IndexValue will contain <nl> + / / first_internal_key . It affects data serialization format , so the same value <nl> + / / have_first_key must be used when writing and reading index . <nl> + / / It is determined by IndexType property of the table . <nl> + IndexBlockIter * NewIndexIterator ( const Comparator * comparator , <nl> + const Comparator * user_comparator , <nl> + IndexBlockIter * iter , Statistics * stats , <nl> + bool total_order_seek , bool have_first_key , <nl> + bool key_includes_seq , bool value_is_full , <nl> + bool block_contents_pinned = false , <nl> + BlockPrefixIndex * prefix_index = nullptr ) ; <nl> <nl> / / Report an approximation of how much memory has been used . <nl> size_t ApproximateMemoryUsage ( ) const ; <nl> class DataBlockIter final : public BlockIter < Slice > { <nl> bool SeekForGetImpl ( const Slice & target ) ; <nl> } ; <nl> <nl> - class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> + class IndexBlockIter final : public BlockIter < IndexValue > { <nl> public : <nl> IndexBlockIter ( ) : BlockIter ( ) , prefix_index_ ( nullptr ) { } <nl> <nl> class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> / / format . <nl> / / value_is_full , default true , means that no delta encoding is <nl> / / applied to values . <nl> - IndexBlockIter ( const Comparator * comparator , <nl> - const Comparator * user_comparator , const char * data , <nl> - uint32_t restarts , uint32_t num_restarts , <nl> - BlockPrefixIndex * prefix_index , bool key_includes_seq , <nl> - bool value_is_full , bool block_contents_pinned ) <nl> - : IndexBlockIter ( ) { <nl> - Initialize ( comparator , user_comparator , data , restarts , num_restarts , <nl> - prefix_index , key_includes_seq , block_contents_pinned , <nl> - value_is_full , nullptr / * data_block_hash_index * / ) ; <nl> - } <nl> - <nl> void Initialize ( const Comparator * comparator , <nl> const Comparator * user_comparator , const char * data , <nl> uint32_t restarts , uint32_t num_restarts , <nl> - BlockPrefixIndex * prefix_index , bool key_includes_seq , <nl> - bool value_is_full , bool block_contents_pinned , <nl> - DataBlockHashIndex * / * data_block_hash_index * / ) { <nl> + SequenceNumber global_seqno , BlockPrefixIndex * prefix_index , <nl> + bool have_first_key , bool key_includes_seq , <nl> + bool value_is_full , bool block_contents_pinned ) { <nl> InitializeBase ( key_includes_seq ? comparator : user_comparator , data , <nl> restarts , num_restarts , kDisableGlobalSequenceNumber , <nl> block_contents_pinned ) ; <nl> class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> key_ . SetIsUserKey ( ! key_includes_seq_ ) ; <nl> prefix_index_ = prefix_index ; <nl> value_delta_encoded_ = ! value_is_full ; <nl> + have_first_key_ = have_first_key ; <nl> + if ( have_first_key_ & & global_seqno ! = kDisableGlobalSequenceNumber ) { <nl> + global_seqno_state_ . reset ( new GlobalSeqnoState ( global_seqno ) ) ; <nl> + } else { <nl> + global_seqno_state_ . reset ( ) ; <nl> + } <nl> } <nl> <nl> Slice user_key ( ) const override { <nl> class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> return key ( ) ; <nl> } <nl> <nl> - virtual BlockHandle value ( ) const override { <nl> + virtual IndexValue value ( ) const override { <nl> assert ( Valid ( ) ) ; <nl> - if ( value_delta_encoded_ ) { <nl> + if ( value_delta_encoded_ | | global_seqno_state_ ! = nullptr ) { <nl> return decoded_value_ ; <nl> } else { <nl> - BlockHandle handle ; <nl> + IndexValue entry ; <nl> Slice v = value_ ; <nl> - Status decode_s __attribute__ ( ( __unused__ ) ) = handle . DecodeFrom ( & v ) ; <nl> + Status decode_s __attribute__ ( ( __unused__ ) ) = <nl> + entry . DecodeFrom ( & v , have_first_key_ , nullptr ) ; <nl> assert ( decode_s . ok ( ) ) ; <nl> - return handle ; <nl> + return entry ; <nl> } <nl> } <nl> <nl> class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> <nl> void Invalidate ( Status s ) { InvalidateBase ( s ) ; } <nl> <nl> + bool IsValuePinned ( ) const override { <nl> + return global_seqno_state_ ! = nullptr ? false : BlockIter : : IsValuePinned ( ) ; <nl> + } <nl> + <nl> private : <nl> / / Key is in InternalKey format <nl> bool key_includes_seq_ ; <nl> bool value_delta_encoded_ ; <nl> + bool have_first_key_ ; / / value includes first_internal_key <nl> BlockPrefixIndex * prefix_index_ ; <nl> / / Whether the value is delta encoded . In that case the value is assumed to be <nl> / / BlockHandle . The first value in each restart interval is the full encoded <nl> class IndexBlockIter final : public BlockIter < BlockHandle > { <nl> / / offset of delta encoded BlockHandles is computed by adding the size of <nl> / / previous delta encoded values in the same restart interval to the offset of <nl> / / the first value in that restart interval . <nl> - BlockHandle decoded_value_ ; <nl> + IndexValue decoded_value_ ; <nl> + <nl> + / / When sequence number overwriting is enabled , this struct contains the seqno <nl> + / / to overwrite with , and current first_internal_key with overwritten seqno . <nl> + / / This is rarely used , so we put it behind a pointer and only allocate when <nl> + / / needed . <nl> + struct GlobalSeqnoState { <nl> + / / First internal key according to current index entry , but with sequence <nl> + / / number overwritten to global_seqno . <nl> + IterKey first_internal_key ; <nl> + SequenceNumber global_seqno ; <nl> + <nl> + explicit GlobalSeqnoState ( SequenceNumber seqno ) : global_seqno ( seqno ) { } <nl> + } ; <nl> + <nl> + std : : unique_ptr < GlobalSeqnoState > global_seqno_state_ ; <nl> <nl> bool PrefixSeek ( const Slice & target , uint32_t * index ) ; <nl> bool BinaryBlockIndexSeek ( const Slice & target , uint32_t * block_ids , <nl> mmm a / table / block_based / block_based_table_reader . cc <nl> ppp b / table / block_based / block_based_table_reader . cc <nl> class BlockBasedTable : : IndexReaderCommon : public BlockBasedTable : : IndexReader { <nl> return & table_ - > get_rep ( ) - > internal_comparator ; <nl> } <nl> <nl> - bool index_key_includes_seq ( ) const { <nl> + bool index_has_first_key ( ) const { <nl> assert ( table_ ! = nullptr ) ; <nl> assert ( table_ - > get_rep ( ) ! = nullptr ) ; <nl> + return table_ - > get_rep ( ) - > index_has_first_key ; <nl> + } <nl> <nl> - const TableProperties * const properties = <nl> - table_ - > get_rep ( ) - > table_properties . get ( ) ; <nl> - <nl> - return properties = = nullptr | | ! properties - > index_key_is_user_key ; <nl> + bool index_key_includes_seq ( ) const { <nl> + assert ( table_ ! = nullptr ) ; <nl> + assert ( table_ - > get_rep ( ) ! = nullptr ) ; <nl> + return table_ - > get_rep ( ) - > index_key_includes_seq ; <nl> } <nl> <nl> bool index_value_is_full ( ) const { <nl> assert ( table_ ! = nullptr ) ; <nl> assert ( table_ - > get_rep ( ) ! = nullptr ) ; <nl> - <nl> - const TableProperties * const properties = <nl> - table_ - > get_rep ( ) - > table_properties . get ( ) ; <nl> - <nl> - return properties = = nullptr | | ! properties - > index_value_is_delta_encoded ; <nl> + return table_ - > get_rep ( ) - > index_value_is_full ; <nl> } <nl> <nl> Status GetOrReadIndexBlock ( bool no_io , GetContext * get_context , <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> } <nl> <nl> / / return a two - level iterator : first level is on the partition index <nl> - InternalIteratorBase < BlockHandle > * NewIterator ( <nl> + InternalIteratorBase < IndexValue > * NewIterator ( <nl> const ReadOptions & read_options , bool / * disable_prefix_seek * / , <nl> IndexBlockIter * iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) override { <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> return iter ; <nl> } <nl> <nl> - return NewErrorInternalIterator < BlockHandle > ( s ) ; <nl> + return NewErrorInternalIterator < IndexValue > ( s ) ; <nl> } <nl> <nl> - InternalIteratorBase < BlockHandle > * it = nullptr ; <nl> + InternalIteratorBase < IndexValue > * it = nullptr ; <nl> <nl> Statistics * kNullStats = nullptr ; <nl> / / Filters are already checked before seeking the index <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> it = NewTwoLevelIterator ( <nl> - new BlockBasedTable : : PartitionedIndexIteratorState ( <nl> - table ( ) , & partition_map_ , index_key_includes_seq ( ) , <nl> - index_value_is_full ( ) ) , <nl> - index_block . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + new BlockBasedTable : : PartitionedIndexIteratorState ( table ( ) , <nl> + & partition_map_ ) , <nl> + index_block . GetValue ( ) - > NewIndexIterator ( <nl> internal_comparator ( ) , internal_comparator ( ) - > user_comparator ( ) , <nl> - nullptr , kNullStats , true , index_key_includes_seq ( ) , <nl> - index_value_is_full ( ) ) ) ; <nl> + nullptr , kNullStats , true , index_has_first_key ( ) , <nl> + index_key_includes_seq ( ) , index_value_is_full ( ) ) ) ; <nl> } else { <nl> ReadOptions ro ; <nl> ro . fill_cache = read_options . fill_cache ; <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> - it = new BlockBasedTableIterator < IndexBlockIter , BlockHandle > ( <nl> + it = new BlockBasedTableIterator < IndexBlockIter , IndexValue > ( <nl> table ( ) , ro , * internal_comparator ( ) , <nl> - index_block . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + index_block . GetValue ( ) - > NewIndexIterator ( <nl> internal_comparator ( ) , internal_comparator ( ) - > user_comparator ( ) , <nl> - nullptr , kNullStats , true , index_key_includes_seq ( ) , <nl> - index_value_is_full ( ) ) , <nl> + nullptr , kNullStats , true , index_has_first_key ( ) , <nl> + index_key_includes_seq ( ) , index_value_is_full ( ) ) , <nl> false , true , / * prefix_extractor * / nullptr , BlockType : : kIndex , <nl> - index_key_includes_seq ( ) , index_value_is_full ( ) , <nl> lookup_context ? lookup_context - > caller <nl> : TableReaderCaller : : kUncategorized ) ; <nl> } <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> void CacheDependencies ( bool pin ) override { <nl> / / Before read partitions , prefetch them to avoid lots of IOs <nl> BlockCacheLookupContext lookup_context { TableReaderCaller : : kPrefetch } ; <nl> - auto rep = table ( ) - > rep_ ; <nl> + const BlockBasedTable : : Rep * rep = table ( ) - > rep_ ; <nl> IndexBlockIter biter ; <nl> BlockHandle handle ; <nl> Statistics * kNullStats = nullptr ; <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> - index_block . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + index_block . GetValue ( ) - > NewIndexIterator ( <nl> internal_comparator ( ) , internal_comparator ( ) - > user_comparator ( ) , & biter , <nl> - kNullStats , true , index_key_includes_seq ( ) , index_value_is_full ( ) ) ; <nl> + kNullStats , true , index_has_first_key ( ) , index_key_includes_seq ( ) , <nl> + index_value_is_full ( ) ) ; <nl> / / Index partitions are assumed to be consecuitive . Prefetch them all . <nl> / / Read the first block offset <nl> biter . SeekToFirst ( ) ; <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> / / Empty index . <nl> return ; <nl> } <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> uint64_t prefetch_off = handle . offset ( ) ; <nl> <nl> / / Read the last block ' s offset <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> / / Empty index . <nl> return ; <nl> } <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> uint64_t last_off = handle . offset ( ) + handle . size ( ) + kBlockTrailerSize ; <nl> uint64_t prefetch_len = last_off - prefetch_off ; <nl> std : : unique_ptr < FilePrefetchBuffer > prefetch_buffer ; <nl> class PartitionIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> biter . SeekToFirst ( ) ; <nl> auto ro = ReadOptions ( ) ; <nl> for ( ; biter . Valid ( ) ; biter . Next ( ) ) { <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> CachableEntry < Block > block ; <nl> / / TODO : Support counter batch update for partitioned index and <nl> / / filter blocks <nl> class BinarySearchIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> - InternalIteratorBase < BlockHandle > * NewIterator ( <nl> + InternalIteratorBase < IndexValue > * NewIterator ( <nl> const ReadOptions & read_options , bool / * disable_prefix_seek * / , <nl> IndexBlockIter * iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) override { <nl> class BinarySearchIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> return iter ; <nl> } <nl> <nl> - return NewErrorInternalIterator < BlockHandle > ( s ) ; <nl> + return NewErrorInternalIterator < IndexValue > ( s ) ; <nl> } <nl> <nl> Statistics * kNullStats = nullptr ; <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> - auto it = index_block . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + auto it = index_block . GetValue ( ) - > NewIndexIterator ( <nl> internal_comparator ( ) , internal_comparator ( ) - > user_comparator ( ) , iter , <nl> - kNullStats , true , index_key_includes_seq ( ) , index_value_is_full ( ) ) ; <nl> + kNullStats , true , index_has_first_key ( ) , index_key_includes_seq ( ) , <nl> + index_value_is_full ( ) ) ; <nl> <nl> assert ( it ! = nullptr ) ; <nl> index_block . TransferTo ( it ) ; <nl> class HashIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> assert ( index_reader ! = nullptr ) ; <nl> assert ( ! pin | | prefetch ) ; <nl> <nl> - auto rep = table - > get_rep ( ) ; <nl> + const BlockBasedTable : : Rep * rep = table - > get_rep ( ) ; <nl> assert ( rep ! = nullptr ) ; <nl> <nl> CachableEntry < Block > index_block ; <nl> class HashIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> - InternalIteratorBase < BlockHandle > * NewIterator ( <nl> + InternalIteratorBase < IndexValue > * NewIterator ( <nl> const ReadOptions & read_options , bool disable_prefix_seek , <nl> IndexBlockIter * iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) override { <nl> class HashIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> return iter ; <nl> } <nl> <nl> - return NewErrorInternalIterator < BlockHandle > ( s ) ; <nl> + return NewErrorInternalIterator < IndexValue > ( s ) ; <nl> } <nl> <nl> Statistics * kNullStats = nullptr ; <nl> class HashIndexReader : public BlockBasedTable : : IndexReaderCommon { <nl> read_options . total_order_seek | | disable_prefix_seek ; <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> - auto it = index_block . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + auto it = index_block . GetValue ( ) - > NewIndexIterator ( <nl> internal_comparator ( ) , internal_comparator ( ) - > user_comparator ( ) , iter , <nl> - kNullStats , total_order_seek , index_key_includes_seq ( ) , <nl> - index_value_is_full ( ) , false / * block_contents_pinned * / , <nl> - prefix_index_ . get ( ) ) ; <nl> + kNullStats , total_order_seek , index_has_first_key ( ) , <nl> + index_key_includes_seq ( ) , index_value_is_full ( ) , <nl> + false / * block_contents_pinned * / , prefix_index_ . get ( ) ) ; <nl> <nl> assert ( it ! = nullptr ) ; <nl> index_block . TransferTo ( it ) ; <nl> Status BlockBasedTable : : Open ( <nl> immortal_table ) ; <nl> rep - > file = std : : move ( file ) ; <nl> rep - > footer = footer ; <nl> - rep - > index_type = table_options . index_type ; <nl> rep - > hash_index_allow_collision = table_options . hash_index_allow_collision ; <nl> / / We need to wrap data with internal_prefix_transform to make sure it can <nl> / / handle prefix correctly . <nl> Status BlockBasedTable : : Open ( <nl> return s ; <nl> } <nl> <nl> + / / Populates table_properties and some fields that depend on it , <nl> + / / such as index_type . <nl> s = new_table - > ReadPropertiesBlock ( prefetch_buffer . get ( ) , meta_iter . get ( ) , <nl> largest_seqno ) ; <nl> if ( ! s . ok ( ) ) { <nl> Status BlockBasedTable : : ReadPropertiesBlock ( <nl> BlockBasedTablePropertyNames : : kPrefixFiltering , <nl> rep_ - > ioptions . info_log ) ; <nl> <nl> + rep_ - > index_key_includes_seq = <nl> + rep_ - > table_properties - > index_key_is_user_key = = 0 ; <nl> + rep_ - > index_value_is_full = <nl> + rep_ - > table_properties - > index_value_is_delta_encoded = = 0 ; <nl> + <nl> + / / Update index_type with the true type . <nl> + / / If table properties don ' t contain index type , we assume that the table <nl> + / / is in very old format and has kBinarySearch index type . <nl> + auto & props = rep_ - > table_properties - > user_collected_properties ; <nl> + auto pos = props . find ( BlockBasedTablePropertyNames : : kIndexType ) ; <nl> + if ( pos ! = props . end ( ) ) { <nl> + rep_ - > index_type = static_cast < BlockBasedTableOptions : : IndexType > ( <nl> + DecodeFixed32 ( pos - > second . c_str ( ) ) ) ; <nl> + } <nl> + <nl> + rep_ - > index_has_first_key = <nl> + rep_ - > index_type = = BlockBasedTableOptions : : kBinarySearchWithFirstKey ; <nl> + <nl> s = GetGlobalSequenceNumber ( * ( rep_ - > table_properties ) , largest_seqno , <nl> & ( rep_ - > global_seqno ) ) ; <nl> if ( ! s . ok ( ) ) { <nl> Status BlockBasedTable : : ReadRangeDelBlock ( <nl> std : : unique_ptr < InternalIterator > iter ( NewDataBlockIterator < DataBlockIter > ( <nl> read_options , range_del_handle , <nl> / * input_iter = * / nullptr , BlockType : : kRangeDeletion , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , <nl> / * get_context = * / nullptr , lookup_context , Status ( ) , prefetch_buffer ) ) ; <nl> assert ( iter ! = nullptr ) ; <nl> s = iter - > status ( ) ; <nl> Status BlockBasedTable : : PrefetchIndexAndFilterBlocks ( <nl> & rep_ - > compression_dict_handle ) ; <nl> } <nl> <nl> - BlockBasedTableOptions : : IndexType index_type = new_table - > UpdateIndexType ( ) ; <nl> + BlockBasedTableOptions : : IndexType index_type = rep_ - > index_type ; <nl> <nl> const bool use_cache = table_options . cache_index_and_filter_blocks ; <nl> <nl> Status BlockBasedTable : : ReadMetaBlock ( FilePrefetchBuffer * prefetch_buffer , <nl> <nl> * meta_block = std : : move ( meta ) ; <nl> / / meta block uses bytewise comparator . <nl> - iter - > reset ( meta_block - > get ( ) - > NewIterator < DataBlockIter > ( <nl> - BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> + iter - > reset ( meta_block - > get ( ) - > NewDataIterator ( BytewiseComparator ( ) , <nl> + BytewiseComparator ( ) ) ) ; <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> FilterBlockReader * BlockBasedTable : : ReadFilter ( <nl> rep - > prefix_filtering ? prefix_extractor : nullptr , <nl> rep - > whole_key_filtering , std : : move ( block ) , nullptr , <nl> rep - > ioptions . statistics , rep - > internal_comparator , this , <nl> - rep_ - > table_properties = = nullptr | | <nl> - rep_ - > table_properties - > index_key_is_user_key = = 0 , <nl> - rep_ - > table_properties = = nullptr | | <nl> - rep_ - > table_properties - > index_value_is_delta_encoded = = 0 ) ; <nl> + rep_ - > index_key_includes_seq , rep_ - > index_value_is_full ) ; <nl> } <nl> <nl> case Rep : : FilterType : : kBlockFilter : <nl> CachableEntry < UncompressionDict > BlockBasedTable : : GetUncompressionDict ( <nl> <nl> / / disable_prefix_seek should be set to true when prefix_extractor found in SST <nl> / / differs from the one in mutable_cf_options and index type is HashBasedIndex <nl> - InternalIteratorBase < BlockHandle > * BlockBasedTable : : NewIndexIterator ( <nl> + InternalIteratorBase < IndexValue > * BlockBasedTable : : NewIndexIterator ( <nl> const ReadOptions & read_options , bool disable_prefix_seek , <nl> IndexBlockIter * input_iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) const { <nl> InternalIteratorBase < BlockHandle > * BlockBasedTable : : NewIndexIterator ( <nl> template < typename TBlockIter > <nl> TBlockIter * BlockBasedTable : : NewDataBlockIterator ( <nl> const ReadOptions & ro , const BlockHandle & handle , TBlockIter * input_iter , <nl> - BlockType block_type , bool key_includes_seq , bool index_key_is_full , <nl> - GetContext * get_context , BlockCacheLookupContext * lookup_context , Status s , <nl> + BlockType block_type , GetContext * get_context , <nl> + BlockCacheLookupContext * lookup_context , Status s , <nl> FilePrefetchBuffer * prefetch_buffer , bool for_compaction ) const { <nl> PERF_TIMER_GUARD ( new_table_block_iter_nanos ) ; <nl> <nl> TBlockIter * BlockBasedTable : : NewDataBlockIterator ( <nl> } <nl> <nl> assert ( block . GetValue ( ) ! = nullptr ) ; <nl> - constexpr bool kTotalOrderSeek = true ; <nl> + <nl> / / Block contents are pinned and it is still pinned after the iterator <nl> / / is destroyed as long as cleanup functions are moved to another object , <nl> / / when : <nl> TBlockIter * BlockBasedTable : : NewDataBlockIterator ( <nl> const bool block_contents_pinned = <nl> block . IsCached ( ) | | <nl> ( ! block . GetValue ( ) - > own_bytes ( ) & & rep_ - > immortal_table ) ; <nl> - iter = block . GetValue ( ) - > NewIterator < TBlockIter > ( <nl> - & rep_ - > internal_comparator , rep_ - > internal_comparator . user_comparator ( ) , <nl> - iter , rep_ - > ioptions . statistics , kTotalOrderSeek , key_includes_seq , <nl> - index_key_is_full , block_contents_pinned ) ; <nl> + iter = InitBlockIterator < TBlockIter > ( rep_ , block . GetValue ( ) , iter , <nl> + block_contents_pinned ) ; <nl> <nl> if ( ! block . IsCached ( ) ) { <nl> if ( ! ro . fill_cache & & rep_ - > cache_key_prefix_size ! = 0 ) { <nl> TBlockIter * BlockBasedTable : : NewDataBlockIterator ( <nl> return iter ; <nl> } <nl> <nl> + template < > <nl> + DataBlockIter * BlockBasedTable : : InitBlockIterator < DataBlockIter > ( <nl> + const Rep * rep , Block * block , DataBlockIter * input_iter , <nl> + bool block_contents_pinned ) { <nl> + return block - > NewDataIterator ( <nl> + & rep - > internal_comparator , rep - > internal_comparator . user_comparator ( ) , <nl> + input_iter , rep - > ioptions . statistics , block_contents_pinned ) ; <nl> + } <nl> + <nl> + template < > <nl> + IndexBlockIter * BlockBasedTable : : InitBlockIterator < IndexBlockIter > ( <nl> + const Rep * rep , Block * block , IndexBlockIter * input_iter , <nl> + bool block_contents_pinned ) { <nl> + return block - > NewIndexIterator ( <nl> + & rep - > internal_comparator , rep - > internal_comparator . user_comparator ( ) , <nl> + input_iter , rep - > ioptions . statistics , / * total_order_seek * / true , <nl> + rep - > index_has_first_key , rep - > index_key_includes_seq , <nl> + rep - > index_value_is_full , block_contents_pinned ) ; <nl> + } <nl> + <nl> Status BlockBasedTable : : MaybeReadBlockAndLoadToCache ( <nl> FilePrefetchBuffer * prefetch_buffer , const ReadOptions & ro , <nl> const BlockHandle & handle , const UncompressionDict & uncompression_dict , <nl> Status BlockBasedTable : : RetrieveBlock ( <nl> <nl> BlockBasedTable : : PartitionedIndexIteratorState : : PartitionedIndexIteratorState ( <nl> const BlockBasedTable * table , <nl> - std : : unordered_map < uint64_t , CachableEntry < Block > > * block_map , <nl> - bool index_key_includes_seq , bool index_key_is_full ) <nl> - : table_ ( table ) , <nl> - block_map_ ( block_map ) , <nl> - index_key_includes_seq_ ( index_key_includes_seq ) , <nl> - index_key_is_full_ ( index_key_is_full ) { } <nl> - <nl> - InternalIteratorBase < BlockHandle > * <nl> + std : : unordered_map < uint64_t , CachableEntry < Block > > * block_map ) <nl> + : table_ ( table ) , block_map_ ( block_map ) { } <nl> + <nl> + InternalIteratorBase < IndexValue > * <nl> BlockBasedTable : : PartitionedIndexIteratorState : : NewSecondaryIterator ( <nl> const BlockHandle & handle ) { <nl> / / Return a block iterator on the index partition <nl> BlockBasedTable : : PartitionedIndexIteratorState : : NewSecondaryIterator ( <nl> / / This is a possible scenario since block cache might not have had space <nl> / / for the partition <nl> if ( block ! = block_map_ - > end ( ) ) { <nl> - auto rep = table_ - > get_rep ( ) ; <nl> + const Rep * rep = table_ - > get_rep ( ) ; <nl> assert ( rep ) ; <nl> <nl> Statistics * kNullStats = nullptr ; <nl> / / We don ' t return pinned data from index blocks , so no need <nl> / / to set ` block_contents_pinned ` . <nl> - return block - > second . GetValue ( ) - > NewIterator < IndexBlockIter > ( <nl> + return block - > second . GetValue ( ) - > NewIndexIterator ( <nl> & rep - > internal_comparator , rep - > internal_comparator . user_comparator ( ) , <nl> - nullptr , kNullStats , true , index_key_includes_seq_ , index_key_is_full_ ) ; <nl> + nullptr , kNullStats , true , rep - > index_has_first_key , <nl> + rep - > index_key_includes_seq , rep - > index_value_is_full ) ; <nl> } <nl> / / Create an empty iterator <nl> return new IndexBlockIter ( ) ; <nl> bool BlockBasedTable : : PrefixMayMatch ( <nl> / / Then , try find it within each block <nl> / / we already know prefix_extractor and prefix_extractor_name must match <nl> / / because ` CheckPrefixMayMatch ` first checks ` check_filter_ = = true ` <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter ( NewIndexIterator ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter ( NewIndexIterator ( <nl> no_io_read_options , <nl> / * need_upper_bound_check = * / false , / * input_iter = * / nullptr , <nl> - / * need_upper_bound_check = * / nullptr , lookup_context ) ) ; <nl> + / * get_context = * / nullptr , lookup_context ) ) ; <nl> iiter - > Seek ( internal_prefix ) ; <nl> <nl> if ( ! iiter - > Valid ( ) ) { <nl> bool BlockBasedTable : : PrefixMayMatch ( <nl> / / and we ' re not really sure that we ' re past the end <nl> / / of the file <nl> may_match = iiter - > status ( ) . IsIncomplete ( ) ; <nl> - } else if ( ( rep_ - > table_properties & & <nl> - rep_ - > table_properties - > index_key_is_user_key <nl> - ? iiter - > key ( ) <nl> - : ExtractUserKey ( iiter - > key ( ) ) ) <nl> + } else if ( ( rep_ - > index_key_includes_seq ? ExtractUserKey ( iiter - > key ( ) ) <nl> + : iiter - > key ( ) ) <nl> . starts_with ( ExtractUserKey ( internal_prefix ) ) ) { <nl> / / we need to check for this subtle case because our only <nl> / / guarantee is that " the key is a string > = last key in that data <nl> bool BlockBasedTable : : PrefixMayMatch ( <nl> / / after the data block corresponding to iiter - > key ( ) cannot <nl> / / possibly contain the key . Thus , the corresponding data block <nl> / / is the only on could potentially contain the prefix . <nl> - BlockHandle handle = iiter - > value ( ) ; <nl> + BlockHandle handle = iiter - > value ( ) . handle ; <nl> may_match = filter - > PrefixMayMatch ( <nl> prefix , prefix_extractor , handle . offset ( ) , / * no_io = * / false , <nl> / * const_key_ptr = * / nullptr , lookup_context ) ; <nl> bool BlockBasedTable : : PrefixMayMatch ( <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : Seek ( const Slice & target ) { <nl> + SeekImpl ( & target ) ; <nl> + } <nl> + <nl> + template < class TBlockIter , typename TValue > <nl> + void BlockBasedTableIterator < TBlockIter , TValue > : : SeekToFirst ( ) { <nl> + SeekImpl ( nullptr ) ; <nl> + } <nl> + <nl> + template < class TBlockIter , typename TValue > <nl> + void BlockBasedTableIterator < TBlockIter , TValue > : : SeekImpl ( <nl> + const Slice * target ) { <nl> is_out_of_bound_ = false ; <nl> - if ( ! CheckPrefixMayMatch ( target ) ) { <nl> + is_at_first_key_from_index_ = false ; <nl> + if ( target & & ! CheckPrefixMayMatch ( * target ) ) { <nl> ResetDataIter ( ) ; <nl> return ; <nl> } <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : Seek ( const Slice & target ) { <nl> bool need_seek_index = true ; <nl> if ( block_iter_points_to_real_block_ & & block_iter_ . Valid ( ) ) { <nl> / / Reseek . <nl> - prev_index_value_ = index_iter_ - > value ( ) ; <nl> - / / We can avoid an index seek if : <nl> - / / 1 . The new seek key is larger than the current key <nl> - / / 2 . The new seek key is within the upper bound of the block <nl> - / / Since we don ' t necessarily know the internal key for either <nl> - / / the current key or the upper bound , we check user keys and <nl> - / / exclude the equality case . Considering internal keys can <nl> - / / improve for the boundary cases , but it would complicate the <nl> - / / code . <nl> - if ( user_comparator_ . Compare ( ExtractUserKey ( target ) , <nl> - block_iter_ . user_key ( ) ) > 0 & & <nl> - user_comparator_ . Compare ( ExtractUserKey ( target ) , <nl> - index_iter_ - > user_key ( ) ) < 0 ) { <nl> - need_seek_index = false ; <nl> + prev_block_offset_ = index_iter_ - > value ( ) . handle . offset ( ) ; <nl> + <nl> + if ( target ) { <nl> + / / We can avoid an index seek if : <nl> + / / 1 . The new seek key is larger than the current key <nl> + / / 2 . The new seek key is within the upper bound of the block <nl> + / / Since we don ' t necessarily know the internal key for either <nl> + / / the current key or the upper bound , we check user keys and <nl> + / / exclude the equality case . Considering internal keys can <nl> + / / improve for the boundary cases , but it would complicate the <nl> + / / code . <nl> + if ( user_comparator_ . Compare ( ExtractUserKey ( * target ) , <nl> + block_iter_ . user_key ( ) ) > 0 & & <nl> + user_comparator_ . Compare ( ExtractUserKey ( * target ) , <nl> + index_iter_ - > user_key ( ) ) < 0 ) { <nl> + need_seek_index = false ; <nl> + } <nl> } <nl> } <nl> <nl> if ( need_seek_index ) { <nl> - index_iter_ - > Seek ( target ) ; <nl> + if ( target ) { <nl> + index_iter_ - > Seek ( * target ) ; <nl> + } else { <nl> + index_iter_ - > SeekToFirst ( ) ; <nl> + } <nl> + <nl> if ( ! index_iter_ - > Valid ( ) ) { <nl> ResetDataIter ( ) ; <nl> return ; <nl> } <nl> - InitDataBlock ( ) ; <nl> } <nl> <nl> - block_iter_ . Seek ( target ) ; <nl> + IndexValue v = index_iter_ - > value ( ) ; <nl> + const bool same_block = block_iter_points_to_real_block_ & & <nl> + v . handle . offset ( ) = = prev_block_offset_ ; <nl> + <nl> + / / TODO ( kolmike ) : Remove the ! = kBlockCacheTier condition . <nl> + if ( ! v . first_internal_key . empty ( ) & & ! same_block & & <nl> + ( ! target | | icomp_ . Compare ( * target , v . first_internal_key ) < = 0 ) & & <nl> + read_options_ . read_tier ! = kBlockCacheTier ) { <nl> + / / Index contains the first key of the block , and it ' s > = target . <nl> + / / We can defer reading the block . <nl> + is_at_first_key_from_index_ = true ; <nl> + ResetDataIter ( ) ; <nl> + } else { <nl> + / / Need to use the data block . <nl> + if ( ! same_block ) { <nl> + InitDataBlock ( ) ; <nl> + } <nl> + <nl> + if ( target ) { <nl> + block_iter_ . Seek ( * target ) ; <nl> + } else { <nl> + block_iter_ . SeekToFirst ( ) ; <nl> + } <nl> + FindKeyForward ( ) ; <nl> + } <nl> <nl> - FindKeyForward ( ) ; <nl> CheckOutOfBound ( ) ; <nl> - assert ( <nl> - ! block_iter_ . Valid ( ) | | <nl> - ( key_includes_seq_ & & icomp_ . Compare ( target , block_iter_ . key ( ) ) < = 0 ) | | <nl> - ( ! key_includes_seq_ & & user_comparator_ . Compare ( ExtractUserKey ( target ) , <nl> - block_iter_ . key ( ) ) < = 0 ) ) ; <nl> + <nl> + if ( target ) { <nl> + assert ( <nl> + ! Valid ( ) | | <nl> + ( ( block_type_ = = BlockType : : kIndex & & <nl> + ! table_ - > get_rep ( ) - > index_key_includes_seq ) <nl> + ? ( user_comparator_ . Compare ( ExtractUserKey ( * target ) , key ( ) ) < = 0 ) <nl> + : ( icomp_ . Compare ( * target , key ( ) ) < = 0 ) ) ) ; <nl> + } <nl> } <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : SeekForPrev ( <nl> const Slice & target ) { <nl> is_out_of_bound_ = false ; <nl> + is_at_first_key_from_index_ = false ; <nl> if ( ! CheckPrefixMayMatch ( target ) ) { <nl> ResetDataIter ( ) ; <nl> return ; <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : SeekForPrev ( <nl> index_iter_ - > Seek ( target ) ; <nl> <nl> if ( ! index_iter_ - > Valid ( ) ) { <nl> + if ( ! index_iter_ - > status ( ) . ok ( ) ) { <nl> + ResetDataIter ( ) ; <nl> + return ; <nl> + } <nl> + <nl> index_iter_ - > SeekToLast ( ) ; <nl> if ( ! index_iter_ - > Valid ( ) ) { <nl> ResetDataIter ( ) ; <nl> - block_iter_points_to_real_block_ = false ; <nl> return ; <nl> } <nl> } <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : SeekForPrev ( <nl> icomp_ . Compare ( target , block_iter_ . key ( ) ) > = 0 ) ; <nl> } <nl> <nl> - template < class TBlockIter , typename TValue > <nl> - void BlockBasedTableIterator < TBlockIter , TValue > : : SeekToFirst ( ) { <nl> - is_out_of_bound_ = false ; <nl> - SavePrevIndexValue ( ) ; <nl> - index_iter_ - > SeekToFirst ( ) ; <nl> - if ( ! index_iter_ - > Valid ( ) ) { <nl> - ResetDataIter ( ) ; <nl> - return ; <nl> - } <nl> - InitDataBlock ( ) ; <nl> - block_iter_ . SeekToFirst ( ) ; <nl> - FindKeyForward ( ) ; <nl> - CheckOutOfBound ( ) ; <nl> - } <nl> - <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : SeekToLast ( ) { <nl> is_out_of_bound_ = false ; <nl> + is_at_first_key_from_index_ = false ; <nl> SavePrevIndexValue ( ) ; <nl> index_iter_ - > SeekToLast ( ) ; <nl> if ( ! index_iter_ - > Valid ( ) ) { <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : SeekToLast ( ) { <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : Next ( ) { <nl> + if ( is_at_first_key_from_index_ & & ! MaterializeCurrentBlock ( ) ) { <nl> + return ; <nl> + } <nl> assert ( block_iter_points_to_real_block_ ) ; <nl> block_iter_ . Next ( ) ; <nl> FindKeyForward ( ) ; <nl> + CheckOutOfBound ( ) ; <nl> } <nl> <nl> template < class TBlockIter , typename TValue > <nl> bool BlockBasedTableIterator < TBlockIter , TValue > : : NextAndGetResult ( <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : Prev ( ) { <nl> - assert ( block_iter_points_to_real_block_ ) ; <nl> - block_iter_ . Prev ( ) ; <nl> + if ( is_at_first_key_from_index_ ) { <nl> + is_at_first_key_from_index_ = false ; <nl> + <nl> + index_iter_ - > Prev ( ) ; <nl> + if ( ! index_iter_ - > Valid ( ) ) { <nl> + return ; <nl> + } <nl> + <nl> + InitDataBlock ( ) ; <nl> + block_iter_ . SeekToLast ( ) ; <nl> + } else { <nl> + assert ( block_iter_points_to_real_block_ ) ; <nl> + block_iter_ . Prev ( ) ; <nl> + } <nl> + <nl> FindKeyBackward ( ) ; <nl> } <nl> <nl> const size_t <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : InitDataBlock ( ) { <nl> - BlockHandle data_block_handle = index_iter_ - > value ( ) ; <nl> + BlockHandle data_block_handle = index_iter_ - > value ( ) . handle ; <nl> if ( ! block_iter_points_to_real_block_ | | <nl> - data_block_handle . offset ( ) ! = prev_index_value_ . offset ( ) | | <nl> + data_block_handle . offset ( ) ! = prev_block_offset_ | | <nl> / / if previous attempt of reading the block missed cache , try again <nl> block_iter_ . status ( ) . IsIncomplete ( ) ) { <nl> if ( block_iter_points_to_real_block_ ) { <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : InitDataBlock ( ) { <nl> Status s ; <nl> table_ - > NewDataBlockIterator < TBlockIter > ( <nl> read_options_ , data_block_handle , & block_iter_ , block_type_ , <nl> - key_includes_seq_ , index_key_is_full_ , <nl> / * get_context = * / nullptr , & lookup_context_ , s , prefetch_buffer_ . get ( ) , <nl> / * for_compaction = * / lookup_context_ . caller = = <nl> TableReaderCaller : : kCompaction ) ; <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : InitDataBlock ( ) { <nl> } <nl> } <nl> <nl> + template < class TBlockIter , typename TValue > <nl> + bool BlockBasedTableIterator < TBlockIter , TValue > : : MaterializeCurrentBlock ( ) { <nl> + assert ( is_at_first_key_from_index_ ) ; <nl> + assert ( ! block_iter_points_to_real_block_ ) ; <nl> + assert ( index_iter_ - > Valid ( ) ) ; <nl> + <nl> + is_at_first_key_from_index_ = false ; <nl> + InitDataBlock ( ) ; <nl> + assert ( block_iter_points_to_real_block_ ) ; <nl> + block_iter_ . SeekToFirst ( ) ; <nl> + <nl> + if ( ! block_iter_ . Valid ( ) | | <nl> + icomp_ . Compare ( block_iter_ . key ( ) , <nl> + index_iter_ - > value ( ) . first_internal_key ) ! = 0 ) { <nl> + / / Uh oh . <nl> + block_iter_ . Invalidate ( Status : : Corruption ( <nl> + " first key in index doesn ' t match first key in block " ) ) ; <nl> + return false ; <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + template < class TBlockIter , typename TValue > <nl> + void BlockBasedTableIterator < TBlockIter , TValue > : : FindKeyForward ( ) { <nl> + / / This method ' s code is kept short to make it likely to be inlined . <nl> + <nl> + assert ( ! is_out_of_bound_ ) ; <nl> + assert ( block_iter_points_to_real_block_ ) ; <nl> + <nl> + if ( ! block_iter_ . Valid ( ) ) { <nl> + / / This is the only call site of FindBlockForward ( ) , but it ' s extracted into <nl> + / / a separate method to keep FindKeyForward ( ) short and likely to be <nl> + / / inlined . When transitioning to a different block , we call <nl> + / / FindBlockForward ( ) , which is much longer and is probably not inlined . <nl> + FindBlockForward ( ) ; <nl> + } else { <nl> + / / This is the fast path that avoids a function call . <nl> + } <nl> + } <nl> + <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : FindBlockForward ( ) { <nl> / / TODO the while loop inherits from two - level - iterator . We don ' t know <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : FindBlockForward ( ) { <nl> return ; <nl> } <nl> <nl> - if ( index_iter_ - > Valid ( ) ) { <nl> - InitDataBlock ( ) ; <nl> - block_iter_ . SeekToFirst ( ) ; <nl> - } else { <nl> + if ( ! index_iter_ - > Valid ( ) ) { <nl> return ; <nl> } <nl> - } while ( ! block_iter_ . Valid ( ) ) ; <nl> - } <nl> <nl> - template < class TBlockIter , typename TValue > <nl> - void BlockBasedTableIterator < TBlockIter , TValue > : : FindKeyForward ( ) { <nl> - assert ( ! is_out_of_bound_ ) ; <nl> + IndexValue v = index_iter_ - > value ( ) ; <nl> <nl> - if ( ! block_iter_ . Valid ( ) ) { <nl> - FindBlockForward ( ) ; <nl> - } <nl> + / / TODO ( kolmike ) : Remove the ! = kBlockCacheTier condition . <nl> + if ( ! v . first_internal_key . empty ( ) & & <nl> + read_options_ . read_tier ! = kBlockCacheTier ) { <nl> + / / Index contains the first key of the block . Defer reading the block . <nl> + is_at_first_key_from_index_ = true ; <nl> + return ; <nl> + } <nl> + <nl> + InitDataBlock ( ) ; <nl> + block_iter_ . SeekToFirst ( ) ; <nl> + } while ( ! block_iter_ . Valid ( ) ) ; <nl> } <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : FindKeyBackward ( ) { <nl> <nl> template < class TBlockIter , typename TValue > <nl> void BlockBasedTableIterator < TBlockIter , TValue > : : CheckOutOfBound ( ) { <nl> - if ( read_options_ . iterate_upper_bound ! = nullptr & & <nl> - block_iter_points_to_real_block_ & & block_iter_ . Valid ( ) ) { <nl> + if ( read_options_ . iterate_upper_bound ! = nullptr & & Valid ( ) ) { <nl> is_out_of_bound_ = user_comparator_ . Compare ( <nl> * read_options_ . iterate_upper_bound , user_key ( ) ) < = 0 ; <nl> } <nl> InternalIterator * BlockBasedTable : : NewIterator ( <nl> ! skip_filters & & ! read_options . total_order_seek & & <nl> prefix_extractor ! = nullptr , <nl> need_upper_bound_check , prefix_extractor , BlockType : : kData , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , caller , <nl> - compaction_readahead_size ) ; <nl> + caller , compaction_readahead_size ) ; <nl> } else { <nl> auto * mem = <nl> arena - > AllocateAligned ( sizeof ( BlockBasedTableIterator < DataBlockIter > ) ) ; <nl> InternalIterator * BlockBasedTable : : NewIterator ( <nl> ! skip_filters & & ! read_options . total_order_seek & & <nl> prefix_extractor ! = nullptr , <nl> need_upper_bound_check , prefix_extractor , BlockType : : kData , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , caller , compaction_readahead_size ) ; <nl> + caller , compaction_readahead_size ) ; <nl> } <nl> } <nl> <nl> Status BlockBasedTable : : Get ( const ReadOptions & read_options , const Slice & key , <nl> auto iiter = <nl> NewIndexIterator ( read_options , need_upper_bound_check , & iiter_on_stack , <nl> get_context , & lookup_context ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter_unique_ptr ; <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter_unique_ptr ; <nl> if ( iiter ! = & iiter_on_stack ) { <nl> iiter_unique_ptr . reset ( iiter ) ; <nl> } <nl> Status BlockBasedTable : : Get ( const ReadOptions & read_options , const Slice & key , <nl> bool matched = false ; / / if such user key mathced a key in SST <nl> bool done = false ; <nl> for ( iiter - > Seek ( key ) ; iiter - > Valid ( ) & & ! done ; iiter - > Next ( ) ) { <nl> - BlockHandle handle = iiter - > value ( ) ; <nl> + IndexValue v = iiter - > value ( ) ; <nl> <nl> bool not_exist_in_filter = <nl> filter ! = nullptr & & filter - > IsBlockBased ( ) = = true & & <nl> ! filter - > KeyMayMatch ( ExtractUserKeyAndStripTimestamp ( key , ts_sz ) , <nl> - prefix_extractor , handle . offset ( ) , no_io , <nl> + prefix_extractor , v . handle . offset ( ) , no_io , <nl> / * const_ikey_ptr = * / nullptr , & lookup_context ) ; <nl> <nl> if ( not_exist_in_filter ) { <nl> Status BlockBasedTable : : Get ( const ReadOptions & read_options , const Slice & key , <nl> RecordTick ( rep_ - > ioptions . statistics , BLOOM_FILTER_USEFUL ) ; <nl> PERF_COUNTER_BY_LEVEL_ADD ( bloom_filter_useful , 1 , rep_ - > level ) ; <nl> break ; <nl> - } else { <nl> - BlockCacheLookupContext lookup_data_block_context { <nl> - TableReaderCaller : : kUserGet } ; <nl> - bool does_referenced_key_exist = false ; <nl> - DataBlockIter biter ; <nl> - uint64_t referenced_data_size = 0 ; <nl> - NewDataBlockIterator < DataBlockIter > ( <nl> - read_options , iiter - > value ( ) , & biter , BlockType : : kData , <nl> - / * key_includes_seq = * / true , <nl> - / * index_key_is_full = * / true , get_context , & lookup_data_block_context , <nl> - / * s = * / Status ( ) , / * prefetch_buffer * / nullptr ) ; <nl> + } <nl> <nl> - if ( read_options . read_tier = = kBlockCacheTier & & <nl> - biter . status ( ) . IsIncomplete ( ) ) { <nl> - / / couldn ' t get block from block_cache <nl> - / / Update Saver . state to Found because we are only looking for <nl> - / / whether we can guarantee the key is not there when " no_io " is set <nl> - get_context - > MarkKeyMayExist ( ) ; <nl> - break ; <nl> - } <nl> - if ( ! biter . status ( ) . ok ( ) ) { <nl> - s = biter . status ( ) ; <nl> - break ; <nl> - } <nl> + if ( ! v . first_internal_key . empty ( ) & & ! skip_filters & & <nl> + UserComparatorWrapper ( rep_ - > internal_comparator . user_comparator ( ) ) <nl> + . Compare ( ExtractUserKey ( key ) , <nl> + ExtractUserKey ( v . first_internal_key ) ) < 0 ) { <nl> + / / The requested key falls between highest key in previous block and <nl> + / / lowest key in current block . <nl> + break ; <nl> + } <nl> <nl> - bool may_exist = biter . SeekForGet ( key ) ; <nl> - / / If user - specified timestamp is supported , we cannot end the search <nl> - / / just because hash index lookup indicates the key + ts does not exist . <nl> - if ( ! may_exist & & ts_sz = = 0 ) { <nl> - / / HashSeek cannot find the key this block and the the iter is not <nl> - / / the end of the block , i . e . cannot be in the following blocks <nl> - / / either . In this case , the seek_key cannot be found , so we break <nl> - / / from the top level for - loop . <nl> - done = true ; <nl> - } else { <nl> - / / Call the * saver function on each entry / block until it returns false <nl> - for ( ; biter . Valid ( ) ; biter . Next ( ) ) { <nl> - ParsedInternalKey parsed_key ; <nl> - if ( ! ParseInternalKey ( biter . key ( ) , & parsed_key ) ) { <nl> - s = Status : : Corruption ( Slice ( ) ) ; <nl> - } <nl> + BlockCacheLookupContext lookup_data_block_context { <nl> + TableReaderCaller : : kUserGet } ; <nl> + bool does_referenced_key_exist = false ; <nl> + DataBlockIter biter ; <nl> + uint64_t referenced_data_size = 0 ; <nl> + NewDataBlockIterator < DataBlockIter > ( <nl> + read_options , v . handle , & biter , BlockType : : kData , <nl> + get_context , & lookup_data_block_context , <nl> + / * s = * / Status ( ) , / * prefetch_buffer * / nullptr ) ; <nl> + <nl> + if ( no_io & & biter . status ( ) . IsIncomplete ( ) ) { <nl> + / / couldn ' t get block from block_cache <nl> + / / Update Saver . state to Found because we are only looking for <nl> + / / whether we can guarantee the key is not there when " no_io " is set <nl> + get_context - > MarkKeyMayExist ( ) ; <nl> + break ; <nl> + } <nl> + if ( ! biter . status ( ) . ok ( ) ) { <nl> + s = biter . status ( ) ; <nl> + break ; <nl> + } <nl> <nl> - if ( ! get_context - > SaveValue ( <nl> - parsed_key , biter . value ( ) , & matched , <nl> - biter . IsValuePinned ( ) ? & biter : nullptr ) ) { <nl> - does_referenced_key_exist = true ; <nl> - referenced_data_size = biter . key ( ) . size ( ) + biter . value ( ) . size ( ) ; <nl> - done = true ; <nl> - break ; <nl> - } <nl> + bool may_exist = biter . SeekForGet ( key ) ; <nl> + / / If user - specified timestamp is supported , we cannot end the search <nl> + / / just because hash index lookup indicates the key + ts does not exist . <nl> + if ( ! may_exist & & ts_sz = = 0 ) { <nl> + / / HashSeek cannot find the key this block and the the iter is not <nl> + / / the end of the block , i . e . cannot be in the following blocks <nl> + / / either . In this case , the seek_key cannot be found , so we break <nl> + / / from the top level for - loop . <nl> + done = true ; <nl> + } else { <nl> + / / Call the * saver function on each entry / block until it returns false <nl> + for ( ; biter . Valid ( ) ; biter . Next ( ) ) { <nl> + ParsedInternalKey parsed_key ; <nl> + if ( ! ParseInternalKey ( biter . key ( ) , & parsed_key ) ) { <nl> + s = Status : : Corruption ( Slice ( ) ) ; <nl> + } <nl> + <nl> + if ( ! get_context - > SaveValue ( <nl> + parsed_key , biter . value ( ) , & matched , <nl> + biter . IsValuePinned ( ) ? & biter : nullptr ) ) { <nl> + does_referenced_key_exist = true ; <nl> + referenced_data_size = biter . key ( ) . size ( ) + biter . value ( ) . size ( ) ; <nl> + done = true ; <nl> + break ; <nl> } <nl> - s = biter . status ( ) ; <nl> - } <nl> - / / Write the block cache access record . <nl> - if ( block_cache_tracer_ ) { <nl> - / / Avoid making copy of block_key , cf_name , and referenced_key when <nl> - / / constructing the access record . <nl> - BlockCacheTraceRecord access_record ( <nl> - rep_ - > ioptions . env - > NowMicros ( ) , <nl> - / * block_key = * / " " , lookup_data_block_context . block_type , <nl> - lookup_data_block_context . block_size , rep_ - > cf_id_for_tracing ( ) , <nl> - / * cf_name = * / " " , rep_ - > level_for_tracing ( ) , <nl> - rep_ - > sst_number_for_tracing ( ) , lookup_data_block_context . caller , <nl> - lookup_data_block_context . is_cache_hit , <nl> - lookup_data_block_context . no_insert , <nl> - / * referenced_key = * / " " , referenced_data_size , <nl> - lookup_data_block_context . num_keys_in_block , <nl> - does_referenced_key_exist ) ; <nl> - block_cache_tracer_ - > WriteBlockAccess ( <nl> - access_record , lookup_data_block_context . block_key , <nl> - rep_ - > cf_name_for_tracing ( ) , key ) ; <nl> } <nl> + s = biter . status ( ) ; <nl> + } <nl> + / / Write the block cache access record . <nl> + if ( block_cache_tracer_ ) { <nl> + / / Avoid making copy of block_key , cf_name , and referenced_key when <nl> + / / constructing the access record . <nl> + BlockCacheTraceRecord access_record ( <nl> + rep_ - > ioptions . env - > NowMicros ( ) , <nl> + / * block_key = * / " " , lookup_data_block_context . block_type , <nl> + lookup_data_block_context . block_size , rep_ - > cf_id_for_tracing ( ) , <nl> + / * cf_name = * / " " , rep_ - > level_for_tracing ( ) , <nl> + rep_ - > sst_number_for_tracing ( ) , lookup_data_block_context . caller , <nl> + lookup_data_block_context . is_cache_hit , <nl> + lookup_data_block_context . no_insert , <nl> + / * referenced_key = * / " " , referenced_data_size , <nl> + lookup_data_block_context . num_keys_in_block , <nl> + does_referenced_key_exist ) ; <nl> + block_cache_tracer_ - > WriteBlockAccess ( <nl> + access_record , lookup_data_block_context . block_key , <nl> + rep_ - > cf_name_for_tracing ( ) , key ) ; <nl> } <nl> <nl> if ( done ) { <nl> void BlockBasedTable : : MultiGet ( const ReadOptions & read_options , <nl> auto iiter = <nl> NewIndexIterator ( read_options , need_upper_bound_check , & iiter_on_stack , <nl> sst_file_range . begin ( ) - > get_context , & lookup_context ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter_unique_ptr ; <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter_unique_ptr ; <nl> if ( iiter ! = & iiter_on_stack ) { <nl> iiter_unique_ptr . reset ( iiter ) ; <nl> } <nl> void BlockBasedTable : : MultiGet ( const ReadOptions & read_options , <nl> bool matched = false ; / / if such user key matched a key in SST <nl> bool done = false ; <nl> for ( iiter - > Seek ( key ) ; iiter - > Valid ( ) & & ! done ; iiter - > Next ( ) ) { <nl> + IndexValue v = iiter - > value ( ) ; <nl> + if ( ! v . first_internal_key . empty ( ) & & ! skip_filters & & <nl> + UserComparatorWrapper ( rep_ - > internal_comparator . user_comparator ( ) ) <nl> + . Compare ( ExtractUserKey ( key ) , <nl> + ExtractUserKey ( v . first_internal_key ) ) < 0 ) { <nl> + / / The requested key falls between highest key in previous block and <nl> + / / lowest key in current block . <nl> + break ; <nl> + } <nl> + <nl> bool reusing_block = true ; <nl> uint64_t referenced_data_size = 0 ; <nl> bool does_referenced_key_exist = false ; <nl> BlockCacheLookupContext lookup_data_block_context ( <nl> TableReaderCaller : : kUserMultiGet ) ; <nl> - if ( iiter - > value ( ) . offset ( ) ! = offset ) { <nl> - offset = iiter - > value ( ) . offset ( ) ; <nl> + if ( iiter - > value ( ) . handle . offset ( ) ! = offset ) { <nl> + offset = iiter - > value ( ) . handle . offset ( ) ; <nl> biter . Invalidate ( Status : : OK ( ) ) ; <nl> NewDataBlockIterator < DataBlockIter > ( <nl> - read_options , iiter - > value ( ) , & biter , BlockType : : kData , <nl> - / * key_includes_seq = * / false , <nl> - / * index_key_is_full = * / true , get_context , <nl> - & lookup_data_block_context , Status ( ) , nullptr ) ; <nl> + read_options , v . handle , & biter , BlockType : : kData , <nl> + get_context , & lookup_data_block_context , Status ( ) , nullptr ) ; <nl> reusing_block = false ; <nl> } <nl> + <nl> if ( read_options . read_tier = = kBlockCacheTier & & <nl> biter . status ( ) . IsIncomplete ( ) ) { <nl> / / couldn ' t get block from block_cache <nl> void BlockBasedTable : : MultiGet ( const ReadOptions & read_options , <nl> Status BlockBasedTable : : Prefetch ( const Slice * const begin , <nl> const Slice * const end ) { <nl> auto & comparator = rep_ - > internal_comparator ; <nl> - auto user_comparator = comparator . user_comparator ( ) ; <nl> + UserComparatorWrapper user_comparator ( comparator . user_comparator ( ) ) ; <nl> / / pre - condition <nl> if ( begin & & end & & comparator . Compare ( * begin , * end ) > 0 ) { <nl> return Status : : InvalidArgument ( * begin , * end ) ; <nl> Status BlockBasedTable : : Prefetch ( const Slice * const begin , <nl> auto iiter = NewIndexIterator ( ReadOptions ( ) , / * need_upper_bound_check = * / false , <nl> & iiter_on_stack , / * get_context = * / nullptr , <nl> & lookup_context ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter_unique_ptr ; <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter_unique_ptr ; <nl> if ( iiter ! = & iiter_on_stack ) { <nl> - iiter_unique_ptr = <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > ( iiter ) ; <nl> + iiter_unique_ptr = std : : unique_ptr < InternalIteratorBase < IndexValue > > ( iiter ) ; <nl> } <nl> <nl> if ( ! iiter - > status ( ) . ok ( ) ) { <nl> Status BlockBasedTable : : Prefetch ( const Slice * const begin , <nl> <nl> for ( begin ? iiter - > Seek ( * begin ) : iiter - > SeekToFirst ( ) ; iiter - > Valid ( ) ; <nl> iiter - > Next ( ) ) { <nl> - BlockHandle block_handle = iiter - > value ( ) ; <nl> - const bool is_user_key = rep_ - > table_properties & & <nl> - rep_ - > table_properties - > index_key_is_user_key > 0 ; <nl> + BlockHandle block_handle = iiter - > value ( ) . handle ; <nl> + const bool is_user_key = ! rep_ - > index_key_includes_seq ; <nl> if ( end & & <nl> ( ( ! is_user_key & & comparator . Compare ( iiter - > key ( ) , * end ) > = 0 ) | | <nl> ( is_user_key & & <nl> - user_comparator - > Compare ( iiter - > key ( ) , ExtractUserKey ( * end ) ) > = 0 ) ) ) { <nl> + user_comparator . Compare ( iiter - > key ( ) , ExtractUserKey ( * end ) ) > = 0 ) ) ) { <nl> if ( prefetching_boundary_page ) { <nl> break ; <nl> } <nl> Status BlockBasedTable : : Prefetch ( const Slice * const begin , <nl> <nl> NewDataBlockIterator < DataBlockIter > ( <nl> ReadOptions ( ) , block_handle , & biter , / * type = * / BlockType : : kData , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , <nl> / * get_context = * / nullptr , & lookup_context , Status ( ) , <nl> / * prefetch_buffer = * / nullptr ) ; <nl> <nl> Status BlockBasedTable : : VerifyChecksum ( TableReaderCaller caller ) { <nl> / / Check Data blocks <nl> IndexBlockIter iiter_on_stack ; <nl> BlockCacheLookupContext context { caller } ; <nl> - InternalIteratorBase < BlockHandle > * iiter = NewIndexIterator ( <nl> + InternalIteratorBase < IndexValue > * iiter = NewIndexIterator ( <nl> ReadOptions ( ) , / * need_upper_bound_check = * / false , & iiter_on_stack , <nl> / * get_context = * / nullptr , & context ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter_unique_ptr ; <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter_unique_ptr ; <nl> if ( iiter ! = & iiter_on_stack ) { <nl> - iiter_unique_ptr = <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > ( iiter ) ; <nl> + iiter_unique_ptr = std : : unique_ptr < InternalIteratorBase < IndexValue > > ( iiter ) ; <nl> } <nl> if ( ! iiter - > status ( ) . ok ( ) ) { <nl> / / error opening index iterator <nl> Status BlockBasedTable : : VerifyChecksum ( TableReaderCaller caller ) { <nl> } <nl> <nl> Status BlockBasedTable : : VerifyChecksumInBlocks ( <nl> - InternalIteratorBase < BlockHandle > * index_iter ) { <nl> + InternalIteratorBase < IndexValue > * index_iter ) { <nl> Status s ; <nl> for ( index_iter - > SeekToFirst ( ) ; index_iter - > Valid ( ) ; index_iter - > Next ( ) ) { <nl> s = index_iter - > status ( ) ; <nl> if ( ! s . ok ( ) ) { <nl> break ; <nl> } <nl> - BlockHandle handle = index_iter - > value ( ) ; <nl> + BlockHandle handle = index_iter - > value ( ) . handle ; <nl> BlockContents contents ; <nl> BlockFetcher block_fetcher ( <nl> rep_ - > file . get ( ) , nullptr / * prefetch buffer * / , rep_ - > footer , <nl> bool BlockBasedTable : : TEST_BlockInCache ( const BlockHandle & handle ) const { <nl> <nl> bool BlockBasedTable : : TEST_KeyInCache ( const ReadOptions & options , <nl> const Slice & key ) { <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > iiter ( NewIndexIterator ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > iiter ( NewIndexIterator ( <nl> options , / * need_upper_bound_check = * / false , / * input_iter = * / nullptr , <nl> / * get_context = * / nullptr , / * lookup_contex = * / nullptr ) ) ; <nl> iiter - > Seek ( key ) ; <nl> assert ( iiter - > Valid ( ) ) ; <nl> <nl> - return TEST_BlockInCache ( iiter - > value ( ) ) ; <nl> - } <nl> - <nl> - BlockBasedTableOptions : : IndexType BlockBasedTable : : UpdateIndexType ( ) { <nl> - / / Some old version of block - based tables don ' t have index type present in <nl> - / / table properties . If that ' s the case we can safely use the kBinarySearch . <nl> - BlockBasedTableOptions : : IndexType index_type_on_file = <nl> - BlockBasedTableOptions : : kBinarySearch ; <nl> - if ( rep_ - > table_properties ) { <nl> - auto & props = rep_ - > table_properties - > user_collected_properties ; <nl> - auto pos = props . find ( BlockBasedTablePropertyNames : : kIndexType ) ; <nl> - if ( pos ! = props . end ( ) ) { <nl> - index_type_on_file = static_cast < BlockBasedTableOptions : : IndexType > ( <nl> - DecodeFixed32 ( pos - > second . c_str ( ) ) ) ; <nl> - / / update index_type with the true type <nl> - rep_ - > index_type = index_type_on_file ; <nl> - } <nl> - } <nl> - return index_type_on_file ; <nl> + return TEST_BlockInCache ( iiter - > value ( ) . handle ) ; <nl> } <nl> <nl> / / REQUIRES : The following fields of rep_ should have already been populated : <nl> Status BlockBasedTable : : CreateIndexReader ( <nl> InternalIterator * preloaded_meta_index_iter , bool use_cache , bool prefetch , <nl> bool pin , IndexReader * * index_reader , <nl> BlockCacheLookupContext * lookup_context ) { <nl> - auto index_type_on_file = rep_ - > index_type ; <nl> - <nl> / / kHashSearch requires non - empty prefix_extractor but bypass checking <nl> / / prefix_extractor here since we have no access to MutableCFOptions . <nl> / / Add need_upper_bound_check flag in BlockBasedTable : : NewIndexIterator . <nl> / / If prefix_extractor does not match prefix_extractor_name from table <nl> / / properties , turn off Hash Index by setting total_order_seek to true <nl> <nl> - switch ( index_type_on_file ) { <nl> + switch ( rep_ - > index_type ) { <nl> case BlockBasedTableOptions : : kTwoLevelIndexSearch : { <nl> return PartitionIndexReader : : Create ( this , prefetch_buffer , use_cache , <nl> prefetch , pin , index_reader , <nl> lookup_context ) ; <nl> } <nl> - case BlockBasedTableOptions : : kBinarySearch : { <nl> + case BlockBasedTableOptions : : kBinarySearch : <nl> + case BlockBasedTableOptions : : kBinarySearchWithFirstKey : { <nl> return BinarySearchIndexReader : : Create ( this , prefetch_buffer , use_cache , <nl> prefetch , pin , index_reader , <nl> lookup_context ) ; <nl> Status BlockBasedTable : : CreateIndexReader ( <nl> } <nl> default : { <nl> std : : string error_message = <nl> - " Unrecognized index type : " + ToString ( index_type_on_file ) ; <nl> + " Unrecognized index type : " + ToString ( rep_ - > index_type ) ; <nl> return Status : : InvalidArgument ( error_message . c_str ( ) ) ; <nl> } <nl> } <nl> Status BlockBasedTable : : CreateIndexReader ( <nl> uint64_t BlockBasedTable : : ApproximateOffsetOf ( const Slice & key , <nl> TableReaderCaller caller ) { <nl> BlockCacheLookupContext context ( caller ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > index_iter ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > index_iter ( <nl> NewIndexIterator ( ReadOptions ( ) , / * need_upper_bound_check = * / false , <nl> / * input_iter = * / nullptr , / * get_context = * / nullptr , <nl> / * lookup_contex = * / & context ) ) ; <nl> uint64_t BlockBasedTable : : ApproximateOffsetOf ( const Slice & key , <nl> index_iter - > Seek ( key ) ; <nl> uint64_t result ; <nl> if ( index_iter - > Valid ( ) ) { <nl> - BlockHandle handle = index_iter - > value ( ) ; <nl> + BlockHandle handle = index_iter - > value ( ) . handle ; <nl> result = handle . offset ( ) ; <nl> } else { <nl> / / key is past the last key in the file . If table_properties is not <nl> bool BlockBasedTable : : TEST_IndexBlockInCache ( ) const { <nl> <nl> Status BlockBasedTable : : GetKVPairsFromDataBlocks ( <nl> std : : vector < KVPairBlock > * kv_pair_blocks ) { <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > blockhandles_iter ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > blockhandles_iter ( <nl> NewIndexIterator ( ReadOptions ( ) , / * need_upper_bound_check = * / false , <nl> / * input_iter = * / nullptr , / * get_context = * / nullptr , <nl> / * lookup_contex = * / nullptr ) ) ; <nl> Status BlockBasedTable : : GetKVPairsFromDataBlocks ( <nl> <nl> std : : unique_ptr < InternalIterator > datablock_iter ; <nl> datablock_iter . reset ( NewDataBlockIterator < DataBlockIter > ( <nl> - ReadOptions ( ) , blockhandles_iter - > value ( ) , / * input_iter = * / nullptr , <nl> - / * type = * / BlockType : : kData , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , <nl> + ReadOptions ( ) , blockhandles_iter - > value ( ) . handle , <nl> + / * input_iter = * / nullptr , / * type = * / BlockType : : kData , <nl> / * get_context = * / nullptr , / * lookup_context = * / nullptr , Status ( ) , <nl> / * prefetch_buffer = * / nullptr ) ) ; <nl> s = datablock_iter - > status ( ) ; <nl> Status BlockBasedTable : : DumpIndexBlock ( WritableFile * out_file ) { <nl> out_file - > Append ( <nl> " Index Details : \ n " <nl> " mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - \ n " ) ; <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > blockhandles_iter ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > blockhandles_iter ( <nl> NewIndexIterator ( ReadOptions ( ) , / * need_upper_bound_check = * / false , <nl> / * input_iter = * / nullptr , / * get_context = * / nullptr , <nl> / * lookup_contex = * / nullptr ) ) ; <nl> Status BlockBasedTable : : DumpIndexBlock ( WritableFile * out_file ) { <nl> Slice key = blockhandles_iter - > key ( ) ; <nl> Slice user_key ; <nl> InternalKey ikey ; <nl> - if ( rep_ - > table_properties & & <nl> - rep_ - > table_properties - > index_key_is_user_key ! = 0 ) { <nl> + if ( ! rep_ - > index_key_includes_seq ) { <nl> user_key = key ; <nl> } else { <nl> ikey . DecodeFrom ( key ) ; <nl> Status BlockBasedTable : : DumpIndexBlock ( WritableFile * out_file ) { <nl> out_file - > Append ( " HEX " ) ; <nl> out_file - > Append ( user_key . ToString ( true ) . c_str ( ) ) ; <nl> out_file - > Append ( " : " ) ; <nl> - out_file - > Append ( blockhandles_iter - > value ( ) . ToString ( true ) . c_str ( ) ) ; <nl> + out_file - > Append ( blockhandles_iter - > value ( ) <nl> + . ToString ( true , rep_ - > index_has_first_key ) <nl> + . c_str ( ) ) ; <nl> out_file - > Append ( " \ n " ) ; <nl> <nl> std : : string str_key = user_key . ToString ( ) ; <nl> Status BlockBasedTable : : DumpIndexBlock ( WritableFile * out_file ) { <nl> } <nl> <nl> Status BlockBasedTable : : DumpDataBlocks ( WritableFile * out_file ) { <nl> - std : : unique_ptr < InternalIteratorBase < BlockHandle > > blockhandles_iter ( <nl> + std : : unique_ptr < InternalIteratorBase < IndexValue > > blockhandles_iter ( <nl> NewIndexIterator ( ReadOptions ( ) , / * need_upper_bound_check = * / false , <nl> / * input_iter = * / nullptr , / * get_context = * / nullptr , <nl> / * lookup_contex = * / nullptr ) ) ; <nl> Status BlockBasedTable : : DumpDataBlocks ( WritableFile * out_file ) { <nl> break ; <nl> } <nl> <nl> - BlockHandle bh = blockhandles_iter - > value ( ) ; <nl> + BlockHandle bh = blockhandles_iter - > value ( ) . handle ; <nl> uint64_t datablock_size = bh . size ( ) ; <nl> datablock_size_min = std : : min ( datablock_size_min , datablock_size ) ; <nl> datablock_size_max = std : : max ( datablock_size_max , datablock_size ) ; <nl> Status BlockBasedTable : : DumpDataBlocks ( WritableFile * out_file ) { <nl> out_file - > Append ( " Data Block # " ) ; <nl> out_file - > Append ( rocksdb : : ToString ( block_id ) ) ; <nl> out_file - > Append ( " @ " ) ; <nl> - out_file - > Append ( blockhandles_iter - > value ( ) . ToString ( true ) . c_str ( ) ) ; <nl> + out_file - > Append ( blockhandles_iter - > value ( ) . handle . ToString ( true ) . c_str ( ) ) ; <nl> out_file - > Append ( " \ n " ) ; <nl> out_file - > Append ( " mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - \ n " ) ; <nl> <nl> std : : unique_ptr < InternalIterator > datablock_iter ; <nl> datablock_iter . reset ( NewDataBlockIterator < DataBlockIter > ( <nl> - ReadOptions ( ) , blockhandles_iter - > value ( ) , / * input_iter = * / nullptr , <nl> - / * type = * / BlockType : : kData , <nl> - / * key_includes_seq = * / true , / * index_key_is_full = * / true , <nl> + ReadOptions ( ) , blockhandles_iter - > value ( ) . handle , <nl> + / * input_iter = * / nullptr , / * type = * / BlockType : : kData , <nl> / * get_context = * / nullptr , / * lookup_context = * / nullptr , Status ( ) , <nl> / * prefetch_buffer = * / nullptr ) ) ; <nl> s = datablock_iter - > status ( ) ; <nl> mmm a / table / block_based / block_based_table_reader . h <nl> ppp b / table / block_based / block_based_table_reader . h <nl> <nl> <nl> namespace rocksdb { <nl> <nl> - class BlockHandle ; <nl> class Cache ; <nl> class FilterBlockReader ; <nl> class BlockBasedFilterBlockReader ; <nl> class BlockBasedTable : public TableReader { <nl> / / wraps the passed iter . In the latter case the return value points <nl> / / to a different object then iter , and the callee has the ownership of the <nl> / / returned object . <nl> - virtual InternalIteratorBase < BlockHandle > * NewIterator ( <nl> + virtual InternalIteratorBase < IndexValue > * NewIterator ( <nl> const ReadOptions & read_options , bool disable_prefix_seek , <nl> IndexBlockIter * iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) = 0 ; <nl> class BlockBasedTable : public TableReader { <nl> template < typename TBlockIter > <nl> TBlockIter * NewDataBlockIterator ( <nl> const ReadOptions & ro , const BlockHandle & block_handle , <nl> - TBlockIter * input_iter , BlockType block_type , bool key_includes_seq , <nl> - bool index_key_is_full , GetContext * get_context , <nl> + TBlockIter * input_iter , BlockType block_type , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context , Status s , <nl> FilePrefetchBuffer * prefetch_buffer , bool for_compaction = false ) const ; <nl> <nl> class BlockBasedTable : public TableReader { <nl> BlockType block_type , <nl> GetContext * get_context ) const ; <nl> <nl> + / / Either Block : : NewDataIterator ( ) or Block : : NewIndexIterator ( ) . <nl> + template < typename TBlockIter > <nl> + static TBlockIter * InitBlockIterator ( const Rep * rep , Block * block , <nl> + TBlockIter * input_iter , <nl> + bool block_contents_pinned ) ; <nl> + <nl> / / If block cache enabled ( compressed or uncompressed ) , looks for the block <nl> / / identified by handle in ( 1 ) uncompressed cache , ( 2 ) compressed cache , and <nl> / / then ( 3 ) file . If found , inserts into the cache ( s ) that were searched <nl> class BlockBasedTable : public TableReader { <nl> / / 2 . index is not present in block cache . <nl> / / 3 . We disallowed any io to be performed , that is , read_options = = <nl> / / kBlockCacheTier <nl> - InternalIteratorBase < BlockHandle > * NewIndexIterator ( <nl> + InternalIteratorBase < IndexValue > * NewIndexIterator ( <nl> const ReadOptions & read_options , bool need_upper_bound_check , <nl> IndexBlockIter * input_iter , GetContext * get_context , <nl> BlockCacheLookupContext * lookup_context ) const ; <nl> class BlockBasedTable : public TableReader { <nl> friend class TableCache ; <nl> friend class BlockBasedTableBuilder ; <nl> <nl> - / / Figure the index type , update it in rep_ , and also return it . <nl> - BlockBasedTableOptions : : IndexType UpdateIndexType ( ) ; <nl> - <nl> / / Create a index reader based on the index type stored in the table . <nl> / / Optionally , user can pass a preloaded meta_index_iter for the index that <nl> / / need to access extra meta blocks for index construction . This parameter <nl> class BlockBasedTable : public TableReader { <nl> static BlockType GetBlockTypeForMetaBlockByName ( const Slice & meta_block_name ) ; <nl> <nl> Status VerifyChecksumInMetaBlocks ( InternalIteratorBase < Slice > * index_iter ) ; <nl> - Status VerifyChecksumInBlocks ( InternalIteratorBase < BlockHandle > * index_iter ) ; <nl> + Status VerifyChecksumInBlocks ( InternalIteratorBase < IndexValue > * index_iter ) ; <nl> <nl> / / Create the filter from the filter block . <nl> virtual FilterBlockReader * ReadFilter ( <nl> class BlockBasedTable : : PartitionedIndexIteratorState <nl> public : <nl> PartitionedIndexIteratorState ( <nl> const BlockBasedTable * table , <nl> - std : : unordered_map < uint64_t , CachableEntry < Block > > * block_map , <nl> - const bool index_key_includes_seq , const bool index_key_is_full ) ; <nl> - InternalIteratorBase < BlockHandle > * NewSecondaryIterator ( <nl> + std : : unordered_map < uint64_t , CachableEntry < Block > > * block_map ) ; <nl> + InternalIteratorBase < IndexValue > * NewSecondaryIterator ( <nl> const BlockHandle & index_value ) override ; <nl> <nl> private : <nl> / / Don ' t own table_ <nl> const BlockBasedTable * table_ ; <nl> std : : unordered_map < uint64_t , CachableEntry < Block > > * block_map_ ; <nl> - bool index_key_includes_seq_ ; <nl> - bool index_key_is_full_ ; <nl> } ; <nl> <nl> / / Stores all the properties associated with a BlockBasedTable . <nl> struct BlockBasedTable : : Rep { <nl> / / still work , just not as quickly . <nl> bool blocks_definitely_zstd_compressed = false ; <nl> <nl> + / / These describe how index is encoded . <nl> + bool index_has_first_key = false ; <nl> + bool index_key_includes_seq = true ; <nl> + bool index_value_is_full = true ; <nl> + <nl> bool closed = false ; <nl> const bool immortal_table ; <nl> <nl> SequenceNumber get_global_seqno ( BlockType block_type ) const { <nl> return ( block_type = = BlockType : : kFilter | | <nl> - block_type = = BlockType : : kIndex | | <nl> block_type = = BlockType : : kCompressionDictionary ) <nl> ? kDisableGlobalSequenceNumber <nl> : global_seqno ; <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> BlockBasedTableIterator ( const BlockBasedTable * table , <nl> const ReadOptions & read_options , <nl> const InternalKeyComparator & icomp , <nl> - InternalIteratorBase < BlockHandle > * index_iter , <nl> + InternalIteratorBase < IndexValue > * index_iter , <nl> bool check_filter , bool need_upper_bound_check , <nl> const SliceTransform * prefix_extractor , <nl> - BlockType block_type , bool key_includes_seq , <nl> - bool index_key_is_full , TableReaderCaller caller , <nl> + BlockType block_type , TableReaderCaller caller , <nl> size_t compaction_readahead_size = 0 ) <nl> : InternalIteratorBase < TValue > ( false ) , <nl> table_ ( table ) , <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> need_upper_bound_check_ ( need_upper_bound_check ) , <nl> prefix_extractor_ ( prefix_extractor ) , <nl> block_type_ ( block_type ) , <nl> - key_includes_seq_ ( key_includes_seq ) , <nl> - index_key_is_full_ ( index_key_is_full ) , <nl> lookup_context_ ( caller ) , <nl> compaction_readahead_size_ ( compaction_readahead_size ) { } <nl> <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> bool NextAndGetResult ( Slice * ret_key ) override ; <nl> void Prev ( ) override ; <nl> bool Valid ( ) const override { <nl> - return ! is_out_of_bound_ & & block_iter_points_to_real_block_ & & <nl> - block_iter_ . Valid ( ) ; <nl> + return ! is_out_of_bound_ & & <nl> + ( is_at_first_key_from_index_ | | <nl> + ( block_iter_points_to_real_block_ & & block_iter_ . Valid ( ) ) ) ; <nl> } <nl> Slice key ( ) const override { <nl> assert ( Valid ( ) ) ; <nl> - return block_iter_ . key ( ) ; <nl> + if ( is_at_first_key_from_index_ ) { <nl> + return index_iter_ - > value ( ) . first_internal_key ; <nl> + } else { <nl> + return block_iter_ . key ( ) ; <nl> + } <nl> } <nl> Slice user_key ( ) const override { <nl> assert ( Valid ( ) ) ; <nl> - return block_iter_ . user_key ( ) ; <nl> + if ( is_at_first_key_from_index_ ) { <nl> + return ExtractUserKey ( index_iter_ - > value ( ) . first_internal_key ) ; <nl> + } else { <nl> + return block_iter_ . user_key ( ) ; <nl> + } <nl> } <nl> TValue value ( ) const override { <nl> assert ( Valid ( ) ) ; <nl> + <nl> + / / Load current block if not loaded . <nl> + if ( is_at_first_key_from_index_ & & <nl> + ! const_cast < BlockBasedTableIterator * > ( this ) <nl> + - > MaterializeCurrentBlock ( ) ) { <nl> + / / Oops , index is not consistent with block contents , but we have <nl> + / / no good way to report error at this point . Let ' s return empty value . <nl> + return TValue ( ) ; <nl> + } <nl> + <nl> return block_iter_ . value ( ) ; <nl> } <nl> Status status ( ) const override { <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> pinned_iters_mgr_ = pinned_iters_mgr ; <nl> } <nl> bool IsKeyPinned ( ) const override { <nl> + / / Our key comes either from block_iter_ ' s current key <nl> + / / or index_iter_ ' s current * value * . <nl> return pinned_iters_mgr_ & & pinned_iters_mgr_ - > PinningEnabled ( ) & & <nl> - block_iter_points_to_real_block_ & & block_iter_ . IsKeyPinned ( ) ; <nl> + ( ( is_at_first_key_from_index_ & & index_iter_ - > IsValuePinned ( ) ) | | <nl> + ( block_iter_points_to_real_block_ & & block_iter_ . IsKeyPinned ( ) ) ) ; <nl> } <nl> bool IsValuePinned ( ) const override { <nl> + / / Load current block if not loaded . <nl> + if ( is_at_first_key_from_index_ ) { <nl> + const_cast < BlockBasedTableIterator * > ( this ) - > MaterializeCurrentBlock ( ) ; <nl> + } <nl> / / BlockIter : : IsValuePinned ( ) is always true . No need to check <nl> return pinned_iters_mgr_ & & pinned_iters_mgr_ - > PinningEnabled ( ) & & <nl> block_iter_points_to_real_block_ ; <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> if ( block_iter_points_to_real_block_ ) { <nl> / / Reseek . If they end up with the same data block , we shouldn ' t re - fetch <nl> / / the same data block . <nl> - prev_index_value_ = index_iter_ - > value ( ) ; <nl> + prev_block_offset_ = index_iter_ - > value ( ) . handle . offset ( ) ; <nl> } <nl> } <nl> <nl> - void InitDataBlock ( ) ; <nl> - inline void FindKeyForward ( ) ; <nl> - void FindBlockForward ( ) ; <nl> - void FindKeyBackward ( ) ; <nl> - void CheckOutOfBound ( ) ; <nl> - <nl> private : <nl> const BlockBasedTable * table_ ; <nl> const ReadOptions read_options_ ; <nl> const InternalKeyComparator & icomp_ ; <nl> UserComparatorWrapper user_comparator_ ; <nl> - InternalIteratorBase < BlockHandle > * index_iter_ ; <nl> + InternalIteratorBase < IndexValue > * index_iter_ ; <nl> PinnedIteratorsManager * pinned_iters_mgr_ ; <nl> TBlockIter block_iter_ ; <nl> + <nl> + / / True if block_iter_ is initialized and points to the same block <nl> + / / as index iterator . <nl> bool block_iter_points_to_real_block_ ; <nl> + / / See InternalIteratorBase : : IsOutOfBound ( ) . <nl> bool is_out_of_bound_ = false ; <nl> + / / True if we ' re standing at the first key of a block , and we haven ' t loaded <nl> + / / that block yet . A call to value ( ) will trigger loading the block . <nl> + bool is_at_first_key_from_index_ = false ; <nl> bool check_filter_ ; <nl> / / TODO ( Zhongyi ) : pick a better name <nl> bool need_upper_bound_check_ ; <nl> const SliceTransform * prefix_extractor_ ; <nl> BlockType block_type_ ; <nl> - / / If the keys in the blocks over which we iterate include 8 byte sequence <nl> - bool key_includes_seq_ ; <nl> - bool index_key_is_full_ ; <nl> - BlockHandle prev_index_value_ ; <nl> + uint64_t prev_block_offset_ ; <nl> BlockCacheLookupContext lookup_context_ ; <nl> / / Readahead size used in compaction , its value is used only if <nl> / / lookup_context_ . caller = kCompaction . <nl> class BlockBasedTableIterator : public InternalIteratorBase < TValue > { <nl> size_t readahead_limit_ = 0 ; <nl> int64_t num_file_reads_ = 0 ; <nl> std : : unique_ptr < FilePrefetchBuffer > prefetch_buffer_ ; <nl> + <nl> + / / If ` target ` is null , seek to first . <nl> + void SeekImpl ( const Slice * target ) ; <nl> + <nl> + void InitDataBlock ( ) ; <nl> + bool MaterializeCurrentBlock ( ) ; <nl> + void FindKeyForward ( ) ; <nl> + void FindBlockForward ( ) ; <nl> + void FindKeyBackward ( ) ; <nl> + void CheckOutOfBound ( ) ; <nl> } ; <nl> <nl> } / / namespace rocksdb <nl> mmm a / table / block_based / block_test . cc <nl> ppp b / table / block_based / block_test . cc <nl> void GenerateRandomKVs ( std : : vector < std : : string > * keys , <nl> } <nl> } <nl> <nl> - / / Same as GenerateRandomKVs but the values are BlockHandle <nl> - void GenerateRandomKBHs ( std : : vector < std : : string > * keys , <nl> - std : : vector < BlockHandle > * values , const int from , <nl> - const int len , const int step = 1 , <nl> - const int padding_size = 0 , <nl> - const int keys_share_prefix = 1 ) { <nl> - Random rnd ( 302 ) ; <nl> - uint64_t offset = 0 ; <nl> - <nl> - / / generate different prefix <nl> - for ( int i = from ; i < from + len ; i + = step ) { <nl> - / / generate keys that shares the prefix <nl> - for ( int j = 0 ; j < keys_share_prefix ; + + j ) { <nl> - keys - > emplace_back ( GenerateKey ( i , j , padding_size , & rnd ) ) ; <nl> - <nl> - uint64_t size = rnd . Uniform ( 1024 * 16 ) ; <nl> - BlockHandle handle ( offset , size ) ; <nl> - offset + = size + kBlockTrailerSize ; <nl> - values - > emplace_back ( handle ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> class BlockTest : public testing : : Test { } ; <nl> <nl> / / block test <nl> TEST_F ( BlockTest , SimpleTest ) { <nl> Random rnd ( 301 ) ; <nl> Options options = Options ( ) ; <nl> - std : : unique_ptr < InternalKeyComparator > ic ; <nl> - ic . reset ( new test : : PlainInternalKeyComparator ( options . comparator ) ) ; <nl> <nl> std : : vector < std : : string > keys ; <nl> std : : vector < std : : string > values ; <nl> TEST_F ( BlockTest , SimpleTest ) { <nl> / / read contents of block sequentially <nl> int count = 0 ; <nl> InternalIterator * iter = <nl> - reader . NewIterator < DataBlockIter > ( options . comparator , options . comparator ) ; <nl> + reader . NewDataIterator ( options . comparator , options . comparator ) ; <nl> for ( iter - > SeekToFirst ( ) ; iter - > Valid ( ) ; count + + , iter - > Next ( ) ) { <nl> / / read kv from block <nl> Slice k = iter - > key ( ) ; <nl> TEST_F ( BlockTest , SimpleTest ) { <nl> delete iter ; <nl> <nl> / / read block contents randomly <nl> - iter = <nl> - reader . NewIterator < DataBlockIter > ( options . comparator , options . comparator ) ; <nl> + iter = reader . NewDataIterator ( options . comparator , options . comparator ) ; <nl> for ( int i = 0 ; i < num_records ; i + + ) { <nl> / / find a random key in the lookaside array <nl> int index = rnd . Uniform ( num_records ) ; <nl> TEST_F ( BlockTest , SimpleTest ) { <nl> delete iter ; <nl> } <nl> <nl> - TEST_F ( BlockTest , ValueDeltaEncodingTest ) { <nl> - Random rnd ( 301 ) ; <nl> - Options options = Options ( ) ; <nl> - std : : unique_ptr < InternalKeyComparator > ic ; <nl> - ic . reset ( new test : : PlainInternalKeyComparator ( options . comparator ) ) ; <nl> - <nl> - std : : vector < std : : string > keys ; <nl> - std : : vector < BlockHandle > values ; <nl> - const bool kUseDeltaEncoding = true ; <nl> - const bool kUseValueDeltaEncoding = true ; <nl> - BlockBuilder builder ( 16 , kUseDeltaEncoding , kUseValueDeltaEncoding ) ; <nl> - int num_records = 100 ; <nl> - <nl> - GenerateRandomKBHs ( & keys , & values , 0 , num_records ) ; <nl> - / / add a bunch of records to a block <nl> - BlockHandle last_encoded_handle ; <nl> - for ( int i = 0 ; i < num_records ; i + + ) { <nl> - auto block_handle = values [ i ] ; <nl> - std : : string handle_encoding ; <nl> - block_handle . EncodeTo ( & handle_encoding ) ; <nl> - std : : string handle_delta_encoding ; <nl> - PutVarsignedint64 ( & handle_delta_encoding , <nl> - block_handle . size ( ) - last_encoded_handle . size ( ) ) ; <nl> - last_encoded_handle = block_handle ; <nl> - const Slice handle_delta_encoding_slice ( handle_delta_encoding ) ; <nl> - builder . Add ( keys [ i ] , handle_encoding , & handle_delta_encoding_slice ) ; <nl> - } <nl> - <nl> - / / read serialized contents of the block <nl> - Slice rawblock = builder . Finish ( ) ; <nl> - <nl> - / / create block reader <nl> - BlockContents contents ; <nl> - contents . data = rawblock ; <nl> - Block reader ( std : : move ( contents ) , kDisableGlobalSequenceNumber ) ; <nl> - <nl> - const bool kTotalOrderSeek = true ; <nl> - const bool kIncludesSeq = true ; <nl> - const bool kValueIsFull = ! kUseValueDeltaEncoding ; <nl> - IndexBlockIter * kNullIter = nullptr ; <nl> - Statistics * kNullStats = nullptr ; <nl> - / / read contents of block sequentially <nl> - int count = 0 ; <nl> - InternalIteratorBase < BlockHandle > * iter = reader . NewIterator < IndexBlockIter > ( <nl> - options . comparator , options . comparator , kNullIter , kNullStats , <nl> - kTotalOrderSeek , kIncludesSeq , kValueIsFull ) ; <nl> - for ( iter - > SeekToFirst ( ) ; iter - > Valid ( ) ; count + + , iter - > Next ( ) ) { <nl> - / / read kv from block <nl> - Slice k = iter - > key ( ) ; <nl> - BlockHandle handle = iter - > value ( ) ; <nl> - <nl> - / / compare with lookaside array <nl> - ASSERT_EQ ( k . ToString ( ) . compare ( keys [ count ] ) , 0 ) ; <nl> - <nl> - ASSERT_EQ ( values [ count ] . offset ( ) , handle . offset ( ) ) ; <nl> - ASSERT_EQ ( values [ count ] . size ( ) , handle . size ( ) ) ; <nl> - } <nl> - delete iter ; <nl> - <nl> - / / read block contents randomly <nl> - iter = reader . NewIterator < IndexBlockIter > ( <nl> - options . comparator , options . comparator , kNullIter , kNullStats , <nl> - kTotalOrderSeek , kIncludesSeq , kValueIsFull ) ; <nl> - for ( int i = 0 ; i < num_records ; i + + ) { <nl> - / / find a random key in the lookaside array <nl> - int index = rnd . Uniform ( num_records ) ; <nl> - Slice k ( keys [ index ] ) ; <nl> - <nl> - / / search in block for this key <nl> - iter - > Seek ( k ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - BlockHandle handle = iter - > value ( ) ; <nl> - ASSERT_EQ ( values [ index ] . offset ( ) , handle . offset ( ) ) ; <nl> - ASSERT_EQ ( values [ index ] . size ( ) , handle . size ( ) ) ; <nl> - } <nl> - delete iter ; <nl> - } <nl> / / return the block contents <nl> BlockContents GetBlockContents ( std : : unique_ptr < BlockBuilder > * builder , <nl> const std : : vector < std : : string > & keys , <nl> void CheckBlockContents ( BlockContents contents , const int max_key , <nl> NewFixedPrefixTransform ( prefix_size ) ) ; <nl> <nl> std : : unique_ptr < InternalIterator > regular_iter ( <nl> - reader2 . NewIterator < DataBlockIter > ( BytewiseComparator ( ) , <nl> - BytewiseComparator ( ) ) ) ; <nl> + reader2 . NewDataIterator ( BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> <nl> / / Seek existent keys <nl> for ( size_t i = 0 ; i < keys . size ( ) ; i + + ) { <nl> TEST_F ( BlockTest , BlockReadAmpBitmap ) { <nl> TEST_F ( BlockTest , BlockWithReadAmpBitmap ) { <nl> Random rnd ( 301 ) ; <nl> Options options = Options ( ) ; <nl> - std : : unique_ptr < InternalKeyComparator > ic ; <nl> - ic . reset ( new test : : PlainInternalKeyComparator ( options . comparator ) ) ; <nl> <nl> std : : vector < std : : string > keys ; <nl> std : : vector < std : : string > values ; <nl> TEST_F ( BlockTest , BlockWithReadAmpBitmap ) { <nl> <nl> / / read contents of block sequentially <nl> size_t read_bytes = 0 ; <nl> - DataBlockIter * iter = <nl> - static_cast < DataBlockIter * > ( reader . NewIterator < DataBlockIter > ( <nl> - options . comparator , options . comparator , nullptr , stats . get ( ) ) ) ; <nl> + DataBlockIter * iter = reader . NewDataIterator ( <nl> + options . comparator , options . comparator , nullptr , stats . get ( ) ) ; <nl> for ( iter - > SeekToFirst ( ) ; iter - > Valid ( ) ; iter - > Next ( ) ) { <nl> iter - > value ( ) ; <nl> read_bytes + = iter - > TEST_CurrentEntrySize ( ) ; <nl> TEST_F ( BlockTest , BlockWithReadAmpBitmap ) { <nl> kBytesPerBit , stats . get ( ) ) ; <nl> <nl> size_t read_bytes = 0 ; <nl> - DataBlockIter * iter = <nl> - static_cast < DataBlockIter * > ( reader . NewIterator < DataBlockIter > ( <nl> - options . comparator , options . comparator , nullptr , stats . get ( ) ) ) ; <nl> + DataBlockIter * iter = reader . NewDataIterator ( <nl> + options . comparator , options . comparator , nullptr , stats . get ( ) ) ; <nl> for ( int i = 0 ; i < num_records ; i + + ) { <nl> Slice k ( keys [ i ] ) ; <nl> <nl> TEST_F ( BlockTest , BlockWithReadAmpBitmap ) { <nl> kBytesPerBit , stats . get ( ) ) ; <nl> <nl> size_t read_bytes = 0 ; <nl> - DataBlockIter * iter = <nl> - static_cast < DataBlockIter * > ( reader . NewIterator < DataBlockIter > ( <nl> - options . comparator , options . comparator , nullptr , stats . get ( ) ) ) ; <nl> + DataBlockIter * iter = reader . NewDataIterator ( <nl> + options . comparator , options . comparator , nullptr , stats . get ( ) ) ; <nl> std : : unordered_set < int > read_keys ; <nl> for ( int i = 0 ; i < num_records ; i + + ) { <nl> int index = rnd . Uniform ( num_records ) ; <nl> TEST_F ( BlockTest , ReadAmpBitmapPow2 ) { <nl> ASSERT_EQ ( BlockReadAmpBitmap ( 100 , 35 , stats . get ( ) ) . GetBytesPerBit ( ) , 32 ) ; <nl> } <nl> <nl> + class IndexBlockTest <nl> + : public testing : : Test , <nl> + public testing : : WithParamInterface < std : : tuple < bool , bool > > { <nl> + public : <nl> + IndexBlockTest ( ) = default ; <nl> + <nl> + bool useValueDeltaEncoding ( ) const { return std : : get < 0 > ( GetParam ( ) ) ; } <nl> + bool includeFirstKey ( ) const { return std : : get < 1 > ( GetParam ( ) ) ; } <nl> + } ; <nl> + <nl> + / / Similar to GenerateRandomKVs but for index block contents . <nl> + void GenerateRandomIndexEntries ( std : : vector < std : : string > * separators , <nl> + std : : vector < BlockHandle > * block_handles , <nl> + std : : vector < std : : string > * first_keys , <nl> + const int len ) { <nl> + Random rnd ( 42 ) ; <nl> + <nl> + / / For each of ` len ` blocks , we need to generate a first and last key . <nl> + / / Let ' s generate n * 2 random keys , sort them , group into consecutive pairs . <nl> + std : : set < std : : string > keys ; <nl> + while ( ( int ) keys . size ( ) < len * 2 ) { <nl> + / / Keys need to be at least 8 bytes long to look like internal keys . <nl> + keys . insert ( test : : RandomKey ( & rnd , 12 ) ) ; <nl> + } <nl> + <nl> + uint64_t offset = 0 ; <nl> + for ( auto it = keys . begin ( ) ; it ! = keys . end ( ) ; ) { <nl> + first_keys - > emplace_back ( * it + + ) ; <nl> + separators - > emplace_back ( * it + + ) ; <nl> + uint64_t size = rnd . Uniform ( 1024 * 16 ) ; <nl> + BlockHandle handle ( offset , size ) ; <nl> + offset + = size + kBlockTrailerSize ; <nl> + block_handles - > emplace_back ( handle ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_P ( IndexBlockTest , IndexValueEncodingTest ) { <nl> + Random rnd ( 301 ) ; <nl> + Options options = Options ( ) ; <nl> + <nl> + std : : vector < std : : string > separators ; <nl> + std : : vector < BlockHandle > block_handles ; <nl> + std : : vector < std : : string > first_keys ; <nl> + const bool kUseDeltaEncoding = true ; <nl> + BlockBuilder builder ( 16 , kUseDeltaEncoding , useValueDeltaEncoding ( ) ) ; <nl> + int num_records = 100 ; <nl> + <nl> + GenerateRandomIndexEntries ( & separators , & block_handles , & first_keys , <nl> + num_records ) ; <nl> + BlockHandle last_encoded_handle ; <nl> + for ( int i = 0 ; i < num_records ; i + + ) { <nl> + IndexValue entry ( block_handles [ i ] , first_keys [ i ] ) ; <nl> + std : : string encoded_entry ; <nl> + std : : string delta_encoded_entry ; <nl> + entry . EncodeTo ( & encoded_entry , includeFirstKey ( ) , nullptr ) ; <nl> + if ( useValueDeltaEncoding ( ) & & i > 0 ) { <nl> + entry . EncodeTo ( & delta_encoded_entry , includeFirstKey ( ) , <nl> + & last_encoded_handle ) ; <nl> + } <nl> + last_encoded_handle = entry . handle ; <nl> + const Slice delta_encoded_entry_slice ( delta_encoded_entry ) ; <nl> + builder . Add ( separators [ i ] , encoded_entry , & delta_encoded_entry_slice ) ; <nl> + } <nl> + <nl> + / / read serialized contents of the block <nl> + Slice rawblock = builder . Finish ( ) ; <nl> + <nl> + / / create block reader <nl> + BlockContents contents ; <nl> + contents . data = rawblock ; <nl> + Block reader ( std : : move ( contents ) , kDisableGlobalSequenceNumber ) ; <nl> + <nl> + const bool kTotalOrderSeek = true ; <nl> + const bool kIncludesSeq = true ; <nl> + const bool kValueIsFull = ! useValueDeltaEncoding ( ) ; <nl> + IndexBlockIter * kNullIter = nullptr ; <nl> + Statistics * kNullStats = nullptr ; <nl> + / / read contents of block sequentially <nl> + InternalIteratorBase < IndexValue > * iter = reader . NewIndexIterator ( <nl> + options . comparator , options . comparator , kNullIter , kNullStats , <nl> + kTotalOrderSeek , includeFirstKey ( ) , kIncludesSeq , kValueIsFull ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + for ( int index = 0 ; index < num_records ; + + index ) { <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + <nl> + Slice k = iter - > key ( ) ; <nl> + IndexValue v = iter - > value ( ) ; <nl> + <nl> + EXPECT_EQ ( separators [ index ] , k . ToString ( ) ) ; <nl> + EXPECT_EQ ( block_handles [ index ] . offset ( ) , v . handle . offset ( ) ) ; <nl> + EXPECT_EQ ( block_handles [ index ] . size ( ) , v . handle . size ( ) ) ; <nl> + EXPECT_EQ ( includeFirstKey ( ) ? first_keys [ index ] : " " , <nl> + v . first_internal_key . ToString ( ) ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + } <nl> + delete iter ; <nl> + <nl> + / / read block contents randomly <nl> + iter = reader . NewIndexIterator ( options . comparator , options . comparator , <nl> + kNullIter , kNullStats , kTotalOrderSeek , <nl> + includeFirstKey ( ) , kIncludesSeq , kValueIsFull ) ; <nl> + for ( int i = 0 ; i < num_records * 2 ; i + + ) { <nl> + / / find a random key in the lookaside array <nl> + int index = rnd . Uniform ( num_records ) ; <nl> + Slice k ( separators [ index ] ) ; <nl> + <nl> + / / search in block for this key <nl> + iter - > Seek ( k ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + IndexValue v = iter - > value ( ) ; <nl> + EXPECT_EQ ( separators [ index ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( block_handles [ index ] . offset ( ) , v . handle . offset ( ) ) ; <nl> + EXPECT_EQ ( block_handles [ index ] . size ( ) , v . handle . size ( ) ) ; <nl> + EXPECT_EQ ( includeFirstKey ( ) ? first_keys [ index ] : " " , <nl> + v . first_internal_key . ToString ( ) ) ; <nl> + } <nl> + delete iter ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( P , IndexBlockTest , <nl> + : : testing : : Values ( std : : make_tuple ( false , false ) , <nl> + std : : make_tuple ( false , true ) , <nl> + std : : make_tuple ( true , false ) , <nl> + std : : make_tuple ( true , true ) ) ) ; <nl> + <nl> } / / namespace rocksdb <nl> <nl> int main ( int argc , char * * argv ) { <nl> mmm a / table / block_based / data_block_hash_index_test . cc <nl> ppp b / table / block_based / data_block_hash_index_test . cc <nl> TEST ( DataBlockHashIndex , BlockTestSingleKey ) { <nl> Block reader ( std : : move ( contents ) , kDisableGlobalSequenceNumber ) ; <nl> <nl> const InternalKeyComparator icmp ( BytewiseComparator ( ) ) ; <nl> - auto iter = reader . NewIterator < DataBlockIter > ( & icmp , icmp . user_comparator ( ) ) ; <nl> + auto iter = reader . NewDataIterator ( & icmp , icmp . user_comparator ( ) ) ; <nl> bool may_exist ; <nl> / / search in block for the key just inserted <nl> { <nl> TEST ( DataBlockHashIndex , BlockTestLarge ) { <nl> <nl> / / random seek existent keys <nl> for ( int i = 0 ; i < num_records ; i + + ) { <nl> - auto iter = <nl> - reader . NewIterator < DataBlockIter > ( & icmp , icmp . user_comparator ( ) ) ; <nl> + auto iter = reader . NewDataIterator ( & icmp , icmp . user_comparator ( ) ) ; <nl> / / find a random key in the lookaside array <nl> int index = rnd . Uniform ( num_records ) ; <nl> std : : string ukey ( keys [ index ] + " 1 " / * existing key marker * / ) ; <nl> TEST ( DataBlockHashIndex , BlockTestLarge ) { <nl> / / C true false <nl> <nl> for ( int i = 0 ; i < num_records ; i + + ) { <nl> - auto iter = <nl> - reader . NewIterator < DataBlockIter > ( & icmp , icmp . user_comparator ( ) ) ; <nl> + auto iter = reader . NewDataIterator ( & icmp , icmp . user_comparator ( ) ) ; <nl> / / find a random key in the lookaside array <nl> int index = rnd . Uniform ( num_records ) ; <nl> std : : string ukey ( keys [ index ] + " 0 " / * non - existing key marker * / ) ; <nl> mmm a / table / block_based / index_builder . cc <nl> ppp b / table / block_based / index_builder . cc <nl> IndexBuilder * IndexBuilder : : CreateIndexBuilder ( <nl> result = new ShortenedIndexBuilder ( <nl> comparator , table_opt . index_block_restart_interval , <nl> table_opt . format_version , use_value_delta_encoding , <nl> - table_opt . index_shortening ) ; <nl> + table_opt . index_shortening , / * include_first_key * / false ) ; <nl> } break ; <nl> case BlockBasedTableOptions : : kHashSearch : { <nl> result = new HashIndexBuilder ( <nl> IndexBuilder * IndexBuilder : : CreateIndexBuilder ( <nl> result = PartitionedIndexBuilder : : CreateIndexBuilder ( <nl> comparator , use_value_delta_encoding , table_opt ) ; <nl> } break ; <nl> + case BlockBasedTableOptions : : kBinarySearchWithFirstKey : { <nl> + result = new ShortenedIndexBuilder ( <nl> + comparator , table_opt . index_block_restart_interval , <nl> + table_opt . format_version , use_value_delta_encoding , <nl> + table_opt . index_shortening , / * include_first_key * / true ) ; <nl> + } break ; <nl> default : { <nl> assert ( ! " Do not recognize the index type " ) ; <nl> } break ; <nl> void PartitionedIndexBuilder : : MakeNewSubIndexBuilder ( ) { <nl> sub_index_builder_ = new ShortenedIndexBuilder ( <nl> comparator_ , table_opt_ . index_block_restart_interval , <nl> table_opt_ . format_version , use_value_delta_encoding_ , <nl> - table_opt_ . index_shortening ) ; <nl> + table_opt_ . index_shortening , / * include_first_key * / false ) ; <nl> flush_policy_ . reset ( FlushBlockBySizePolicyFactory : : NewFlushBlockPolicy ( <nl> table_opt_ . metadata_block_size , table_opt_ . block_size_deviation , <nl> / / Note : this is sub - optimal since sub_index_builder_ could later reset <nl> mmm a / table / block_based / index_builder . h <nl> ppp b / table / block_based / index_builder . h <nl> class IndexBuilder { <nl> / / To allow further optimization , we provide ` last_key_in_current_block ` and <nl> / / ` first_key_in_next_block ` , based on which the specific implementation can <nl> / / determine the best index key to be used for the index block . <nl> + / / Called before the OnKeyAdded ( ) call for first_key_in_next_block . <nl> / / @ last_key_in_current_block : this parameter maybe overridden with the value <nl> / / " substitute key " . <nl> / / @ first_key_in_next_block : it will be nullptr if the entry being added is <nl> class ShortenedIndexBuilder : public IndexBuilder { <nl> const InternalKeyComparator * comparator , <nl> const int index_block_restart_interval , const uint32_t format_version , <nl> const bool use_value_delta_encoding , <nl> - BlockBasedTableOptions : : IndexShorteningMode shortening_mode ) <nl> + BlockBasedTableOptions : : IndexShorteningMode shortening_mode , <nl> + bool include_first_key ) <nl> : IndexBuilder ( comparator ) , <nl> index_block_builder_ ( index_block_restart_interval , <nl> true / * use_delta_encoding * / , <nl> class ShortenedIndexBuilder : public IndexBuilder { <nl> index_block_builder_without_seq_ ( index_block_restart_interval , <nl> true / * use_delta_encoding * / , <nl> use_value_delta_encoding ) , <nl> + use_value_delta_encoding_ ( use_value_delta_encoding ) , <nl> + include_first_key_ ( include_first_key ) , <nl> shortening_mode_ ( shortening_mode ) { <nl> / / Making the default true will disable the feature for old versions <nl> seperator_is_key_plus_seq_ = ( format_version < = 2 ) ; <nl> } <nl> <nl> + virtual void OnKeyAdded ( const Slice & key ) override { <nl> + if ( include_first_key_ & & current_block_first_internal_key_ . empty ( ) ) { <nl> + current_block_first_internal_key_ . assign ( key . data ( ) , key . size ( ) ) ; <nl> + } <nl> + } <nl> + <nl> virtual void AddIndexEntry ( std : : string * last_key_in_current_block , <nl> const Slice * first_key_in_next_block , <nl> const BlockHandle & block_handle ) override { <nl> class ShortenedIndexBuilder : public IndexBuilder { <nl> } <nl> auto sep = Slice ( * last_key_in_current_block ) ; <nl> <nl> - std : : string handle_encoding ; <nl> - block_handle . EncodeTo ( & handle_encoding ) ; <nl> - std : : string handle_delta_encoding ; <nl> - PutVarsignedint64 ( & handle_delta_encoding , <nl> - block_handle . size ( ) - last_encoded_handle_ . size ( ) ) ; <nl> - assert ( handle_delta_encoding . size ( ) ! = 0 ) ; <nl> + assert ( ! include_first_key_ | | ! current_block_first_internal_key_ . empty ( ) ) ; <nl> + IndexValue entry ( block_handle , current_block_first_internal_key_ ) ; <nl> + std : : string encoded_entry ; <nl> + std : : string delta_encoded_entry ; <nl> + entry . EncodeTo ( & encoded_entry , include_first_key_ , nullptr ) ; <nl> + if ( use_value_delta_encoding_ & & ! last_encoded_handle_ . IsNull ( ) ) { <nl> + entry . EncodeTo ( & delta_encoded_entry , include_first_key_ , <nl> + & last_encoded_handle_ ) ; <nl> + } else { <nl> + / / If it ' s the first block , or delta encoding is disabled , <nl> + / / BlockBuilder : : Add ( ) below won ' t use delta - encoded slice . <nl> + } <nl> last_encoded_handle_ = block_handle ; <nl> - const Slice handle_delta_encoding_slice ( handle_delta_encoding ) ; <nl> - index_block_builder_ . Add ( sep , handle_encoding , <nl> - & handle_delta_encoding_slice ) ; <nl> + const Slice delta_encoded_entry_slice ( delta_encoded_entry ) ; <nl> + index_block_builder_ . Add ( sep , encoded_entry , & delta_encoded_entry_slice ) ; <nl> if ( ! seperator_is_key_plus_seq_ ) { <nl> - index_block_builder_without_seq_ . Add ( ExtractUserKey ( sep ) , handle_encoding , <nl> - & handle_delta_encoding_slice ) ; <nl> + index_block_builder_without_seq_ . Add ( ExtractUserKey ( sep ) , encoded_entry , <nl> + & delta_encoded_entry_slice ) ; <nl> } <nl> + <nl> + current_block_first_internal_key_ . clear ( ) ; <nl> } <nl> <nl> using IndexBuilder : : Finish ; <nl> class ShortenedIndexBuilder : public IndexBuilder { <nl> private : <nl> BlockBuilder index_block_builder_ ; <nl> BlockBuilder index_block_builder_without_seq_ ; <nl> + const bool use_value_delta_encoding_ ; <nl> bool seperator_is_key_plus_seq_ ; <nl> + const bool include_first_key_ ; <nl> BlockBasedTableOptions : : IndexShorteningMode shortening_mode_ ; <nl> - BlockHandle last_encoded_handle_ ; <nl> + BlockHandle last_encoded_handle_ = BlockHandle : : NullBlockHandle ( ) ; <nl> + std : : string current_block_first_internal_key_ ; <nl> } ; <nl> <nl> / / HashIndexBuilder contains a binary - searchable primary index and the <nl> class HashIndexBuilder : public IndexBuilder { <nl> : IndexBuilder ( comparator ) , <nl> primary_index_builder_ ( comparator , index_block_restart_interval , <nl> format_version , use_value_delta_encoding , <nl> - shortening_mode ) , <nl> + shortening_mode , / * include_first_key * / false ) , <nl> hash_key_extractor_ ( hash_key_extractor ) { } <nl> <nl> virtual void AddIndexEntry ( std : : string * last_key_in_current_block , <nl> mmm a / table / block_based / partitioned_filter_block . cc <nl> ppp b / table / block_based / partitioned_filter_block . cc <nl> PartitionedFilterBlockReader : : ~ PartitionedFilterBlockReader ( ) { <nl> IndexBlockIter biter ; <nl> BlockHandle handle ; <nl> Statistics * kNullStats = nullptr ; <nl> - idx_on_fltr_blk_ - > NewIterator < IndexBlockIter > ( <nl> + idx_on_fltr_blk_ - > NewIndexIterator ( <nl> & comparator_ , comparator_ . user_comparator ( ) , & biter , kNullStats , true , <nl> - index_key_includes_seq_ , index_value_is_full_ ) ; <nl> + / * have_first_key * / false , index_key_includes_seq_ , <nl> + index_value_is_full_ ) ; <nl> biter . SeekToFirst ( ) ; <nl> for ( ; biter . Valid ( ) ; biter . Next ( ) ) { <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> auto key = BlockBasedTable : : GetCacheKey ( table_ - > rep_ - > cache_key_prefix , <nl> table_ - > rep_ - > cache_key_prefix_size , <nl> handle , cache_key ) ; <nl> BlockHandle PartitionedFilterBlockReader : : GetFilterPartitionHandle ( <nl> const Slice & entry ) { <nl> IndexBlockIter iter ; <nl> Statistics * kNullStats = nullptr ; <nl> - idx_on_fltr_blk_ - > NewIterator < IndexBlockIter > ( <nl> + idx_on_fltr_blk_ - > NewIndexIterator ( <nl> & comparator_ , comparator_ . user_comparator ( ) , & iter , kNullStats , true , <nl> - index_key_includes_seq_ , index_value_is_full_ ) ; <nl> + / * have_first_key * / false , index_key_includes_seq_ , <nl> + index_value_is_full_ ) ; <nl> iter . Seek ( entry ) ; <nl> if ( UNLIKELY ( ! iter . Valid ( ) ) ) { <nl> return BlockHandle ( 0 , 0 ) ; <nl> } <nl> assert ( iter . Valid ( ) ) ; <nl> - BlockHandle fltr_blk_handle = iter . value ( ) ; <nl> + BlockHandle fltr_blk_handle = iter . value ( ) . handle ; <nl> return fltr_blk_handle ; <nl> } <nl> <nl> void PartitionedFilterBlockReader : : CacheDependencies ( <nl> BlockCacheLookupContext lookup_context { TableReaderCaller : : kPrefetch } ; <nl> IndexBlockIter biter ; <nl> Statistics * kNullStats = nullptr ; <nl> - idx_on_fltr_blk_ - > NewIterator < IndexBlockIter > ( <nl> + idx_on_fltr_blk_ - > NewIndexIterator ( <nl> & comparator_ , comparator_ . user_comparator ( ) , & biter , kNullStats , true , <nl> - index_key_includes_seq_ , index_value_is_full_ ) ; <nl> + / * have_first_key * / false , index_key_includes_seq_ , <nl> + index_value_is_full_ ) ; <nl> / / Index partitions are assumed to be consecuitive . Prefetch them all . <nl> / / Read the first block offset <nl> biter . SeekToFirst ( ) ; <nl> - BlockHandle handle = biter . value ( ) ; <nl> + BlockHandle handle = biter . value ( ) . handle ; <nl> uint64_t prefetch_off = handle . offset ( ) ; <nl> <nl> / / Read the last block ' s offset <nl> biter . SeekToLast ( ) ; <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> uint64_t last_off = handle . offset ( ) + handle . size ( ) + kBlockTrailerSize ; <nl> uint64_t prefetch_len = last_off - prefetch_off ; <nl> std : : unique_ptr < FilePrefetchBuffer > prefetch_buffer ; <nl> void PartitionedFilterBlockReader : : CacheDependencies ( <nl> / / After prefetch , read the partitions one by one <nl> biter . SeekToFirst ( ) ; <nl> for ( ; biter . Valid ( ) ; biter . Next ( ) ) { <nl> - handle = biter . value ( ) ; <nl> + handle = biter . value ( ) . handle ; <nl> const bool no_io = true ; <nl> const bool is_a_filter_partition = true ; <nl> auto filter = table_ - > GetFilter ( <nl> mmm a / table / block_fetcher . cc <nl> ppp b / table / block_fetcher . cc <nl> <nl> # include " logging / logging . h " <nl> # include " memory / memory_allocator . h " <nl> # include " monitoring / perf_context_imp . h " <nl> - # include " monitoring / statistics . h " <nl> # include " rocksdb / env . h " <nl> # include " table / block_based / block . h " <nl> # include " table / block_based / block_based_table_reader . h " <nl> mmm a / table / format . cc <nl> ppp b / table / format . cc <nl> std : : string BlockHandle : : ToString ( bool hex ) const { <nl> <nl> const BlockHandle BlockHandle : : kNullBlockHandle ( 0 , 0 ) ; <nl> <nl> + void IndexValue : : EncodeTo ( std : : string * dst , bool have_first_key , <nl> + const BlockHandle * previous_handle ) const { <nl> + if ( previous_handle ) { <nl> + assert ( handle . offset ( ) = = previous_handle - > offset ( ) + <nl> + previous_handle - > size ( ) + kBlockTrailerSize ) ; <nl> + PutVarsignedint64 ( dst , handle . size ( ) - previous_handle - > size ( ) ) ; <nl> + } else { <nl> + handle . EncodeTo ( dst ) ; <nl> + } <nl> + assert ( dst - > size ( ) ! = 0 ) ; <nl> + <nl> + if ( have_first_key ) { <nl> + PutLengthPrefixedSlice ( dst , first_internal_key ) ; <nl> + } <nl> + } <nl> + <nl> + Status IndexValue : : DecodeFrom ( Slice * input , bool have_first_key , <nl> + const BlockHandle * previous_handle ) { <nl> + if ( previous_handle ) { <nl> + int64_t delta ; <nl> + if ( ! GetVarsignedint64 ( input , & delta ) ) { <nl> + return Status : : Corruption ( " bad delta - encoded index value " ) ; <nl> + } <nl> + handle = BlockHandle ( <nl> + previous_handle - > offset ( ) + previous_handle - > size ( ) + kBlockTrailerSize , <nl> + previous_handle - > size ( ) + delta ) ; <nl> + } else { <nl> + Status s = handle . DecodeFrom ( input ) ; <nl> + if ( ! s . ok ( ) ) { <nl> + return s ; <nl> + } <nl> + } <nl> + <nl> + if ( ! have_first_key ) { <nl> + first_internal_key = Slice ( ) ; <nl> + } else if ( ! GetLengthPrefixedSlice ( input , & first_internal_key ) ) { <nl> + return Status : : Corruption ( " bad first key in block info " ) ; <nl> + } <nl> + <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> + std : : string IndexValue : : ToString ( bool hex , bool have_first_key ) const { <nl> + std : : string s ; <nl> + EncodeTo ( & s , have_first_key , nullptr ) ; <nl> + if ( hex ) { <nl> + return Slice ( s ) . ToString ( true ) ; <nl> + } else { <nl> + return s ; <nl> + } <nl> + } <nl> + <nl> namespace { <nl> inline bool IsLegacyFooterFormat ( uint64_t magic_number ) { <nl> return magic_number = = kLegacyBlockBasedTableMagicNumber | | <nl> mmm a / table / format . h <nl> ppp b / table / format . h <nl> class BlockHandle { <nl> static const BlockHandle kNullBlockHandle ; <nl> } ; <nl> <nl> + / / Value in block - based table file index . <nl> + / / <nl> + / / The index entry for block n is : y - > h , [ x ] , <nl> + / / where : y is some key between the last key of block n ( inclusive ) and the <nl> + / / first key of block n + 1 ( exclusive ) ; h is BlockHandle pointing to block n ; <nl> + / / x , if present , is the first key of block n ( unshortened ) . <nl> + / / This struct represents the " h , [ x ] " part . <nl> + struct IndexValue { <nl> + BlockHandle handle ; <nl> + / / Empty means unknown . <nl> + Slice first_internal_key ; <nl> + <nl> + IndexValue ( ) = default ; <nl> + IndexValue ( BlockHandle _handle , Slice _first_internal_key ) <nl> + : handle ( _handle ) , first_internal_key ( _first_internal_key ) { } <nl> + <nl> + / / have_first_key indicates whether the ` first_internal_key ` is used . <nl> + / / If previous_handle is not null , delta encoding is used ; <nl> + / / in this case , the two handles must point to consecutive blocks : <nl> + / / handle . offset ( ) = = <nl> + / / previous_handle - > offset ( ) + previous_handle - > size ( ) + kBlockTrailerSize <nl> + void EncodeTo ( std : : string * dst , bool have_first_key , <nl> + const BlockHandle * previous_handle ) const ; <nl> + Status DecodeFrom ( Slice * input , bool have_first_key , <nl> + const BlockHandle * previous_handle ) ; <nl> + <nl> + std : : string ToString ( bool hex , bool have_first_key ) const ; <nl> + } ; <nl> + <nl> inline uint32_t GetCompressFormatForVersion ( CompressionType compression_type , <nl> uint32_t version ) { <nl> # ifdef NDEBUG <nl> mmm a / table / internal_iterator . h <nl> ppp b / table / internal_iterator . h <nl> class InternalIteratorBase : public Cleanable { <nl> / / satisfied without doing some IO , then this returns Status : : Incomplete ( ) . <nl> virtual Status status ( ) const = 0 ; <nl> <nl> - / / True if the iterator is invalidated because it is out of the iterator <nl> - / / upper bound <nl> + / / True if the iterator is invalidated because it reached a key that is above <nl> + / / the iterator upper bound . Used by LevelIterator to decide whether it should <nl> + / / stop or move on to the next file . <nl> + / / Important : if iterator reached the end of the file without encountering any <nl> + / / keys above the upper bound , IsOutOfBound ( ) must return false . <nl> virtual bool IsOutOfBound ( ) { return false ; } <nl> <nl> / / Pass the PinnedIteratorsManager to the Iterator , most Iterators dont <nl> mmm a / table / iterator . cc <nl> ppp b / table / iterator . cc <nl> template < class TValue > <nl> InternalIteratorBase < TValue > * NewErrorInternalIterator ( const Status & status ) { <nl> return new EmptyInternalIterator < TValue > ( status ) ; <nl> } <nl> - template InternalIteratorBase < BlockHandle > * NewErrorInternalIterator ( <nl> + template InternalIteratorBase < IndexValue > * NewErrorInternalIterator ( <nl> const Status & status ) ; <nl> template InternalIteratorBase < Slice > * NewErrorInternalIterator ( <nl> const Status & status ) ; <nl> InternalIteratorBase < TValue > * NewErrorInternalIterator ( const Status & status , <nl> return new ( mem ) EmptyInternalIterator < TValue > ( status ) ; <nl> } <nl> } <nl> - template InternalIteratorBase < BlockHandle > * NewErrorInternalIterator ( <nl> + template InternalIteratorBase < IndexValue > * NewErrorInternalIterator ( <nl> const Status & status , Arena * arena ) ; <nl> template InternalIteratorBase < Slice > * NewErrorInternalIterator ( <nl> const Status & status , Arena * arena ) ; <nl> template < class TValue > <nl> InternalIteratorBase < TValue > * NewEmptyInternalIterator ( ) { <nl> return new EmptyInternalIterator < TValue > ( Status : : OK ( ) ) ; <nl> } <nl> - template InternalIteratorBase < BlockHandle > * NewEmptyInternalIterator ( ) ; <nl> + template InternalIteratorBase < IndexValue > * NewEmptyInternalIterator ( ) ; <nl> template InternalIteratorBase < Slice > * NewEmptyInternalIterator ( ) ; <nl> <nl> template < class TValue > <nl> InternalIteratorBase < TValue > * NewEmptyInternalIterator ( Arena * arena ) { <nl> return new ( mem ) EmptyInternalIterator < TValue > ( Status : : OK ( ) ) ; <nl> } <nl> } <nl> - template InternalIteratorBase < BlockHandle > * NewEmptyInternalIterator ( <nl> + template InternalIteratorBase < IndexValue > * NewEmptyInternalIterator ( <nl> Arena * arena ) ; <nl> template InternalIteratorBase < Slice > * NewEmptyInternalIterator ( Arena * arena ) ; <nl> <nl> mmm a / table / meta_blocks . cc <nl> ppp b / table / meta_blocks . cc <nl> Status ReadProperties ( const Slice & handle_value , RandomAccessFileReader * file , <nl> Block properties_block ( std : : move ( block_contents ) , <nl> kDisableGlobalSequenceNumber ) ; <nl> DataBlockIter iter ; <nl> - properties_block . NewIterator < DataBlockIter > ( BytewiseComparator ( ) , <nl> - BytewiseComparator ( ) , & iter ) ; <nl> + properties_block . NewDataIterator ( BytewiseComparator ( ) , BytewiseComparator ( ) , <nl> + & iter ) ; <nl> <nl> auto new_table_properties = new TableProperties ( ) ; <nl> / / All pre - defined properties of type uint64_t <nl> Status ReadTableProperties ( RandomAccessFileReader * file , uint64_t file_size , <nl> / / are to compress it . <nl> Block metaindex_block ( std : : move ( metaindex_contents ) , <nl> kDisableGlobalSequenceNumber ) ; <nl> - std : : unique_ptr < InternalIterator > meta_iter ( <nl> - metaindex_block . NewIterator < DataBlockIter > ( BytewiseComparator ( ) , <nl> - BytewiseComparator ( ) ) ) ; <nl> + std : : unique_ptr < InternalIterator > meta_iter ( metaindex_block . NewDataIterator ( <nl> + BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> <nl> / / - - Read property block <nl> bool found_properties_block = true ; <nl> Status FindMetaBlock ( RandomAccessFileReader * file , uint64_t file_size , <nl> kDisableGlobalSequenceNumber ) ; <nl> <nl> std : : unique_ptr < InternalIterator > meta_iter ; <nl> - meta_iter . reset ( metaindex_block . NewIterator < DataBlockIter > ( <nl> - BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> + meta_iter . reset ( metaindex_block . NewDataIterator ( BytewiseComparator ( ) , <nl> + BytewiseComparator ( ) ) ) ; <nl> <nl> return FindMetaBlock ( meta_iter . get ( ) , meta_block_name , block_handle ) ; <nl> } <nl> Status ReadMetaBlock ( RandomAccessFileReader * file , <nl> kDisableGlobalSequenceNumber ) ; <nl> <nl> std : : unique_ptr < InternalIterator > meta_iter ; <nl> - meta_iter . reset ( metaindex_block . NewIterator < DataBlockIter > ( <nl> - BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> + meta_iter . reset ( metaindex_block . NewDataIterator ( BytewiseComparator ( ) , <nl> + BytewiseComparator ( ) ) ) ; <nl> <nl> BlockHandle block_handle ; <nl> status = FindMetaBlock ( meta_iter . get ( ) , meta_block_name , & block_handle ) ; <nl> mmm a / table / table_test . cc <nl> ppp b / table / table_test . cc <nl> class BlockConstructor : public Constructor { <nl> } <nl> InternalIterator * NewIterator ( <nl> const SliceTransform * / * prefix_extractor * / ) const override { <nl> - return block_ - > NewIterator < DataBlockIter > ( comparator_ , comparator_ ) ; <nl> + return block_ - > NewDataIterator ( comparator_ , comparator_ ) ; <nl> } <nl> <nl> private : <nl> class TableConstructor : public Constructor { <nl> public : <nl> explicit TableConstructor ( const Comparator * cmp , <nl> bool convert_to_internal_key = false , <nl> - int level = - 1 ) <nl> + int level = - 1 , SequenceNumber largest_seqno = 0 ) <nl> : Constructor ( cmp ) , <nl> + largest_seqno_ ( largest_seqno ) , <nl> convert_to_internal_key_ ( convert_to_internal_key ) , <nl> level_ ( level ) { } <nl> ~ TableConstructor ( ) override { Reset ( ) ; } <nl> class TableConstructor : public Constructor { <nl> std : : unique_ptr < TableBuilder > builder ; <nl> std : : vector < std : : unique_ptr < IntTblPropCollectorFactory > > <nl> int_tbl_prop_collector_factories ; <nl> + <nl> + if ( largest_seqno_ ! = 0 ) { <nl> + / / Pretend that it ' s an external file written by SstFileWriter . <nl> + int_tbl_prop_collector_factories . emplace_back ( <nl> + new SstFileWriterPropertiesCollectorFactory ( 2 / * version * / , <nl> + 0 / * global_seqno * / ) ) ; <nl> + } <nl> + <nl> std : : string column_family_name ; <nl> builder . reset ( ioptions . table_factory - > NewTableBuilder ( <nl> TableBuilderOptions ( ioptions , moptions , internal_comparator , <nl> class TableConstructor : public Constructor { <nl> return ioptions . table_factory - > NewTableReader ( <nl> TableReaderOptions ( ioptions , moptions . prefix_extractor . get ( ) , soptions , <nl> internal_comparator , ! kSkipFilters , ! kImmortal , <nl> - level_ ) , <nl> + level_ , largest_seqno_ , nullptr ) , <nl> std : : move ( file_reader_ ) , TEST_GetSink ( ) - > contents ( ) . size ( ) , <nl> & table_reader_ ) ; <nl> } <nl> class TableConstructor : public Constructor { <nl> std : : unique_ptr < WritableFileWriter > file_writer_ ; <nl> std : : unique_ptr < RandomAccessFileReader > file_reader_ ; <nl> std : : unique_ptr < TableReader > table_reader_ ; <nl> + SequenceNumber largest_seqno_ ; <nl> bool convert_to_internal_key_ ; <nl> int level_ ; <nl> <nl> TEST_P ( BlockBasedTableTest , PrefetchTest ) { <nl> <nl> TEST_P ( BlockBasedTableTest , TotalOrderSeekOnHashIndex ) { <nl> BlockBasedTableOptions table_options = GetBlockBasedTableOptions ( ) ; <nl> - for ( int i = 0 ; i < 4 ; + + i ) { <nl> + for ( int i = 0 ; i < = 5 ; + + i ) { <nl> Options options ; <nl> / / Make each key / value an individual block <nl> table_options . block_size = 64 ; <nl> TEST_P ( BlockBasedTableTest , TotalOrderSeekOnHashIndex ) { <nl> options . prefix_extractor . reset ( NewFixedPrefixTransform ( 4 ) ) ; <nl> break ; <nl> case 4 : <nl> - default : <nl> - / / Binary search index <nl> + / / Two - level index <nl> table_options . index_type = BlockBasedTableOptions : : kTwoLevelIndexSearch ; <nl> options . table_factory . reset ( new BlockBasedTableFactory ( table_options ) ) ; <nl> break ; <nl> + case 5 : <nl> + / / Binary search with first key <nl> + table_options . index_type = <nl> + BlockBasedTableOptions : : kBinarySearchWithFirstKey ; <nl> + options . table_factory . reset ( new BlockBasedTableFactory ( table_options ) ) ; <nl> + break ; <nl> } <nl> <nl> TableConstructor c ( BytewiseComparator ( ) , <nl> static std : : string RandomString ( Random * rnd , int len ) { <nl> } <nl> <nl> void AddInternalKey ( TableConstructor * c , const std : : string & prefix , <nl> - int / * suffix_len * / = 800 ) { <nl> + std : : string value = " v " , int / * suffix_len * / = 800 ) { <nl> static Random rnd ( 1023 ) ; <nl> InternalKey k ( prefix + RandomString ( & rnd , 800 ) , 0 , kTypeValue ) ; <nl> - c - > Add ( k . Encode ( ) . ToString ( ) , " v " ) ; <nl> + c - > Add ( k . Encode ( ) . ToString ( ) , value ) ; <nl> } <nl> <nl> void TableTest : : IndexTest ( BlockBasedTableOptions table_options ) { <nl> TEST_P ( BlockBasedTableTest , IndexSeekOptimizationIncomplete ) { <nl> ASSERT_TRUE ( iter - > status ( ) . IsIncomplete ( ) ) ; <nl> } <nl> <nl> + TEST_P ( BlockBasedTableTest , BinaryIndexWithFirstKey1 ) { <nl> + BlockBasedTableOptions table_options = GetBlockBasedTableOptions ( ) ; <nl> + table_options . index_type = BlockBasedTableOptions : : kBinarySearchWithFirstKey ; <nl> + IndexTest ( table_options ) ; <nl> + } <nl> + <nl> + class CustomFlushBlockPolicy : public FlushBlockPolicyFactory , <nl> + public FlushBlockPolicy { <nl> + public : <nl> + explicit CustomFlushBlockPolicy ( std : : vector < int > keys_per_block ) <nl> + : keys_per_block_ ( keys_per_block ) { } <nl> + <nl> + const char * Name ( ) const override { return " table_test " ; } <nl> + FlushBlockPolicy * NewFlushBlockPolicy ( const BlockBasedTableOptions & , <nl> + const BlockBuilder & ) const override { <nl> + return new CustomFlushBlockPolicy ( keys_per_block_ ) ; <nl> + } <nl> + <nl> + bool Update ( const Slice & , const Slice & ) override { <nl> + if ( keys_in_current_block_ > = keys_per_block_ . at ( current_block_idx_ ) ) { <nl> + + + current_block_idx_ ; <nl> + keys_in_current_block_ = 1 ; <nl> + return true ; <nl> + } <nl> + <nl> + + + keys_in_current_block_ ; <nl> + return false ; <nl> + } <nl> + <nl> + std : : vector < int > keys_per_block_ ; <nl> + <nl> + int current_block_idx_ = 0 ; <nl> + int keys_in_current_block_ = 0 ; <nl> + } ; <nl> + <nl> + TEST_P ( BlockBasedTableTest , BinaryIndexWithFirstKey2 ) { <nl> + for ( int use_first_key = 0 ; use_first_key < 2 ; + + use_first_key ) { <nl> + SCOPED_TRACE ( " use_first_key = " + std : : to_string ( use_first_key ) ) ; <nl> + BlockBasedTableOptions table_options = GetBlockBasedTableOptions ( ) ; <nl> + table_options . index_type = <nl> + use_first_key ? BlockBasedTableOptions : : kBinarySearchWithFirstKey <nl> + : BlockBasedTableOptions : : kBinarySearch ; <nl> + table_options . block_cache = NewLRUCache ( 10000 ) ; / / fits all blocks <nl> + table_options . index_shortening = <nl> + BlockBasedTableOptions : : IndexShorteningMode : : kNoShortening ; <nl> + table_options . flush_block_policy_factory = <nl> + std : : make_shared < CustomFlushBlockPolicy > ( std : : vector < int > { 2 , 1 , 3 , 2 } ) ; <nl> + Options options ; <nl> + options . table_factory . reset ( NewBlockBasedTableFactory ( table_options ) ) ; <nl> + options . statistics = CreateDBStatistics ( ) ; <nl> + Statistics * stats = options . statistics . get ( ) ; <nl> + std : : unique_ptr < InternalKeyComparator > comparator ( <nl> + new InternalKeyComparator ( BytewiseComparator ( ) ) ) ; <nl> + const ImmutableCFOptions ioptions ( options ) ; <nl> + const MutableCFOptions moptions ( options ) ; <nl> + <nl> + TableConstructor c ( BytewiseComparator ( ) ) ; <nl> + <nl> + / / Block 0 . <nl> + AddInternalKey ( & c , " aaaa " , " v0 " ) ; <nl> + AddInternalKey ( & c , " aaac " , " v1 " ) ; <nl> + <nl> + / / Block 1 . <nl> + AddInternalKey ( & c , " aaca " , " v2 " ) ; <nl> + <nl> + / / Block 2 . <nl> + AddInternalKey ( & c , " caaa " , " v3 " ) ; <nl> + AddInternalKey ( & c , " caac " , " v4 " ) ; <nl> + AddInternalKey ( & c , " caae " , " v5 " ) ; <nl> + <nl> + / / Block 3 . <nl> + AddInternalKey ( & c , " ccaa " , " v6 " ) ; <nl> + AddInternalKey ( & c , " ccac " , " v7 " ) ; <nl> + <nl> + / / Write the file . <nl> + std : : vector < std : : string > keys ; <nl> + stl_wrappers : : KVMap kvmap ; <nl> + c . Finish ( options , ioptions , moptions , table_options , * comparator , & keys , <nl> + & kvmap ) ; <nl> + ASSERT_EQ ( 8 , keys . size ( ) ) ; <nl> + <nl> + auto reader = c . GetTableReader ( ) ; <nl> + auto props = reader - > GetTableProperties ( ) ; <nl> + ASSERT_EQ ( 4u , props - > num_data_blocks ) ; <nl> + std : : unique_ptr < InternalIterator > iter ( reader - > NewIterator ( <nl> + ReadOptions ( ) , / * prefix_extractor = * / nullptr , / * arena = * / nullptr , <nl> + / * skip_filters = * / false , TableReaderCaller : : kUncategorized ) ) ; <nl> + <nl> + / / Shouldn ' t have read data blocks before iterator is seeked . <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + auto ikey = [ ] ( Slice user_key ) { <nl> + return InternalKey ( user_key , 0 , kTypeValue ) . Encode ( ) . ToString ( ) ; <nl> + } ; <nl> + <nl> + / / Seek to a key between blocks . If index contains first key , we shouldn ' t <nl> + / / read any data blocks until value is requested . <nl> + iter - > Seek ( ikey ( " aaba " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 2 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 0 : 1 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( " v2 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 1 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Seek to the middle of a block . The block should be read right away . <nl> + iter - > Seek ( ikey ( " caab " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 4 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 2 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( " v4 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Seek to just before the same block and don ' t access value . <nl> + / / The iterator should keep pinning the block contents . <nl> + iter - > Seek ( ikey ( " baaa " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 3 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Seek to the same block again to check that the block is still pinned . <nl> + iter - > Seek ( ikey ( " caae " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 5 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( " v5 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 2 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Step forward and fall through to the next block . Don ' t access value . <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 6 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 3 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Step forward again . Block should be read . <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 7 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 3 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( " v7 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Step forward and reach the end . <nl> + iter - > Next ( ) ; <nl> + EXPECT_FALSE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( 3 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Seek to a single - key block and step forward without accessing value . <nl> + iter - > Seek ( ikey ( " aaca " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 2 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 0 : 1 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 3 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 1 : 2 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( " v3 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 2 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 3 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + / / Seek between blocks and step back without accessing value . <nl> + iter - > Seek ( ikey ( " aaca " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 2 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 3 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( 3 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + iter - > Prev ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 1 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 3 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + / / All blocks are in cache now , there ' ll be no more misses ever . <nl> + EXPECT_EQ ( 4 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( " v1 " , iter - > value ( ) . ToString ( ) ) ; <nl> + <nl> + / / Next into the next block again . <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 2 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 4 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Seek to first and step back without accessing value . <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 0 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 5 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + iter - > Prev ( ) ; <nl> + EXPECT_FALSE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 2 : 5 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + / / Do some SeekForPrev ( ) and SeekToLast ( ) just to cover all methods . <nl> + iter - > SeekForPrev ( ikey ( " caad " ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 4 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 3 : 6 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( " v4 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 3 : 6 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + iter - > SeekToLast ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( keys [ 7 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 4 : 7 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( " v7 " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( use_first_key ? 4 : 7 , <nl> + stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + <nl> + EXPECT_EQ ( 4 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + c . ResetTableReader ( ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_P ( BlockBasedTableTest , BinaryIndexWithFirstKeyGlobalSeqno ) { <nl> + BlockBasedTableOptions table_options = GetBlockBasedTableOptions ( ) ; <nl> + table_options . index_type = BlockBasedTableOptions : : kBinarySearchWithFirstKey ; <nl> + table_options . block_cache = NewLRUCache ( 10000 ) ; <nl> + Options options ; <nl> + options . statistics = CreateDBStatistics ( ) ; <nl> + Statistics * stats = options . statistics . get ( ) ; <nl> + options . table_factory . reset ( NewBlockBasedTableFactory ( table_options ) ) ; <nl> + std : : unique_ptr < InternalKeyComparator > comparator ( <nl> + new InternalKeyComparator ( BytewiseComparator ( ) ) ) ; <nl> + const ImmutableCFOptions ioptions ( options ) ; <nl> + const MutableCFOptions moptions ( options ) ; <nl> + <nl> + TableConstructor c ( BytewiseComparator ( ) , / * convert_to_internal_key * / false , <nl> + / * level * / - 1 , / * largest_seqno * / 42 ) ; <nl> + <nl> + c . Add ( InternalKey ( " b " , 0 , kTypeValue ) . Encode ( ) . ToString ( ) , " x " ) ; <nl> + c . Add ( InternalKey ( " c " , 0 , kTypeValue ) . Encode ( ) . ToString ( ) , " y " ) ; <nl> + <nl> + std : : vector < std : : string > keys ; <nl> + stl_wrappers : : KVMap kvmap ; <nl> + c . Finish ( options , ioptions , moptions , table_options , * comparator , & keys , <nl> + & kvmap ) ; <nl> + ASSERT_EQ ( 2 , keys . size ( ) ) ; <nl> + <nl> + auto reader = c . GetTableReader ( ) ; <nl> + auto props = reader - > GetTableProperties ( ) ; <nl> + ASSERT_EQ ( 1u , props - > num_data_blocks ) ; <nl> + std : : unique_ptr < InternalIterator > iter ( reader - > NewIterator ( <nl> + ReadOptions ( ) , / * prefix_extractor = * / nullptr , / * arena = * / nullptr , <nl> + / * skip_filters = * / false , TableReaderCaller : : kUncategorized ) ) ; <nl> + <nl> + iter - > Seek ( InternalKey ( " a " , 0 , kTypeValue ) . Encode ( ) . ToString ( ) ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + EXPECT_EQ ( InternalKey ( " b " , 42 , kTypeValue ) . Encode ( ) . ToString ( ) , <nl> + iter - > key ( ) . ToString ( ) ) ; <nl> + EXPECT_NE ( keys [ 0 ] , iter - > key ( ) . ToString ( ) ) ; <nl> + / / Key should have been served from index , without reading data blocks . <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + <nl> + EXPECT_EQ ( " x " , iter - > value ( ) . ToString ( ) ) ; <nl> + EXPECT_EQ ( 1 , stats - > getTickerCount ( BLOCK_CACHE_DATA_MISS ) ) ; <nl> + EXPECT_EQ ( 0 , stats - > getTickerCount ( BLOCK_CACHE_DATA_HIT ) ) ; <nl> + EXPECT_EQ ( InternalKey ( " b " , 42 , kTypeValue ) . Encode ( ) . ToString ( ) , <nl> + iter - > key ( ) . ToString ( ) ) ; <nl> + <nl> + c . ResetTableReader ( ) ; <nl> + } <nl> + <nl> / / It ' s very hard to figure out the index block size of a block accurately . <nl> / / To make sure we get the index size , we just make sure as key number <nl> / / grows , the filter block size also grows . <nl> TEST_P ( BlockBasedTableTest , PropertiesBlockRestartPointTest ) { <nl> Block metaindex_block ( std : : move ( metaindex_contents ) , <nl> kDisableGlobalSequenceNumber ) ; <nl> <nl> - std : : unique_ptr < InternalIterator > meta_iter ( <nl> - metaindex_block . NewIterator < DataBlockIter > ( BytewiseComparator ( ) , <nl> - BytewiseComparator ( ) ) ) ; <nl> + std : : unique_ptr < InternalIterator > meta_iter ( metaindex_block . NewDataIterator ( <nl> + BytewiseComparator ( ) , BytewiseComparator ( ) ) ) ; <nl> bool found_properties_block = true ; <nl> ASSERT_OK ( SeekToPropertiesBlock ( meta_iter . get ( ) , & found_properties_block ) ) ; <nl> ASSERT_TRUE ( found_properties_block ) ; <nl> TEST_P ( BlockBasedTableTest , PropertiesMetaBlockLast ) { <nl> <nl> / / verify properties block comes last <nl> std : : unique_ptr < InternalIterator > metaindex_iter { <nl> - metaindex_block . NewIterator < DataBlockIter > ( options . comparator , <nl> - options . comparator ) } ; <nl> + metaindex_block . NewDataIterator ( options . comparator , options . comparator ) } ; <nl> uint64_t max_offset = 0 ; <nl> std : : string key_at_max_offset ; <nl> for ( metaindex_iter - > SeekToFirst ( ) ; metaindex_iter - > Valid ( ) ; <nl> mmm a / table / two_level_iterator . cc <nl> ppp b / table / two_level_iterator . cc <nl> namespace rocksdb { <nl> <nl> namespace { <nl> <nl> - class TwoLevelIndexIterator : public InternalIteratorBase < BlockHandle > { <nl> + class TwoLevelIndexIterator : public InternalIteratorBase < IndexValue > { <nl> public : <nl> explicit TwoLevelIndexIterator ( <nl> TwoLevelIteratorState * state , <nl> - InternalIteratorBase < BlockHandle > * first_level_iter ) ; <nl> + InternalIteratorBase < IndexValue > * first_level_iter ) ; <nl> <nl> ~ TwoLevelIndexIterator ( ) override { <nl> first_level_iter_ . DeleteIter ( false / * is_arena_mode * / ) ; <nl> class TwoLevelIndexIterator : public InternalIteratorBase < BlockHandle > { <nl> assert ( Valid ( ) ) ; <nl> return second_level_iter_ . key ( ) ; <nl> } <nl> - BlockHandle value ( ) const override { <nl> + IndexValue value ( ) const override { <nl> assert ( Valid ( ) ) ; <nl> return second_level_iter_ . value ( ) ; <nl> } <nl> class TwoLevelIndexIterator : public InternalIteratorBase < BlockHandle > { <nl> } <nl> void SkipEmptyDataBlocksForward ( ) ; <nl> void SkipEmptyDataBlocksBackward ( ) ; <nl> - void SetSecondLevelIterator ( InternalIteratorBase < BlockHandle > * iter ) ; <nl> + void SetSecondLevelIterator ( InternalIteratorBase < IndexValue > * iter ) ; <nl> void InitDataBlock ( ) ; <nl> <nl> TwoLevelIteratorState * state_ ; <nl> - IteratorWrapperBase < BlockHandle > first_level_iter_ ; <nl> - IteratorWrapperBase < BlockHandle > second_level_iter_ ; / / May be nullptr <nl> + IteratorWrapperBase < IndexValue > first_level_iter_ ; <nl> + IteratorWrapperBase < IndexValue > second_level_iter_ ; / / May be nullptr <nl> Status status_ ; <nl> / / If second_level_iter is non - nullptr , then " data_block_handle_ " holds the <nl> / / " index_value " passed to block_function_ to create the second_level_iter . <nl> class TwoLevelIndexIterator : public InternalIteratorBase < BlockHandle > { <nl> <nl> TwoLevelIndexIterator : : TwoLevelIndexIterator ( <nl> TwoLevelIteratorState * state , <nl> - InternalIteratorBase < BlockHandle > * first_level_iter ) <nl> + InternalIteratorBase < IndexValue > * first_level_iter ) <nl> : state_ ( state ) , first_level_iter_ ( first_level_iter ) { } <nl> <nl> void TwoLevelIndexIterator : : Seek ( const Slice & target ) { <nl> void TwoLevelIndexIterator : : SkipEmptyDataBlocksBackward ( ) { <nl> } <nl> <nl> void TwoLevelIndexIterator : : SetSecondLevelIterator ( <nl> - InternalIteratorBase < BlockHandle > * iter ) { <nl> - InternalIteratorBase < BlockHandle > * old_iter = second_level_iter_ . Set ( iter ) ; <nl> + InternalIteratorBase < IndexValue > * iter ) { <nl> + InternalIteratorBase < IndexValue > * old_iter = second_level_iter_ . Set ( iter ) ; <nl> delete old_iter ; <nl> } <nl> <nl> void TwoLevelIndexIterator : : InitDataBlock ( ) { <nl> if ( ! first_level_iter_ . Valid ( ) ) { <nl> SetSecondLevelIterator ( nullptr ) ; <nl> } else { <nl> - BlockHandle handle = first_level_iter_ . value ( ) ; <nl> + BlockHandle handle = first_level_iter_ . value ( ) . handle ; <nl> if ( second_level_iter_ . iter ( ) ! = nullptr & & <nl> ! second_level_iter_ . status ( ) . IsIncomplete ( ) & & <nl> handle . offset ( ) = = data_block_handle_ . offset ( ) ) { <nl> / / second_level_iter is already constructed with this iterator , so <nl> / / no need to change anything <nl> } else { <nl> - InternalIteratorBase < BlockHandle > * iter = <nl> + InternalIteratorBase < IndexValue > * iter = <nl> state_ - > NewSecondaryIterator ( handle ) ; <nl> data_block_handle_ = handle ; <nl> SetSecondLevelIterator ( iter ) ; <nl> void TwoLevelIndexIterator : : InitDataBlock ( ) { <nl> <nl> } / / namespace <nl> <nl> - InternalIteratorBase < BlockHandle > * NewTwoLevelIterator ( <nl> + InternalIteratorBase < IndexValue > * NewTwoLevelIterator ( <nl> TwoLevelIteratorState * state , <nl> - InternalIteratorBase < BlockHandle > * first_level_iter ) { <nl> + InternalIteratorBase < IndexValue > * first_level_iter ) { <nl> return new TwoLevelIndexIterator ( state , first_level_iter ) ; <nl> } <nl> } / / namespace rocksdb <nl> mmm a / table / two_level_iterator . h <nl> ppp b / table / two_level_iterator . h <nl> struct TwoLevelIteratorState { <nl> TwoLevelIteratorState ( ) { } <nl> <nl> virtual ~ TwoLevelIteratorState ( ) { } <nl> - virtual InternalIteratorBase < BlockHandle > * NewSecondaryIterator ( <nl> + virtual InternalIteratorBase < IndexValue > * NewSecondaryIterator ( <nl> const BlockHandle & handle ) = 0 ; <nl> } ; <nl> <nl> - <nl> / / Return a new two level iterator . A two - level iterator contains an <nl> / / index iterator whose values point to a sequence of blocks where <nl> / / each block is itself a sequence of key , value pairs . The returned <nl> struct TwoLevelIteratorState { <nl> / / Uses a supplied function to convert an index_iter value into <nl> / / an iterator over the contents of the corresponding block . <nl> / / Note : this function expects first_level_iter was not created using the arena <nl> - extern InternalIteratorBase < BlockHandle > * NewTwoLevelIterator ( <nl> + extern InternalIteratorBase < IndexValue > * NewTwoLevelIterator ( <nl> TwoLevelIteratorState * state , <nl> - InternalIteratorBase < BlockHandle > * first_level_iter ) ; <nl> + InternalIteratorBase < IndexValue > * first_level_iter ) ; <nl> <nl> } / / namespace rocksdb <nl> mmm a / test_util / testutil . cc <nl> ppp b / test_util / testutil . cc <nl> <nl> <nl> # include " test_util / testutil . h " <nl> <nl> + # include < array > <nl> # include < cctype > <nl> # include < sstream > <nl> <nl> BlockBasedTableOptions RandomBlockBasedTableOptions ( Random * rnd ) { <nl> opt . cache_index_and_filter_blocks = rnd - > Uniform ( 2 ) ; <nl> opt . pin_l0_filter_and_index_blocks_in_cache = rnd - > Uniform ( 2 ) ; <nl> opt . pin_top_level_index_and_filter = rnd - > Uniform ( 2 ) ; <nl> - opt . index_type = rnd - > Uniform ( 2 ) ? BlockBasedTableOptions : : kBinarySearch <nl> - : BlockBasedTableOptions : : kHashSearch ; <nl> + using IndexType = BlockBasedTableOptions : : IndexType ; <nl> + const std : : array < IndexType , 4 > index_types = { <nl> + { IndexType : : kBinarySearch , IndexType : : kHashSearch , <nl> + IndexType : : kTwoLevelIndexSearch , IndexType : : kBinarySearchWithFirstKey } } ; <nl> + opt . index_type = <nl> + index_types [ rnd - > Uniform ( static_cast < int > ( index_types . size ( ) ) ) ] ; <nl> opt . hash_index_allow_collision = rnd - > Uniform ( 2 ) ; <nl> opt . checksum = static_cast < ChecksumType > ( rnd - > Uniform ( 3 ) ) ; <nl> opt . block_size = rnd - > Uniform ( 10000000 ) ; <nl> mmm a / util / coding . h <nl> ppp b / util / coding . h <nl> extern bool GetFixed32 ( Slice * input , uint32_t * value ) ; <nl> extern bool GetFixed16 ( Slice * input , uint16_t * value ) ; <nl> extern bool GetVarint32 ( Slice * input , uint32_t * value ) ; <nl> extern bool GetVarint64 ( Slice * input , uint64_t * value ) ; <nl> + extern bool GetVarsignedint64 ( Slice * input , int64_t * value ) ; <nl> extern bool GetLengthPrefixedSlice ( Slice * input , Slice * result ) ; <nl> / / This function assumes data is well - formed . <nl> extern Slice GetLengthPrefixedSlice ( const char * data ) ; <nl> inline bool GetVarint64 ( Slice * input , uint64_t * value ) { <nl> } <nl> } <nl> <nl> + inline bool GetVarsignedint64 ( Slice * input , int64_t * value ) { <nl> + const char * p = input - > data ( ) ; <nl> + const char * limit = p + input - > size ( ) ; <nl> + const char * q = GetVarsignedint64Ptr ( p , limit , value ) ; <nl> + if ( q = = nullptr ) { <nl> + return false ; <nl> + } else { <nl> + * input = Slice ( q , static_cast < size_t > ( limit - q ) ) ; <nl> + return true ; <nl> + } <nl> + } <nl> + <nl> / / Provide an interface for platform independent endianness transformation <nl> inline uint64_t EndianTransform ( uint64_t input , size_t size ) { <nl> char * pos = reinterpret_cast < char * > ( & input ) ; <nl>
Add an option to put first key of each sst block in the index ( )
facebook/rocksdb
b4d72094280e1e0220ec321779902aba6662db25
2019-06-25T03:54:04Z
mmm a / xbmc / utils / test / Makefile <nl> ppp b / xbmc / utils / test / Makefile <nl> SRCS = \ <nl> TestDownloadQueue . cpp \ <nl> TestDownloadQueueManager . cpp \ <nl> TestEndianSwap . cpp \ <nl> + Testfastmemcpy . cpp \ <nl> TestGlobalsHandling . cpp \ <nl> TestXBMCTinyXML . cpp <nl> <nl> new file mode 100644 <nl> index 000000000000 . . 04314bc9b930 <nl> mmm / dev / null <nl> ppp b / xbmc / utils / test / Testfastmemcpy . cpp <nl> <nl> + / * <nl> + * Copyright ( C ) 2005 - 2012 Team XBMC <nl> + * http : / / www . xbmc . org <nl> + * <nl> + * This Program is free software ; you can redistribute it and / or modify <nl> + * it under the terms of the GNU General Public License as published by <nl> + * the Free Software Foundation ; either version 2 , or ( at your option ) <nl> + * any later version . <nl> + * <nl> + * This Program is distributed in the hope that it will be useful , <nl> + * but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> + * GNU General Public License for more details . <nl> + * <nl> + * You should have received a copy of the GNU General Public License <nl> + * along with XBMC ; see the file COPYING . If not , write to <nl> + * the Free Software Foundation , 675 Mass Ave , Cambridge , MA 02139 , USA . <nl> + * http : / / www . gnu . org / copyleft / gpl . html <nl> + * <nl> + * / <nl> + <nl> + # include < stddef . h > / / TODO : This should go in fastmemcpy . h instead . <nl> + # include " utils / fastmemcpy . h " <nl> + <nl> + # include " gtest / gtest . h " <nl> + <nl> + static const char refdata [ ] = " \ x01 \ x02 \ x03 \ x04 \ x05 \ x06 \ x07 \ x08 " <nl> + " \ x09 \ x0a \ x0b \ x0c \ x0d \ x0e \ x0f \ x10 " <nl> + " \ x11 \ x12 \ x13 \ x14 \ x15 \ x16 \ x17 \ x18 " <nl> + " \ x19 \ x1a \ x1b \ x1c \ x1d \ x1e \ x1f \ x20 " <nl> + " \ x21 \ x22 \ x23 \ x24 \ x25 \ x26 \ x27 \ x28 " <nl> + " \ x29 \ x2a \ x2b \ x2c \ x2d \ x2e \ x2f \ x30 " ; <nl> + <nl> + TEST ( Testfastmemcpy , General ) <nl> + { <nl> + char vardata [ sizeof ( refdata ) ] ; <nl> + memset ( vardata , 0 , sizeof ( vardata ) ) ; <nl> + EXPECT_TRUE ( fast_memcpy ( vardata , refdata , sizeof ( refdata ) ) ) ; <nl> + EXPECT_TRUE ( ! memcmp ( refdata , vardata , sizeof ( refdata ) ) ) ; <nl> + } <nl>
[ GSOC ] Add test case for fast_memcpy ( ) .
xbmc/xbmc
a2ade7099007710cdd9897d7fc3df674ac242fd4
2012-09-05T19:07:41Z
mmm a / Code / CryEngine / CryAISystem / AIBubblesSystem / AIBubblesSystemImpl . cpp <nl> ppp b / Code / CryEngine / CryAISystem / AIBubblesSystem / AIBubblesSystemImpl . cpp <nl> SBubbleRequestId CAIBubblesSystem : : QueueMessage ( const char * messageName , const S <nl> { <nl> const SBubbleRequestId requestId = + + m_requestIdCounter ; <nl> <nl> - if ( request . GetRequestType ( ) = = SAIBubbleRequest : : eRT_PrototypeDialog ) <nl> - requestsList . push_back ( SAIBubbleRequestContainer ( requestId , messageNameId , request ) ) ; <nl> + if ( request . GetRequestType ( ) = = SAIBubbleRequest : : eRT_PrototypeDialog ) <nl> + requestsList . push_back ( SAIBubbleRequestContainer ( requestId , messageNameId , request ) ) ; <nl> else <nl> - requestsList . push_front ( SAIBubbleRequestContainer ( requestId , messageNameId , request ) ) ; <nl> + requestsList . push_front ( SAIBubbleRequestContainer ( requestId , messageNameId , request ) ) ; <nl> <nl> / / Log the message and if it ' s needed show the blocking popup <nl> + stack_string sTmp ; <nl> stack_string sMessage ; <nl> - request . GetMessage ( sMessage ) ; <nl> - sMessage . Format ( " % s - Message : % s " , pEntity - > GetName ( ) , sMessage . c_str ( ) ) ; <nl> + request . GetMessage ( sTmp ) ; <nl> + sMessage . Format ( " % s - Message : % s " , pEntity - > GetName ( ) , sTmp . c_str ( ) ) ; <nl> <nl> LogMessage ( sMessage . c_str ( ) , requestFlags ) ; <nl> <nl> class CAIBubblesSystem : : CBubbleRender <nl> <nl> if ( m_drawContext - > ProjectToScreen ( entityPos . x , entityPos . y , entityPos . z , & x , & y , & z ) ) <nl> { <nl> - if ( ( z > = 0 . 0f ) & & ( z < = 1 . 0f ) ) <nl> + if ( ( z > = 0 . 0f ) & & ( z < = 1 . 0f ) ) <nl> { <nl> m_bOnScreen = true ; <nl> <nl> class CAIBubblesSystem : : CBubbleRender <nl> y * = m_drawContext - > GetHeight ( ) * 0 . 01f ; <nl> <nl> m_bubbleOnscreenPos = Vec3 ( x , y , z ) ; <nl> - <nl> + <nl> const float distance = gEnv - > pSystem - > GetViewCamera ( ) . GetPosition ( ) . GetDistance ( entityPos ) ; <nl> m_currentTextSize = gAIEnv . CVars . BubblesSystemFontSize / distance ; <nl> } <nl> class CAIBubblesSystem : : CBubbleRender <nl> return true ; <nl> } <nl> <nl> - bool IsOnScreen ( ) const <nl> - { <nl> - return m_bOnScreen ; <nl> + bool IsOnScreen ( ) const <nl> + { <nl> + return m_bOnScreen ; <nl> } <nl> <nl> void DrawBubble ( const char * const message , const size_t numberOfLines , const EBubbleRequestOption flags ) <nl> class CAIBubblesSystem : : CBubbleRender <nl> bool bUseDepthTest ; <nl> if ( flags & eBNS_BalloonOverrideDepthTestCVar ) <nl> { <nl> - bUseDepthTest = ( flags & eBNS_BalloonUseDepthTest ) ! = 0 ; <nl> + bUseDepthTest = ( flags & eBNS_BalloonUseDepthTest ) ! = 0 ; <nl> } <nl> else <nl> { <nl> class CAIBubblesSystem : : CBubbleRender <nl> { <nl> SDrawTextInfo ti ; <nl> ti . xscale = ti . yscale = m_currentTextSize ; <nl> - ti . flags = eDrawText_IgnoreOverscan | eDrawText_2D | eDrawText_800x600 | eDrawText_FixedSize | eDrawText_Center <nl> - | ( bDepthTest ? eDrawText_DepthTest : 0 ) <nl> - | ( bFramed ? eDrawText_Framed : 0 ) ; <nl> + ti . flags = eDrawText_IgnoreOverscan | eDrawText_2D | eDrawText_800x600 | eDrawText_FixedSize | eDrawText_Center <nl> + | ( bDepthTest ? eDrawText_DepthTest : 0 ) <nl> + | ( bFramed ? eDrawText_Framed : 0 ) ; <nl> ti . color [ 0 ] = 0 . 0f ; <nl> ti . color [ 1 ] = 0 . 0f ; <nl> ti . color [ 2 ] = 0 . 0f ; <nl> class CAIBubblesSystem : : CBubbleRender <nl> <nl> private : <nl> CDebugDrawContext & m_drawContext ; <nl> - EntityId m_entityId ; <nl> - Vec3 m_bubbleOnscreenPos ; <nl> - float m_currentTextSize ; <nl> - bool m_bInitialized ; <nl> - bool m_bOnScreen ; <nl> + EntityId m_entityId ; <nl> + Vec3 m_bubbleOnscreenPos ; <nl> + float m_currentTextSize ; <nl> + bool m_bInitialized ; <nl> + bool m_bOnScreen ; <nl> } ; <nl> <nl> - <nl> void CAIBubblesSystem : : Update ( ) <nl> { <nl> if ( ! m_entityRequestsMap . empty ( ) ) <nl> void CAIBubblesSystem : : Update ( ) <nl> { <nl> SAIBubbleRequestContainer & requestContainer = * reqIt ; <nl> bool result = DisplaySpeechBubble ( requestContainer , bubbleRender ) ; <nl> - if ( requestContainer . IsOld ( currentTimestamp ) | | ! result ) <nl> + if ( requestContainer . IsOld ( currentTimestamp ) | | ! result ) <nl> { <nl> reqIt = requestsList . erase ( reqIt ) ; <nl> } <nl> bool CAIBubblesSystem : : DisplaySpeechBubble ( SAIBubbleRequestContainer & requestCon <nl> <nl> const SAIBubbleRequest & request = requestContainer . GetRequest ( ) ; <nl> <nl> - if ( ShouldSuppressMessageVisibility ( request . GetRequestType ( ) ) ) <nl> + if ( ShouldSuppressMessageVisibility ( request . GetRequestType ( ) ) ) <nl> { <nl> / / We only want to suppress the visibility of the message <nl> / / but we don ' t want to remove it from the queue <nl> bool CAIBubblesSystem : : DisplaySpeechBubble ( SAIBubbleRequestContainer & requestCon <nl> { <nl> return true ; <nl> } <nl> - <nl> + <nl> const TBubbleRequestOptionFlags requestFlags = request . GetFlags ( ) ; <nl> <nl> if ( requestFlags & eBNS_Balloon & & gAIEnv . CVars . BubblesSystemAlertnessFilter & eBNS_Balloon ) <nl> bool CAIBubblesSystem : : ShouldSuppressMessageVisibility ( const SAIBubbleRequest : : E <nl> <nl> bool CAIBubblesSystem : : ShouldFilterOutMessage ( const uint32 messsageNameUniqueId ) const <nl> { <nl> - if ( m_messageNameFilterSet . empty ( ) ) <nl> + if ( m_messageNameFilterSet . empty ( ) ) <nl> { <nl> return false ; <nl> } <nl> void CAIBubblesSystem : : SetNameFilter ( const char * szMessageNameFilter ) <nl> { <nl> return ; <nl> } <nl> - <nl> + <nl> stack_string messageNameFilter = szMessageNameFilter ; <nl> const size_t length = messageNameFilter . length ( ) ; <nl> int pos = 0 ; <nl> - do <nl> + do <nl> { <nl> stack_string token = messageNameFilter . Tokenize ( " " , pos ) ; <nl> m_messageNameFilterSet . insert ( ComputeMessageNameId ( token . c_str ( ) ) ) ; <nl> - } while ( pos < length ) ; <nl> + } <nl> + while ( pos < length ) ; <nl> } <nl> <nl> # endif / / CRYAISYSTEM_DEBUG <nl>
! B ( CE - 9397 ) ( AISystem ) AIBubblesSystem was writing to a string while reading from it at the same time ( Approved by achim )
CRYTEK/CRYENGINE
de55d69371b167fe385d78f62b412201d41cbe75
2016-06-17T12:44:44Z
mmm a / doc / installation . md <nl> ppp b / doc / installation . md <nl> This installation section is only intended if you plan to modify the OpenPose co <nl> - * * Ubuntu * * 14 , 16 , 18 . <nl> - * * Windows * * 7 , 8 , 10 . <nl> - * * Mac OSX * * Mavericks and above . <nl> + - * * Nvidia Jetson TX1 * * ( for JetPack 3 . 1 ) , installation instructions in [ doc / installation_jetson_tx1 . md ] ( . / installation_jetson_tx1 . md ) . <nl> - * * Nvidia Jetson TX2 * * ( for JetPack 3 . 1 or 3 . 3 ) , installation instructions in [ doc / installation_jetson_tx2_jetpack3 . 1 . md ] ( . / installation_jetson_tx2_jetpack3 . 1 . md ) and [ doc / installation_jetson_tx2_jetpack3 . 3 . md ] ( . / installation_jetson_tx2_jetpack3 . 3 . md ) respectively . <nl> - OpenPose has also been used on * * Windows 7 * * , * * CentOS * * , and * * Nvidia Jetson ( TK1 and TX1 ) * * embedded systems . However , we do not officially support them at the moment . <nl> <nl> new file mode 100644 <nl> index 000000000 . . 44cee0751 <nl> mmm / dev / null <nl> ppp b / doc / installation_jetson_tx1 . md <nl> <nl> + OpenPose - Installation on Nvidia Jetson TX1 <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + # # Introduction <nl> + We do not officially support TX1 , but thanks to @ dreinsdo , we have these instructions about how he made it work in his TX1 . We would like to thank @ dreinsdo , who added this documentation in [ this GitHub issue post ] ( https : / / github . com / CMU - Perceptual - Computing - Lab / openpose / issues / 1124 # issuecomment - 474090671 ) . If you face any issue , feel free to post on that issue post . <nl> + <nl> + # # Purpose <nl> + This document describes the full procedure for installing openpose on the Jetson TX1 . Other , and less involved , procedures may have been found successful by community members , and we encourage you to share your alternatives . <nl> + <nl> + <nl> + # # Preliminary remarks <nl> + This procedure details moving the Jetson file system to a larger drive , building a custom kernel , building OpenCV from source , and customizing Openpose Makefiles because TX1 eMMC is limited , the onboard camera did not work with Openpose , stock Jetpack 3 . 1 OpenCV build lacks Openpose dependencies , and Openpose makefiles are not compatible with TX1 CUDA arch , respectively . We used a PS3 Eye camera in place of the onboard camera , and a 120Gb SSD , but most USB webcams and SATA drives should work fine . <nl> + <nl> + <nl> + # # Contents <nl> + - [ Prep the TX1 ] ( # prep - the - tx1 ) <nl> + - [ Move file system to SATA drive ] ( # move - file - system - to - sata - drive ) <nl> + - [ Build custom kernel ] ( # build - custom - kernel ) <nl> + - [ Build OpenCV from source ] ( # build - opencv - from - source ) <nl> + - [ Install Openpose ] ( # install - openpose ) <nl> + - [ Usage ] ( # usage ) <nl> + <nl> + <nl> + # # Prep the TX1 <nl> + 1 . Flash Jetson TX1 with [ JetPack 3 . 1 ] ( https : / / developer . nvidia . com / embedded / jetpack ) per Jetpack installation guide . Be sure to complete both OS flashing and CUDA / cuDNN installation parts before installation . <nl> + 2 . Move file system to SATA drive . Follow steps of JetsonHacks article [ Install Samsung SSD on NVIDIA Jetson TX1 ] ( https : / / www . jetsonhacks . com / 2017 / 01 / 28 / install - samsung - ssd - on - nvidia - jetson - tx1 / ) . <nl> + <nl> + <nl> + # # Build custom kernel <nl> + This step is required because we were not able to use Openpose with the onboard TX1 camera . The steps are a combination of two JetsonHacks articles [ Build Kernel and ttyACM Module – NVIDIA Jetson TX1 ] ( https : / / www . jetsonhacks . com / 2017 / 08 / 07 / build - kernel - ttyacm - module - nvidia - jetson - tx1 / ) and [ Sony PlayStation Eye – NVIDIA Jetson TX1 ] ( https : / / www . jetsonhacks . com / 2016 / 09 / 29 / sony - playstation - eye - nvidia - jetson - tx1 / ) . If you are using a different webcam then include the driver for that webcam in place of the PS3 eye driver in step 3 . <nl> + 1 . Get the install scripts from [ JetsonHacks Github ] ( https : / / github . com / jetsonhacks / buildJetsonTX1Kernel / archive / v1 . 0 - L4T28 . 1 . zip ) . This link is to the zip of the ' JetPack 3 . 1 ' release . If you $ git clone $ from the master branch then you will get the most recent kernel build files , which are not compatible with JetPack 3 . 1 . <nl> + 2 . Unzip the downloaded files , enter the unzipped directory and run script to get kernel sources . <nl> + ` ` ` <nl> + $ cd buildJetsonTX1Kernel <nl> + $ sudo . / getKernelSources . sh <nl> + ` ` ` <nl> + 3 . The script will open the editor for the kernel configuration . Find the driver for your webcam and select with a checkbox ( not a dot ) . Save the configuration and quit the config window . <nl> + 4 . Make the kernel . <nl> + ` ` ` <nl> + $ sudo . / makeKernel . sh <nl> + ` ` ` <nl> + 5 . Replace the current kernel the newly built kernel image . <nl> + ` ` ` <nl> + $ sudo cp / usr / src / kernel / kernel - 4 . 4 / arch / arm64 / boot / Image ( $ PATH_TO_EMMC ) / boot / Image <nl> + ` ` ` <nl> + Replace $ PATH_TO_EMMC with the path to your eMMC . This is required because the Jetson initially boots to eMMC and loads the kernel from their , even with the SATA drive connected . <nl> + <nl> + <nl> + # # Build OpenCV from source <nl> + Follow JK Jung ' s steps from [ How to Install OpenCV ( 3 . 4 . 0 ) on Jetson TX2 ] ( https : / / jkjung - avt . github . io / opencv3 - on - tx2 / ) verbatim , with the following exception : omit installation of Python3 dependencies , i . e . skip the following lines . <nl> + ` ` ` <nl> + $ sudo apt - get install python3 - dev python3 - pip python3 - tk <nl> + $ sudo pip3 install numpy <nl> + $ sudo pip3 install matplotlib <nl> + ` ` ` <nl> + <nl> + <nl> + # # Install Openpose <nl> + The following steps detail the modification of three files to install Openpose . Modified versions of the files are attached and may alternatively be used . To use , be sure to rename both makefile configs to ` Makefile . config . Ubuntu16_cuda8_JetsonTX2 ` . <nl> + 1 . Clone from the master branch . <nl> + ` ` ` <nl> + $ git clone https : / / github . com / CMU - Perceptual - Computing - Lab / openpose <nl> + $ cd openpose <nl> + ` ` ` <nl> + 2 . Modify makefile config . For the installation procedure we will use the TX2 files for JetPack 3 . 1 . <nl> + ` ` ` <nl> + $ gedit scripts / ubuntu / Makefile . config . Ubuntu16_cuda8_JetsonTX2 <nl> + ` ` ` <nl> + Uncomment the opencv line <nl> + ` ` ` <nl> + OPENCV_VERSION : = 3 <nl> + ` ` ` <nl> + Replace all the ' CUDA_ARCH : = ' lines with the following <nl> + ` ` ` <nl> + CUDA_ARCH : = - gencode arch = compute_53 , code = [ sm_53 , compute_53 ] <nl> + ` ` ` <nl> + Add CUDNN - not sure if this is necessary , have not retried the install without it . <nl> + ` ` ` <nl> + USE_CUDNN : = 1 <nl> + ` ` ` <nl> + 3 . Correct error in install script path . <nl> + ` ` ` <nl> + $ gedit scripts / ubuntu / install_caffe_and_openpose_JetsonTX2_JetPack3 . 1 . sh <nl> + ` ` ` <nl> + Replace <nl> + ` ` ` <nl> + executeShInItsFolder " install_openpose_JetsonTX2_JetPack3 . 1 . sh " " . / scripts / ubuntu / " " . / " <nl> + ` ` ` <nl> + with <nl> + ` ` ` <nl> + executeShInItsFolder " . / scripts / ubuntu / install_openpose_JetsonTX2_JetPack3 . 1 . sh " " . / " " . / " <nl> + ` ` ` <nl> + 4 . Start the install process . When you initially call the install script the caffe repo will be cloned and associated files downloaded . As soon as Caffe starts compiling , halt the process and change the makefile config as in step 2 . <nl> + ` ` ` <nl> + bash . / scripts / ubuntu / install_caffe_and_openpose_JetsonTX2_JetPack3 . 1 . sh <nl> + ` ` ` <nl> + Once caffe begins to compile ` CTRL + C ` . <nl> + ` ` ` <nl> + $ gedit 3rdparty / caffe / Makefile . config . Ubuntu16_cuda8_JetsonTX2 <nl> + ` ` ` <nl> + Make the same changes as in step 2 . The CUDNN switch should already be on . <nl> + <nl> + 5 . Restart the installation process . <nl> + ` ` ` <nl> + bash . / scripts / ubuntu / install_caffe_and_openpose_JetsonTX2_JetPack3 . 1 . sh <nl> + ` ` ` <nl> + <nl> + # # Usage <nl> + To get to decent FPS you need to lower the net resolution : <nl> + ` ` ` <nl> + . / build / examples / openpose / openpose . bin - camera_resolution 640x480 - net_resolution 128x96 <nl> + ` ` ` <nl> + <nl> + To activate hand or face resolution please complete this command with the following options ( warning , both simultaneously will cause out of memory error ) : <nl> + ` ` ` <nl> + # Body and face <nl> + . / build / examples / openpose / openpose . bin - - face - face_net_resolution 256x256 <nl> + # Body and hands <nl> + . / build / examples / openpose / openpose . bin - - hand - hand_net_resolution 256x256 <nl> + # All body , face , and hands <nl> + . / build / examples / openpose / openpose . bin - - face - face_net_resolution 256x256 - - hand - hand_net_resolution 256x256 <nl> + ` ` ` <nl>
Added installation instructions for TX1
CMU-Perceptual-Computing-Lab/openpose
b6058505a61a65b14510470c6c0212c88df57e40
2019-04-14T04:16:56Z
mmm a / contracts / eosio . system / producer_pay . cpp <nl> ppp b / contracts / eosio . system / producer_pay . cpp <nl> <nl> <nl> namespace eosiosystem { <nl> <nl> - const int64_t min_daily_tokens = 100 ; <nl> - <nl> + const int64_t min_daily_tokens = 100 ; <nl> + const int64_t min_activated_stake = 150 ' 000 ' 000 ' 0000 ; <nl> const double continuous_rate = 0 . 04879 ; / / 5 % annual rate <nl> const double perblock_rate = 0 . 0025 ; / / 0 . 25 % <nl> const double standby_rate = 0 . 0075 ; / / 0 . 75 % <nl> namespace eosiosystem { <nl> require_auth ( N ( eosio ) ) ; <nl> <nl> / * * until activated stake crosses this threshold no new rewards are paid * / <nl> - if ( _gstate . total_activated_stake < 150 ' 000 ' 000 ' 0000 ) <nl> + if ( _gstate . total_activated_stake < min_activated_stake ) <nl> return ; <nl> <nl> if ( _gstate . last_pervote_bucket_fill = = 0 ) / / / start the presses <nl> namespace eosiosystem { <nl> <nl> const auto & prod = _producers . get ( owner ) ; <nl> eosio_assert ( prod . active ( ) , " producer does not have an active key " ) ; <nl> + <nl> + eosio_assert ( _gstate . total_activated_stake > = min_activated_stake , " not enough has been staked for producers to claim rewards " ) ; <nl> <nl> auto ct = current_time ( ) ; <nl> <nl> namespace eosiosystem { <nl> _gstate . last_pervote_bucket_fill = ct ; <nl> } <nl> <nl> - int64_t producer_per_block_pay = ( _gstate . perblock_bucket * prod . unpaid_blocks ) / _gstate . total_unpaid_blocks ; <nl> - int64_t producer_per_vote_pay = int64_t ( ( _gstate . pervote_bucket * prod . total_votes ) / _gstate . total_producer_vote_weight ) ; <nl> + int64_t producer_per_block_pay = 0 ; <nl> + if ( _gstate . total_unpaid_blocks > 0 ) { <nl> + producer_per_block_pay = ( _gstate . perblock_bucket * prod . unpaid_blocks ) / _gstate . total_unpaid_blocks ; <nl> + } <nl> + int64_t producer_per_vote_pay = 0 ; <nl> + if ( _gstate . total_producer_vote_weight > 0 ) { <nl> + producer_per_vote_pay = int64_t ( ( _gstate . pervote_bucket * prod . total_votes ) / _gstate . total_producer_vote_weight ) ; <nl> + } <nl> if ( producer_per_vote_pay < 100 ' 0000 ) { <nl> producer_per_vote_pay = 0 ; <nl> } <nl> mmm a / unittests / eosio . system_tests . cpp <nl> ppp b / unittests / eosio . system_tests . cpp <nl> BOOST_FIXTURE_TEST_CASE ( producer_onblock_check , eosio_system_tester ) try { <nl> BOOST_REQUIRE_EQUAL ( true , rest_didnt_produce ) ; <nl> } <nl> <nl> + { <nl> + BOOST_CHECK_EQUAL ( 0 , get_global_state ( ) [ " total_unpaid_blocks " ] . as < uint32_t > ( ) ) ; <nl> + BOOST_REQUIRE_EQUAL ( error ( " condition : assertion failed : not enough has been staked for producers to claim rewards " ) , <nl> + push_action ( producer_names . front ( ) , N ( claimrewards ) , mvo ( ) ( " owner " , producer_names . front ( ) ) ) ) ; <nl> + BOOST_REQUIRE_EQUAL ( 0 , get_balance ( producer_names . front ( ) ) . amount ) ; <nl> + BOOST_REQUIRE_EQUAL ( error ( " condition : assertion failed : not enough has been staked for producers to claim rewards " ) , <nl> + push_action ( producer_names . back ( ) , N ( claimrewards ) , mvo ( ) ( " owner " , producer_names . back ( ) ) ) ) ; <nl> + BOOST_REQUIRE_EQUAL ( 0 , get_balance ( producer_names . back ( ) ) . amount ) ; <nl> + } <nl> + <nl> / / stake across 15 % boundary <nl> transfer ( config : : system_account_name , " producvoterb " , " 100000000 . 0000 EOS " , config : : system_account_name ) ; <nl> BOOST_REQUIRE_EQUAL ( success ( ) , stake ( " producvoterb " , " 4000000 . 0000 EOS " , " 4000000 . 0000 EOS " ) ) ; <nl> BOOST_FIXTURE_TEST_CASE ( producer_onblock_check , eosio_system_tester ) try { <nl> } <nl> BOOST_REQUIRE_EQUAL ( true , all_21_produced ) ; <nl> BOOST_REQUIRE_EQUAL ( true , rest_didnt_produce ) ; <nl> + BOOST_REQUIRE_EQUAL ( success ( ) , <nl> + push_action ( producer_names . front ( ) , N ( claimrewards ) , mvo ( ) ( " owner " , producer_names . front ( ) ) ) ) ; <nl> + BOOST_REQUIRE ( 0 < get_balance ( producer_names . front ( ) ) . amount ) ; <nl> } <nl> <nl> } FC_LOG_AND_RETHROW ( ) <nl>
Merge pull request from EOSIO / issue3157
EOSIO/eos
f442d63d43d2da1d51e0c5e04a8b74c26c5e4030
2018-05-18T00:39:47Z
mmm a / emscripten . py <nl> ppp b / emscripten . py <nl> def make_table ( sig , raw ) : <nl> asm_setup + = ' \ n ' . join ( [ ' var % s = % s ; ' % ( f . replace ( ' . ' , ' _ ' ) , f ) for f in math_envs ] ) <nl> basic_funcs = [ ' abort ' , ' assert ' , ' asmPrintInt ' , ' asmPrintFloat ' , ' copyTempDouble ' , ' copyTempFloat ' ] + [ m . replace ( ' . ' , ' _ ' ) for m in math_envs ] <nl> if settings [ ' SAFE_HEAP ' ] : basic_funcs + = [ ' SAFE_HEAP_LOAD ' , ' SAFE_HEAP_STORE ' , ' SAFE_HEAP_CLEAR ' ] <nl> + if settings [ ' CHECK_HEAP_ALIGN ' ] : basic_funcs + = [ ' CHECK_ALIGN_2 ' , ' CHECK_ALIGN_4 ' , ' CHECK_ALIGN_8 ' ] <nl> basic_vars = [ ' STACKTOP ' , ' STACK_MAX ' , ' tempDoublePtr ' , ' ABORT ' ] <nl> basic_float_vars = [ ' NaN ' , ' Infinity ' ] <nl> if forwarded_json [ ' Types ' ] [ ' preciseI64MathUsed ' ] : <nl> mmm a / src / compiler . js <nl> ppp b / src / compiler . js <nl> if ( phase = = ' pre ' ) { <nl> print ( ' / / Note : For maximum - speed code , see " Optimizing Code " on the Emscripten wiki , https : / / github . com / kripken / emscripten / wiki / Optimizing - Code ' ) ; <nl> } <nl> <nl> - if ( DOUBLE_MODE | | CORRECT_SIGNS | | CORRECT_OVERFLOWS | | CORRECT_ROUNDINGS ) { <nl> + if ( DOUBLE_MODE | | CORRECT_SIGNS | | CORRECT_OVERFLOWS | | CORRECT_ROUNDINGS | | CHECK_HEAP_ALIGN ) { <nl> print ( ' / / Note : Some Emscripten settings may limit the speed of the generated code . ' ) ; <nl> } <nl> } <nl> mmm a / src / parseTools . js <nl> ppp b / src / parseTools . js <nl> function checkSafeHeap ( ) { <nl> function getHeapOffset ( offset , type , forceAsm ) { <nl> if ( USE_TYPED_ARRAYS ! = = 2 ) { <nl> return offset ; <nl> - } else { <nl> - if ( Runtime . getNativeFieldSize ( type ) > 4 ) { <nl> - type = ' i32 ' ; / / XXX we emulate 64 - bit values as 32 <nl> - } <nl> - var shifts = Math . log ( Runtime . getNativeTypeSize ( type ) ) / Math . LN2 ; <nl> - offset = ' ( ' + offset + ' ) ' ; <nl> - if ( shifts ! = 0 ) { <nl> - return ' ( ' + offset + ' > > ' + shifts + ' ) ' ; <nl> + } <nl> + <nl> + if ( Runtime . getNativeFieldSize ( type ) > 4 ) { <nl> + type = ' i32 ' ; / / XXX we emulate 64 - bit values as 32 <nl> + } <nl> + <nl> + var sz = Runtime . getNativeTypeSize ( type ) ; <nl> + var shifts = Math . log ( sz ) / Math . LN2 ; <nl> + offset = ' ( ' + offset + ' ) ' ; <nl> + if ( shifts ! = 0 ) { <nl> + if ( CHECK_HEAP_ALIGN ) { <nl> + return ' ( CHECK_ALIGN_ ' + sz + ' ( ' + offset + ' ) > > ' + shifts + ' ) ' ; <nl> } else { <nl> - / / we need to guard against overflows here , HEAP [ U ] 8 expects a guaranteed int <nl> - return isJSVar ( offset ) ? offset : ' ( ' + offset + ' | 0 ) ' ; <nl> + return ' ( ' + offset + ' > > ' + shifts + ' ) ' ; <nl> } <nl> + } else { <nl> + / / we need to guard against overflows here , HEAP [ U ] 8 expects a guaranteed int <nl> + return isJSVar ( offset ) ? offset : ' ( ' + offset + ' | 0 ) ' ; <nl> } <nl> } <nl> <nl> mmm a / src / preamble . js <nl> ppp b / src / preamble . js <nl> function SAFE_HEAP_COPY_HISTORY ( dest , src ) { <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> # endif <nl> <nl> + # if CHECK_HEAP_ALIGN <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / Debugging tools - alignment check <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + function CHECK_ALIGN_8 ( addr ) { <nl> + assert ( ( addr & 7 ) = = 0 , " address must be 8 - byte aligned , is " + addr + " ! " ) ; <nl> + return addr ; <nl> + } <nl> + function CHECK_ALIGN_4 ( addr ) { <nl> + assert ( ( addr & 3 ) = = 0 , " address must be 4 - byte aligned , is " + addr + " ! " ) ; <nl> + return addr ; <nl> + } <nl> + function CHECK_ALIGN_2 ( addr ) { <nl> + assert ( ( addr & 1 ) = = 0 , " address must be 2 - byte aligned ! " ) ; <nl> + return addr ; <nl> + } <nl> + # endif <nl> + <nl> + <nl> # if CHECK_OVERFLOWS <nl> / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> / / Debugging tools - Mathop overflows <nl> mmm a / src / settings . js <nl> ppp b / src / settings . js <nl> var SAFE_HEAP = 0 ; / / Check each write to the heap , for example , this will give <nl> / / that 3 is the option you usually want here . <nl> var SAFE_HEAP_LOG = 0 ; / / Log out all SAFE_HEAP operations <nl> <nl> + var CHECK_HEAP_ALIGN = 0 ; / / Check heap accesses for alignment , but don ' t do as <nl> + / / near extensive ( or slow ) checks as SAFE_HEAP . <nl> + <nl> var SAFE_DYNCALLS = 0 ; / / Show stack traces on missing function pointer / virtual method calls <nl> <nl> var ASM_HEAP_LOG = 0 ; / / Simple heap logging , like SAFE_HEAP_LOG but cheaper , and in asm . js <nl>
Merge pull request from vvuk / check - heap - align
emscripten-core/emscripten
5e6e6f889c7aef090ea1d5aad25b29083afb1036
2013-02-27T16:04:06Z
mmm a / Examples / Image / Miscellaneous / CIFAR - 10 / 02_BatchNormConv . ndl <nl> ppp b / Examples / Image / Miscellaneous / CIFAR - 10 / 02_BatchNormConv . ndl <nl> ndlMnistMacros = [ <nl> conv3WScale = 1 . 414 <nl> conv3BValue = 0 <nl> <nl> - scScale = 0 . 03 <nl> + scValue = 1 <nl> <nl> + expAvg = 1 <nl> + <nl> fc1WScale = 12 <nl> fc1BValue = 0 <nl> fc2WScale = 1 . 5 <nl> DNN = [ <nl> hStride1 = 1 <nl> vStride1 = 1 <nl> # weight [ cMap1 , kW1 * kH1 * ImageC ] <nl> - conv1 = ConvBNReLULayer ( featScaled , cMap1 , 75 , kW1 , kH1 , hStride1 , vStride1 , conv1WScale , conv1BValue , scScale ) <nl> + conv1 = ConvBNReLULayer ( featScaled , cMap1 , 75 , kW1 , kH1 , hStride1 , vStride1 , conv1WScale , conv1BValue , scValue , expAvg ) <nl> <nl> # pool1 <nl> pool1W = 3 <nl> DNN = [ <nl> hStride2 = 1 <nl> vStride2 = 1 <nl> # weight [ cMap2 , kW2 * kH2 * cMap1 ] <nl> - conv2 = ConvBNReLULayer ( pool1 , cMap2 , 800 , kW2 , kH2 , hStride2 , vStride2 , conv2WScale , conv2BValue , scScale ) <nl> + conv2 = ConvBNReLULayer ( pool1 , cMap2 , 800 , kW2 , kH2 , hStride2 , vStride2 , conv2WScale , conv2BValue , scValue , expAvg ) <nl> <nl> # pool2 <nl> pool2W = 3 <nl> DNN = [ <nl> hStride3 = 1 <nl> vStride3 = 1 <nl> # weight [ cMap3 , kW3 * kH3 * cMap2 ] <nl> - conv3 = ConvBNReLULayer ( pool2 , cMap3 , 800 , kW3 , kH3 , hStride3 , vStride3 , conv3WScale , conv3BValue , scScale ) <nl> + conv3 = ConvBNReLULayer ( pool2 , cMap3 , 800 , kW3 , kH3 , hStride3 , vStride3 , conv3WScale , conv3BValue , scValue , expAvg ) <nl> <nl> # pool3 <nl> pool3W = 3 <nl> DNN = [ <nl> pool3 = MaxPooling ( conv3 , pool3W , pool3H , pool3hStride , pool3vStride , imageLayout = " cudnn " ) <nl> <nl> hiddenDim = 64 <nl> - h1 = DnnBNReLULayer ( 576 , hiddenDim , pool3 , fc1WScale , fc1BValue ) <nl> + h1 = DnnBNReLULayer ( 576 , hiddenDim , pool3 , fc1WScale , fc1BValue , scValue , expAvg ) <nl> ol = DNNLastLayer ( hiddenDim , labelDim , h1 , fc2WScale , fc2BValue ) <nl> <nl> CE = CrossEntropyWithSoftmax ( labels , ol , tag = Criteria ) <nl> mmm a / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . config <nl> ppp b / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . config <nl> Train = [ <nl> minibatchSize = 128 <nl> learningRatesPerMB = 0 . 1 * 80 : 0 . 01 * 40 : 0 . 001 <nl> momentumPerMB = 0 . 9 <nl> - maxEpochs = 120 <nl> + maxEpochs = 160 <nl> L2RegWeight = 0 . 0001 <nl> dropoutRate = 0 <nl> <nl> mmm a / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . mel <nl> ppp b / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . mel <nl> rn2_1 . bn1_e = BatchNormalization ( rn2_1 . c1 , rn2_1 . sc1 , rn2_1 . b1 , rn2_1 . m1 , rn2_1 . <nl> SetNodeInput ( rn2_1 . y1 , 0 , rn2_1 . bn1_e ) <nl> rn2_1 . bn2_e = BatchNormalization ( rn2_1 . c2 , rn2_1 . sc2 , rn2_1 . b2 , rn2_1 . m2 , rn2_1 . isd2 , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> SetNodeInput ( rn2_1 . p , 0 , rn2_1 . bn2_e ) <nl> + # rn2_1 . bn_proj_e = BatchNormalization ( rn2_1 . c_proj , rn2_1 . sc_proj , rn2_1 . b_proj , rn2_1 . m_proj , rn2_1 . isd_proj , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> + SetNodeInput ( rn2_1 . p , 0 , rn2_1 . bn2_e ) <nl> + # SetNodeInput ( rn2_1 . p , 1 , rn2_1 . bn_proj_e ) <nl> <nl> rn2_2 . bn1_e = BatchNormalization ( rn2_2 . c1 , rn2_2 . sc1 , rn2_2 . b1 , rn2_2 . m1 , rn2_2 . isd1 , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> SetNodeInput ( rn2_2 . y1 , 0 , rn2_2 . bn1_e ) <nl> SetNodeInput ( rn2_3 . p , 0 , rn2_3 . bn2_e ) <nl> rn3_1 . bn1_e = BatchNormalization ( rn3_1 . c1 , rn3_1 . sc1 , rn3_1 . b1 , rn3_1 . m1 , rn3_1 . isd1 , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> SetNodeInput ( rn3_1 . y1 , 0 , rn3_1 . bn1_e ) <nl> rn3_1 . bn2_e = BatchNormalization ( rn3_1 . c2 , rn3_1 . sc2 , rn3_1 . b2 , rn3_1 . m2 , rn3_1 . isd2 , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> + # rn3_1 . bn_proj_e = BatchNormalization ( rn3_1 . c_proj , rn3_1 . sc_proj , rn3_1 . b_proj , rn3_1 . m_proj , rn3_1 . isd_proj , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> SetNodeInput ( rn3_1 . p , 0 , rn3_1 . bn2_e ) <nl> + # SetNodeInput ( rn3_1 . p , 1 , rn3_1 . bn_proj_e ) <nl> <nl> rn3_2 . bn1_e = BatchNormalization ( rn3_2 . c1 , rn3_2 . sc1 , rn3_2 . b1 , rn3_2 . m1 , rn3_2 . isd1 , eval = true , spatial = true , imageLayout = " cudnn " ) <nl> SetNodeInput ( rn3_2 . y1 , 0 , rn3_2 . bn1_e ) <nl> mmm a / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . ndl <nl> ppp b / Examples / Image / Miscellaneous / CIFAR - 10 / 03_ResNet . ndl <nl> LocalMacros = [ <nl> fc1WScale = 12 <nl> fc1BValue = 0 <nl> <nl> - scValue = 0 . 03 <nl> + scValue = 1 <nl> + <nl> + expAvg = 1 <nl> <nl> kW = 3 <nl> kH = 3 <nl> LocalMacros = [ <nl> <nl> DNN = [ <nl> cMap1 = 16 <nl> - conv1 = ConvBNReLULayer ( featScaled , cMap1 , 27 , kW , kH , hStride1 , vStride1 , convWScale , convBValue , scValue ) <nl> + conv1 = ConvBNReLULayer ( featScaled , cMap1 , 27 , kW , kH , hStride1 , vStride1 , convWScale , convBValue , scValue , expAvg ) <nl> <nl> - rn1_1 = ResNetNode2 ( conv1 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue ) <nl> - rn1_2 = ResNetNode2 ( rn1_1 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue ) <nl> - rn1_3 = ResNetNode2 ( rn1_2 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue ) <nl> + rn1_1 = ResNetNode2 ( conv1 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> + rn1_2 = ResNetNode2 ( rn1_1 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> + rn1_3 = ResNetNode2 ( rn1_2 , cMap1 , 144 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> <nl> cMap2 = 32 <nl> rn2_1_Wproj = Parameter ( cMap2 , cMap1 , init = fromFile , initFromFilePath = " $ Proj16to32Filename $ " , needGradient = false ) <nl> - rn2_1 = ResNetNode2Inc ( rn1_3 , cMap2 , 144 , 288 , kW , kH , convWScale , convBValue , scValue , rn2_1_Wproj ) <nl> - rn2_2 = ResNetNode2 ( rn2_1 , cMap2 , 288 , kW , kH , convWScale , convBValue , scValue ) <nl> - rn2_3 = ResNetNode2 ( rn2_2 , cMap2 , 288 , kW , kH , convWScale , convBValue , scValue ) <nl> + rn2_1 = ResNetNode2Inc ( rn1_3 , cMap2 , 144 , 288 , kW , kH , convWScale , convBValue , scValue , expAvg , rn2_1_Wproj ) <nl> + rn2_2 = ResNetNode2 ( rn2_1 , cMap2 , 288 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> + rn2_3 = ResNetNode2 ( rn2_2 , cMap2 , 288 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> <nl> cMap3 = 64 <nl> rn3_1_Wproj = Parameter ( cMap3 , cMap2 , init = fromFile , initFromFilePath = " $ Proj32to64Filename $ " , needGradient = false ) <nl> - rn3_1 = ResNetNode2Inc ( rn2_3 , cMap3 , 288 , 576 , kW , kH , convWScale , convBValue , scValue , rn3_1_Wproj ) <nl> - rn3_2 = ResNetNode2 ( rn3_1 , cMap3 , 576 , kW , kH , convWScale , convBValue , scValue ) <nl> - rn3_3 = ResNetNode2 ( rn3_2 , cMap3 , 576 , kW , kH , convWScale , convBValue , scValue ) <nl> + rn3_1 = ResNetNode2Inc ( rn2_3 , cMap3 , 288 , 576 , kW , kH , convWScale , convBValue , scValue , expAvg , rn3_1_Wproj ) <nl> + rn3_2 = ResNetNode2 ( rn3_1 , cMap3 , 576 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> + rn3_3 = ResNetNode2 ( rn3_2 , cMap3 , 576 , kW , kH , convWScale , convBValue , scValue , expAvg ) <nl> <nl> # Global average pooling <nl> poolW = 8 <nl> mmm a / Examples / Image / Miscellaneous / CIFAR - 10 / Macros . ndl <nl> ppp b / Examples / Image / Miscellaneous / CIFAR - 10 / Macros . ndl <nl> ConvReLULayer ( inp , outMap , inWCount , kW , kH , hStride , vStride , wScale , bValue ) <nl> y = RectifiedLinear ( p ) ; <nl> } <nl> <nl> - ConvBNReLULayer ( inp , outMap , inWCount , kW , kH , hStride , vStride , wScale , bValue , scScale ) <nl> + ConvBNReLULayer ( inp , outMap , inWCount , kW , kH , hStride , vStride , wScale , bValue , scValue , expAvg ) <nl> { <nl> W = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - # sc = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scScale ) <nl> - sc = Parameter ( outMap , 1 , init = fixedValue , value = 1 ) <nl> + sc = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> c = Convolution ( W , inp , kW , kH , outMap , hStride , vStride , zeroPadding = true , imageLayout = " cudnn " ) <nl> - bn = BatchNormalization ( c , sc , b , m , isd , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> + bn = BatchNormalization ( c , sc , b , m , isd , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> y = RectifiedLinear ( bn ) ; <nl> } <nl> <nl> - ResNetNode2 ( inp , outMap , inWCount , kW , kH , wScale , bValue , scScale ) <nl> + ResNetNode2 ( inp , outMap , inWCount , kW , kH , wScale , bValue , scValue , expAvg ) <nl> { <nl> W1 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - # sc1 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scScale ) <nl> - sc1 = Parameter ( outMap , 1 , init = fixedValue , value = 1 ) <nl> + sc1 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> c1 = Convolution ( W1 , inp , kW , kH , outMap , 1 , 1 , zeroPadding = true , imageLayout = " cudnn " ) <nl> - bn1 = BatchNormalization ( c1 , sc1 , b1 , m1 , isd1 , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> + bn1 = BatchNormalization ( c1 , sc1 , b1 , m1 , isd1 , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> y1 = RectifiedLinear ( bn1 ) ; <nl> <nl> W2 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - # sc2 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scScale ) <nl> - sc2 = Parameter ( outMap , 1 , init = fixedValue , value = 1 ) <nl> + sc2 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> c2 = Convolution ( W2 , y1 , kW , kH , outMap , 1 , 1 , zeroPadding = true , imageLayout = " cudnn " ) <nl> - bn2 = BatchNormalization ( c2 , sc2 , b2 , m2 , isd2 , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> + bn2 = BatchNormalization ( c2 , sc2 , b2 , m2 , isd2 , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> p = Plus ( bn2 , inp ) <nl> y2 = RectifiedLinear ( p ) ; <nl> } <nl> <nl> - ResNetNode2Inc ( inp , outMap , inWCount , wCount , kW , kH , wScale , bValue , scScale , Wproj ) <nl> + ResNetNode2Inc ( inp , outMap , inWCount , wCount , kW , kH , wScale , bValue , scValue , expAvg , Wproj ) <nl> { <nl> + # First convolution layer . <nl> W1 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - # sc1 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scScale ) <nl> - sc1 = Parameter ( outMap , 1 , init = fixedValue , value = 1 ) <nl> + sc1 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> c1 = Convolution ( W1 , inp , kW , kH , outMap , 2 , 2 , zeroPadding = true , imageLayout = " cudnn " ) <nl> - bn1 = BatchNormalization ( c1 , sc1 , b1 , m1 , isd1 , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> + bn1 = BatchNormalization ( c1 , sc1 , b1 , m1 , isd1 , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> y1 = RectifiedLinear ( bn1 ) ; <nl> <nl> + # Second convolution layer . <nl> W2 = Parameter ( outMap , wCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - # sc2 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scScale ) <nl> - sc2 = Parameter ( outMap , 1 , init = fixedValue , value = 1 ) <nl> + sc2 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> c2 = Convolution ( W2 , y1 , kW , kH , outMap , 1 , 1 , zeroPadding = true , imageLayout = " cudnn " ) <nl> - bn2 = BatchNormalization ( c2 , sc2 , b2 , m2 , isd2 , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> + bn2 = BatchNormalization ( c2 , sc2 , b2 , m2 , isd2 , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> <nl> - cproj = Convolution ( Wproj , inp , 1 , 1 , outMap , 2 , 2 , zeroPadding = false , imageLayout = " cudnn " ) <nl> - p = Plus ( bn2 , cproj ) <nl> + # Projection convolution layer . <nl> + # b_proj = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> + # sc_proj = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> + # m_proj = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> + # isd_proj = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> + <nl> + c_proj = Convolution ( Wproj , inp , 1 , 1 , outMap , 2 , 2 , zeroPadding = false , imageLayout = " cudnn " ) <nl> + # bn_proj = BatchNormalization ( c_proj , sc_proj , b_proj , m_proj , isd_proj , eval = false , spatial = true , expAvgFactor = expAvg , imageLayout = " cudnn " ) <nl> + <nl> + # p = Plus ( bn2 , bn_proj ) <nl> + p = Plus ( bn2 , c_proj ) <nl> y2 = RectifiedLinear ( p ) ; <nl> } <nl> <nl> DnnReLULayer ( inDim , outDim , x , wScale , bValue ) <nl> y = RectifiedLinear ( z ) <nl> } <nl> <nl> - DnnBNReLULayer ( inDim , outDim , x , wScale , bValue ) <nl> + DnnBNReLULayer ( inDim , outDim , x , wScale , bValue , scValue , expAvg ) <nl> { <nl> W = Parameter ( outDim , inDim , init = Gaussian , initValueScale = wScale ) <nl> b = Parameter ( outDim , 1 , init = fixedValue , value = bValue ) <nl> - sc = Parameter ( outDim , 1 , init = Gaussian , initValueScale = 0 . 01 ) <nl> + sc = Parameter ( outDim , 1 , init = fixedValue , value = scValue ) <nl> m = Parameter ( outDim , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd = Parameter ( outDim , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> t = Times ( W , x ) <nl> - bn = BatchNormalization ( t , sc , b , m , isd , eval = false , spatial = false , imageLayout = " cudnn " ) <nl> + bn = BatchNormalization ( t , sc , b , m , isd , eval = false , spatial = false , expAvgFactor = expAvg ) <nl> y = RectifiedLinear ( bn ) <nl> } <nl> <nl> mmm a / Examples / Image / Miscellaneous / ImageNet / ResNet / Macros . ndl <nl> ppp b / Examples / Image / Miscellaneous / ImageNet / ResNet / Macros . ndl <nl> ConvBNReLULayer ( inp , outMap , inWCount , kW , kH , hStride , vStride , wScale , bValue , <nl> { <nl> W = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode2 ( inp , outMap , inWCount , kW , kH , wScale , bValue , scValue ) <nl> { <nl> W1 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc1 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc1 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode2 ( inp , outMap , inWCount , kW , kH , wScale , bValue , scValue ) <nl> <nl> W2 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc2 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc2 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode2Conv ( inp , outMap , inWCount , wCount , kW , kH , wScale , bValue , scValue , <nl> { <nl> W1 = Parameter ( outMap , inWCount , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc1 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc1 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode2Conv ( inp , outMap , inWCount , wCount , kW , kH , wScale , bValue , scValue , <nl> <nl> W2 = Parameter ( outMap , wCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc2 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc2 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3 ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue ) <nl> # 1x1 reducing convolution . <nl> W1 = Parameter ( convMap , inMap , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( convMap , 1 , init = fixedValue , value = bValue ) <nl> - sc1 = Parameter ( convMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc1 = Parameter ( convMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3 ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue ) <nl> # 3x3 convolution . <nl> W2 = Parameter ( convMap , convWCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( convMap , 1 , init = fixedValue , value = bValue ) <nl> - sc2 = Parameter ( convMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc2 = Parameter ( convMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3 ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue ) <nl> # 1x1 expanding convolution . <nl> W3 = Parameter ( outMap , convMap , init = Gaussian , initValueScale = wScale ) <nl> b3 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc3 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc3 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m3 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd3 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3 ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue ) <nl> y3 = RectifiedLinear ( p ) ; <nl> } <nl> <nl> - ResNetNode3Inc ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue , wProj ) <nl> + ResNetNode3Inc ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue , wProj , projStride ) <nl> { <nl> # 1x1 reducing convolution . <nl> W1 = Parameter ( convMap , inMap , init = Gaussian , initValueScale = wScale ) <nl> b1 = Parameter ( convMap , 1 , init = fixedValue , value = bValue ) <nl> - sc1 = Parameter ( convMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc1 = Parameter ( convMap , 1 , init = fixedValue , value = scValue ) <nl> m1 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd1 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3Inc ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue , <nl> # 3x3 convolution . <nl> W2 = Parameter ( convMap , convWCount , init = Gaussian , initValueScale = wScale ) <nl> b2 = Parameter ( convMap , 1 , init = fixedValue , value = bValue ) <nl> - sc2 = Parameter ( convMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc2 = Parameter ( convMap , 1 , init = fixedValue , value = scValue ) <nl> m2 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd2 = Parameter ( convMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> - c2 = Convolution ( W2 , y1 , 3 , 3 , convMap , 2 , 2 , zeroPadding = true , imageLayout = " cudnn " ) <nl> + c2 = Convolution ( W2 , y1 , 3 , 3 , convMap , projStride , projStride , zeroPadding = true , imageLayout = " cudnn " ) <nl> bn2 = BatchNormalization ( c2 , sc2 , b2 , m2 , isd2 , eval = false , spatial = true , expAvgFactor = 1 . 0 , imageLayout = " cudnn " ) <nl> y2 = RectifiedLinear ( bn2 ) ; <nl> <nl> # 1x1 expanding convolution . <nl> W3 = Parameter ( outMap , convMap , init = Gaussian , initValueScale = wScale ) <nl> b3 = Parameter ( outMap , 1 , init = fixedValue , value = bValue ) <nl> - sc3 = Parameter ( outMap , 1 , init = Gaussian , initValueScale = scValue ) <nl> + sc3 = Parameter ( outMap , 1 , init = fixedValue , value = scValue ) <nl> m3 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> isd3 = Parameter ( outMap , 1 , init = fixedValue , value = 0 , needGradient = false ) <nl> <nl> ResNetNode3Inc ( inp , inMap , convMap , outMap , convWCount , wScale , bValue , scValue , <nl> bn3 = BatchNormalization ( c3 , sc3 , b3 , m3 , isd3 , eval = false , spatial = true , imageLayout = " cudnn " ) <nl> <nl> # Increasing input dimension convolution <nl> - cProj = Convolution ( wProj , inp , 1 , 1 , outMap , 2 , 2 , zeroPadding = false , imageLayout = " cudnn " ) <nl> + cProj = Convolution ( wProj , inp , 1 , 1 , outMap , projStride , projStride , zeroPadding = false , imageLayout = " cudnn " ) <nl> <nl> p = Plus ( bn3 , cProj ) <nl> y3 = RectifiedLinear ( p ) ; <nl> mmm a / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_152 . ndl <nl> ppp b / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_152 . ndl <nl> ndlMacros = [ <nl> LabelDim = 1000 <nl> <nl> features = ImageInput ( ImageW , ImageH , ImageC , tag = feature , imageLayout = " cudnn " ) <nl> - featOffs = Const ( 0 , rows = 150528 ) <nl> - featScaled = Plus ( features , featOffs ) <nl> labels = Input ( LabelDim , tag = label ) <nl> <nl> # Kernels width and height . <nl> ndlMacros = [ <nl> # Initial parameter values . <nl> convWScale = 7 . 07 <nl> convBValue = 0 <nl> - scValue = 0 . 03 <nl> + scValue = 1 <nl> fcWScale = 3 . 0 <nl> fcBValue = 1 <nl> ] <nl> DNN = [ <nl> cMap5 = 1024 <nl> cMap6 = 2048 <nl> <nl> - conv1 = ConvBNReLULayer ( featScaled , cMap1 , 147 , 7 , 7 , 2 , 2 , convWScale , convBValue , scValue ) <nl> - pool1 = MaxPooling ( conv1 , poolW , poolH , poolhs , poolvs , imageLayout = " cudnn " ) <nl> + conv1 = ConvBNReLULayer ( features , cMap1 , 147 , 7 , 7 , 2 , 2 , convWScale , convBValue , scValue ) <nl> + # Max pooling <nl> + pool1W = 2 <nl> + pool1H = 2 <nl> + pool1hs = 2 <nl> + pool1vs = 2 <nl> + pool1 = MaxPooling ( conv1 , pool1W , pool1H , pool1hs , pool1vs , imageLayout = " cudnn " ) <nl> <nl> rn1_1_Wproj = Parameter ( cMap3 , cMap1 , init = fromFile , initFromFilePath = " $ Proj64to256Filename $ " , needGradient = false ) <nl> - rn1_1 = ResNetNode3Inc ( pool1 , cMap1 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue , rn1_1_Wproj ) <nl> + rn1_1 = ResNetNode3Inc ( pool1 , cMap1 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue , rn1_1_Wproj , 1 ) <nl> rn1_2 = ResNetNode3 ( rn1_1 , cMap3 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue ) <nl> rn1_3 = ResNetNode3 ( rn1_2 , cMap3 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue ) <nl> <nl> rn2_1_Wproj = Parameter ( cMap4 , cMap3 , init = fromFile , initFromFilePath = " $ Proj256to512Filename $ " , needGradient = false ) <nl> - rn2_1 = ResNetNode3Inc ( rn1_3 , cMap3 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue , rn2_1_Wproj ) <nl> + rn2_1 = ResNetNode3Inc ( rn1_3 , cMap3 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue , rn2_1_Wproj , 2 ) <nl> rn2_2 = ResNetNode3 ( rn2_1 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> rn2_3 = ResNetNode3 ( rn2_2 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> rn2_4 = ResNetNode3 ( rn2_3 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> DNN = [ <nl> rn2_8 = ResNetNode3 ( rn2_7 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> <nl> rn3_1_Wproj = Parameter ( cMap5 , cMap4 , init = fromFile , initFromFilePath = " $ Proj512to1024Filename $ " , needGradient = false ) <nl> - rn3_1 = ResNetNode3Inc ( rn2_8 , cMap4 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue , rn3_1_Wproj ) <nl> + rn3_1 = ResNetNode3Inc ( rn2_8 , cMap4 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue , rn3_1_Wproj , 2 ) <nl> rn3_2 = ResNetNode3 ( rn3_1 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> rn3_3 = ResNetNode3 ( rn3_2 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> rn3_4 = ResNetNode3 ( rn3_3 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> DNN = [ <nl> rn3_36 = ResNetNode3 ( rn3_35 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> <nl> rn4_1_Wproj = Parameter ( cMap6 , cMap5 , init = fromFile , initFromFilePath = " $ Proj1024to2048Filename $ " , needGradient = false ) <nl> - rn4_1 = ResNetNode3Inc ( rn3_36 , cMap5 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue , rn4_1_Wproj ) <nl> + rn4_1 = ResNetNode3Inc ( rn3_36 , cMap5 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue , rn4_1_Wproj , 2 ) <nl> rn4_2 = ResNetNode3 ( rn4_1 , cMap6 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue ) <nl> rn4_3 = ResNetNode3 ( rn4_2 , cMap6 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue ) <nl> <nl> - pool5 = AveragePooling ( rn4_3 , poolW , poolH , poolhs , poolvs , imageLayout = " cudnn " ) <nl> + # Global average pooling <nl> + pool2W = 7 <nl> + pool2H = 7 <nl> + pool2hs = 1 <nl> + pool2vs = 1 <nl> + pool2 = AveragePooling ( rn4_3 , pool2W , pool2H , pool2hs , pool2vs , imageLayout = " cudnn " ) <nl> <nl> - ol = DnnLayer ( 8192 , labelDim , pool5 , fcWScale , fcBValue ) <nl> + ol = DnnLayer ( cMap6 , labelDim , pool2 , fcWScale , fcBValue ) <nl> <nl> CE = CrossEntropyWithSoftmax ( labels , ol , tag = Criteria ) <nl> Err = ErrorPrediction ( labels , ol , tag = Eval ) <nl> mmm a / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_34 . ndl <nl> ppp b / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_34 . ndl <nl> ndlMacros = [ <nl> hs = 1 <nl> vs = 1 <nl> <nl> - # Pooling settings . <nl> - poolW = 2 <nl> - poolH = 2 <nl> - poolhs = 2 <nl> - poolvs = 2 <nl> - <nl> # Initial parameter values . <nl> convWScale = 7 . 07 <nl> convBValue = 0 <nl> - scValue = 0 . 03 <nl> + scValue = 1 <nl> fcWScale = 3 . 0 <nl> fcBValue = 1 <nl> ] <nl> ndlMacros = [ <nl> DNN = [ <nl> cMap1 = 64 <nl> conv1 = ConvBNReLULayer ( features , cMap1 , 147 , 7 , 7 , 2 , 2 , convWScale , convBValue , scValue ) <nl> - pool1 = MaxPooling ( conv1 , poolW , poolH , poolhs , poolvs , imageLayout = " cudnn " ) <nl> + # Max pooling <nl> + pool1W = 2 <nl> + pool1H = 2 <nl> + pool1hs = 2 <nl> + pool1vs = 2 <nl> + pool1 = MaxPooling ( conv1 , pool1W , pool1H , pool1hs , pool1vs , imageLayout = " cudnn " ) <nl> <nl> rn1_1 = ResNetNode2 ( pool1 , cMap1 , 576 , kW , kH , convWScale , convBValue , scValue ) <nl> rn1_2 = ResNetNode2 ( rn1_1 , cMap1 , 576 , kW , kH , convWScale , convBValue , scValue ) <nl> DNN = [ <nl> rn4_2 = ResNetNode2 ( rn4_1 , cMap4 , 4608 , kW , kH , convWScale , convBValue , scValue ) <nl> rn4_3 = ResNetNode2 ( rn4_2 , cMap4 , 4608 , kW , kH , convWScale , convBValue , scValue ) <nl> <nl> - pool5 = AveragePooling ( rn4_3 , poolW , poolH , poolhs , poolvs , imageLayout = " cudnn " ) <nl> + # Global average pooling <nl> + pool2W = 7 <nl> + pool2H = 7 <nl> + pool2hs = 1 <nl> + pool2vs = 1 <nl> + pool5 = AveragePooling ( rn4_3 , pool2W , pool2H , pool2hs , pool2vs , imageLayout = " cudnn " ) <nl> <nl> - ol = DnnLayer ( 4608 , labelDim , pool5 , fcWScale , fcBValue ) <nl> + ol = DnnLayer ( cMap4 , labelDim , pool5 , fcWScale , fcBValue ) <nl> <nl> CE = CrossEntropyWithSoftmax ( labels , ol , tag = Criteria ) <nl> Err = ErrorPrediction ( labels , ol , tag = Eval ) <nl> new file mode 100644 <nl> index 00000000000 . . 520e68bc755 <nl> mmm / dev / null <nl> ppp b / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_50 . config <nl> <nl> + RootDir = " . " <nl> + <nl> + ConfigDir = " $ RootDir $ " <nl> + DataDir = " $ RootDir $ " <nl> + OutputDir = " $ RootDir $ / Output " <nl> + ModelDir = " $ OutputDir $ / Models " <nl> + <nl> + ndlMacros = $ ConfigDir $ / Macros . ndl <nl> + <nl> + precision = float <nl> + deviceId = Auto <nl> + <nl> + command = Train : AddTop5Eval : Test <nl> + <nl> + parallelTrain = false <nl> + <nl> + stderr = $ OutputDir $ / ResNet_50 <nl> + traceLevel = 1 <nl> + <nl> + Proj64to256Filename = $ ConfigDir $ / 64to256 . txt <nl> + Proj256to512Filename = $ ConfigDir $ / 256to512 . txt <nl> + Proj512to1024Filename = $ ConfigDir $ / 512to1024 . txt <nl> + Proj1024to2048Filename = $ ConfigDir $ / 1024to2048 . txt <nl> + <nl> + Train = [ <nl> + action = train <nl> + modelPath = $ ModelDir $ / ResNet_50 <nl> + <nl> + NDLNetworkBuilder = [ <nl> + networkDescription = $ ConfigDir $ / ResNet_50 . ndl <nl> + ] <nl> + <nl> + SGD = [ <nl> + epochSize = 0 <nl> + minibatchSize = 32 <nl> + learningRatesPerMB = 0 . 1 * 30 : 0 . 03 * 30 : 0 . 01 * 25 : 0 . 003 * 25 : 0 . 001 <nl> + momentumPerMB = 0 . 9 <nl> + maxEpochs = 120 <nl> + gradUpdateType = None <nl> + L2RegWeight = 0 . 0001 <nl> + dropoutRate = 0 <nl> + <nl> + ParallelTrain = [ <nl> + parallelizationMethod = DataParallelSGD <nl> + distributedMBReading = true <nl> + parallelizationStartEpoch = 1 <nl> + DataParallelSGD = [ <nl> + gradientBits = 1 <nl> + ] <nl> + ] <nl> + <nl> + numMBsToShowResult = 100 <nl> + ] <nl> + <nl> + reader = [ <nl> + readerType = ImageReader <nl> + # Map file which maps images to labels using the following format : <nl> + # < full path to image > < tab > < numerical label ( 0 - based class id ) > <nl> + # Example : <nl> + # C : \ Data \ ImageNet \ 2012 \ train \ n01440764 \ n01440764_10026 . JPEG < tab > 0 <nl> + file = $ DataDir $ / train_map . txt <nl> + # Randomize images before every epoch . Possible values : None , Auto . Default : Auto . <nl> + randomize = Auto <nl> + features = [ <nl> + # Below are the required parameters . <nl> + width = 224 <nl> + height = 224 <nl> + channels = 3 <nl> + # Below are the optional parameters . <nl> + # Possible values : Center , Random . Default : Center <nl> + cropType = Random <nl> + # Horizontal random flip , will be enabled by default if cropType = Random <nl> + # hflip = 0 <nl> + # Crop scale ratio . Examples : cropRatio = 0 . 9 , cropRatio = 0 . 7 : 0 . 9 . Default : 1 . <nl> + cropRatio = 0 . 46666 : 0 . 875 <nl> + # Crop scale ratio jitter type . <nl> + # Possible values : None , UniRatio , UniLength , UniArea . Default : UniRatio <nl> + jitterType = UniRatio <nl> + # Interpolation to use when scaling image to width x height size . <nl> + # Possible values : nearest , linear , cubic , lanczos . Default : linear . <nl> + interpolations = Linear <nl> + # Stores mean values for each pixel in OpenCV matrix XML format . <nl> + meanFile = $ ConfigDir $ / ImageNet1K_mean . xml <nl> + ] <nl> + labels = [ <nl> + labelDim = 1000 <nl> + ] <nl> + ] <nl> + ] <nl> + <nl> + AddTop5Eval = [ <nl> + action = edit <nl> + CurModel = $ ModelDir $ / ResNet_50 <nl> + NewModel = $ ModelDir $ / ResNet_50 . Top5 <nl> + editPath = $ ConfigDir $ / add_top5_layer . mel <nl> + ] <nl> + <nl> + Test = [ <nl> + action = test <nl> + modelPath = $ ModelDir $ / ResNet_50 . Top5 <nl> + # Set minibatch size for testing . <nl> + minibatchSize = 32 <nl> + <nl> + NDLNetworkBuilder = [ <nl> + networkDescription = $ ConfigDir $ / ResNet_50 . ndl <nl> + ] <nl> + <nl> + reader = [ <nl> + readerType = ImageReader <nl> + file = $ DataDir $ / val_map . txt <nl> + randomize = None <nl> + features = [ <nl> + width = 224 <nl> + height = 224 <nl> + channels = 3 <nl> + cropType = Center <nl> + meanFile = $ ConfigDir $ / ImageNet1K_mean . xml <nl> + ] <nl> + labels = [ <nl> + labelDim = 1000 <nl> + ] <nl> + ] <nl> + ] <nl> new file mode 100644 <nl> index 00000000000 . . 4d38a2af931 <nl> mmm / dev / null <nl> ppp b / Examples / Image / Miscellaneous / ImageNet / ResNet / ResNet_50 . ndl <nl> <nl> + load = ndlMacros <nl> + run = DNN <nl> + <nl> + ndlMacros = [ <nl> + ImageW = 224 <nl> + ImageH = 224 <nl> + ImageC = 3 <nl> + LabelDim = 1000 <nl> + <nl> + features = ImageInput ( ImageW , ImageH , ImageC , tag = feature , imageLayout = " cudnn " ) <nl> + labels = Input ( LabelDim , tag = label ) <nl> + <nl> + # Kernels width and height . <nl> + kW = 3 <nl> + kH = 3 <nl> + # Kernel stride . <nl> + hs = 1 <nl> + vs = 1 <nl> + <nl> + # Initial parameter values . <nl> + convWScale = 7 . 07 <nl> + convBValue = 0 <nl> + scValue = 1 <nl> + fcWScale = 3 . 0 <nl> + fcBValue = 1 <nl> + ] <nl> + <nl> + DNN = [ <nl> + cMap1 = 64 <nl> + cMap2 = 128 <nl> + cMap3 = 256 <nl> + cMap4 = 512 <nl> + cMap5 = 1024 <nl> + cMap6 = 2048 <nl> + <nl> + conv1 = ConvBNReLULayer ( features , cMap1 , 147 , 7 , 7 , 2 , 2 , convWScale , convBValue , scValue ) <nl> + # Max pooling <nl> + pool1W = 2 <nl> + pool1H = 2 <nl> + pool1hs = 2 <nl> + pool1vs = 2 <nl> + pool1 = MaxPooling ( conv1 , pool1W , pool1H , pool1hs , pool1vs , imageLayout = " cudnn " ) <nl> + <nl> + rn1_1_Wproj = Parameter ( cMap3 , cMap1 , init = fromFile , initFromFilePath = " $ Proj64to256Filename $ " , needGradient = false ) <nl> + rn1_1 = ResNetNode3Inc ( pool1 , cMap1 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue , rn1_1_Wproj , 1 ) <nl> + rn1_2 = ResNetNode3 ( rn1_1 , cMap3 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue ) <nl> + rn1_3 = ResNetNode3 ( rn1_2 , cMap3 , cMap1 , cMap3 , 576 , convWScale , convBValue , scValue ) <nl> + <nl> + rn2_1_Wproj = Parameter ( cMap4 , cMap3 , init = fromFile , initFromFilePath = " $ Proj256to512Filename $ " , needGradient = false ) <nl> + rn2_1 = ResNetNode3Inc ( rn1_3 , cMap3 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue , rn2_1_Wproj , 2 ) <nl> + rn2_2 = ResNetNode3 ( rn2_1 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> + rn2_3 = ResNetNode3 ( rn2_2 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> + rn2_4 = ResNetNode3 ( rn2_3 , cMap4 , cMap2 , cMap4 , 1152 , convWScale , convBValue , scValue ) <nl> + <nl> + rn3_1_Wproj = Parameter ( cMap5 , cMap4 , init = fromFile , initFromFilePath = " $ Proj512to1024Filename $ " , needGradient = false ) <nl> + rn3_1 = ResNetNode3Inc ( rn2_4 , cMap4 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue , rn3_1_Wproj , 2 ) <nl> + rn3_2 = ResNetNode3 ( rn3_1 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> + rn3_3 = ResNetNode3 ( rn3_2 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> + rn3_4 = ResNetNode3 ( rn3_3 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> + rn3_5 = ResNetNode3 ( rn3_4 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> + rn3_6 = ResNetNode3 ( rn3_5 , cMap5 , cMap3 , cMap5 , 2304 , convWScale , convBValue , scValue ) <nl> + <nl> + rn4_1_Wproj = Parameter ( cMap6 , cMap5 , init = fromFile , initFromFilePath = " $ Proj1024to2048Filename $ " , needGradient = false ) <nl> + rn4_1 = ResNetNode3Inc ( rn3_6 , cMap5 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue , rn4_1_Wproj , 2 ) <nl> + rn4_2 = ResNetNode3 ( rn4_1 , cMap6 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue ) <nl> + rn4_3 = ResNetNode3 ( rn4_2 , cMap6 , cMap4 , cMap6 , 4608 , convWScale , convBValue , scValue ) <nl> + <nl> + # Global average pooling <nl> + pool2W = 7 <nl> + pool2H = 7 <nl> + pool2hs = 1 <nl> + pool2vs = 1 <nl> + pool2 = AveragePooling ( rn4_3 , pool2W , pool2H , pool2hs , pool2vs , imageLayout = " cudnn " ) <nl> + <nl> + ol = DnnLayer ( cMap6 , labelDim , pool2 , fcWScale , fcBValue ) <nl> + <nl> + CE = CrossEntropyWithSoftmax ( labels , ol , tag = Criteria ) <nl> + Err = ErrorPrediction ( labels , ol , tag = Eval ) <nl> + OutputNodes = ol <nl> + ] <nl> mmm a / Source / ComputationNetworkLib / ConvolutionalNodes . h <nl> ppp b / Source / ComputationNetworkLib / ConvolutionalNodes . h <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> static const std : : wstring TypeName ( ) { return L " BatchNormalization " ; } <nl> public : <nl> BatchNormalizationNode ( DEVICEID_TYPE deviceId , const wstring & name ) : <nl> - Base ( deviceId , name ) , m_eval ( false ) , m_spatial ( false ) , m_expAvgFactor ( 0 ) , m_sampleCount ( 0 ) , m_imageLayoutKind ( ImageLayoutKind : : CHW ) <nl> + Base ( deviceId , name ) , m_eval ( false ) , m_spatial ( false ) , m_expAvgFactor ( 0 ) , m_mbCount ( 0 ) , m_imageLayoutKind ( ImageLayoutKind : : CHW ) <nl> { <nl> } <nl> BatchNormalizationNode ( DEVICEID_TYPE deviceId , const wstring & name , bool eval , bool spatial , double expAvgFactor , ImageLayoutKind imageLayoutKind ) : <nl> - Base ( deviceId , name ) , m_eval ( eval ) , m_spatial ( spatial ) , m_expAvgFactor ( expAvgFactor ) , m_imageLayoutKind ( imageLayoutKind ) , m_sampleCount ( 0 ) <nl> + Base ( deviceId , name ) , m_eval ( eval ) , m_spatial ( spatial ) , m_expAvgFactor ( expAvgFactor ) , m_imageLayoutKind ( imageLayoutKind ) , m_mbCount ( 0 ) <nl> { <nl> } <nl> BatchNormalizationNode ( const ScriptableObjects : : IConfigRecordPtr configp ) : <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> fstream < < m_spatial ; <nl> fstream < < m_expAvgFactor ; <nl> fstream < < ( int32_t ) m_imageLayoutKind ; <nl> - fstream < < m_sampleCount ; <nl> + fstream < < m_mbCount ; <nl> } <nl> <nl> void Load ( File & fstream , size_t modelVersion ) override <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> if ( verWritten > = 0x00010002 ) <nl> { <nl> fstream > > m_imageLayoutKind ; <nl> - fstream > > m_sampleCount ; <nl> + fstream > > m_mbCount ; <nl> } <nl> } <nl> <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> m_convEng - > NormalizeBatchInference ( * m_inT , sliceInputValue , * m_scaleBiasT , scale , bias , m_spatial , runMean , runInvStdDev , sliceOutputValue ) ; <nl> else <nl> { <nl> - m_convEng - > NormalizeBatch ( * m_inT , sliceInputValue , * m_scaleBiasT , scale , bias , m_spatial , m_expAvgFactor , runMean , runInvStdDev , <nl> + / / REVIEW alexeyk : hack , use m_expAvgFactor < = 0 to compute CMA . <nl> + double expAvgFactor = ( m_expAvgFactor > 0 ) ? m_expAvgFactor : ( 1 . 0 / ( 1 . 0 + m_mbCount ) ) ; <nl> + m_convEng - > NormalizeBatch ( * m_inT , sliceInputValue , * m_scaleBiasT , scale , bias , m_spatial , expAvgFactor , runMean , runInvStdDev , <nl> sliceOutputValue , * m_saveMean , * m_saveInvStdDev ) ; <nl> + m_mbCount + + ; <nl> } <nl> # if NANCHECK <nl> sliceOutputValue . HasNan ( " BatchNormalization " ) ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> struct VersionInfo <nl> { <nl> / / int32_t VerWrittenCur ( ) const { return 0x00010001 ; } / / Initial <nl> - int32_t VerWrittenCur ( ) const { return 0x00010002 ; } / / Added m_imageLayoutKind and m_sampleCount <nl> + int32_t VerWrittenCur ( ) const { return 0x00010002 ; } / / Added m_imageLayoutKind and m_mbCount <nl> int32_t VerReadableCur ( ) const { return 0x00010002 ; } <nl> int32_t VerWeCanReadBack ( ) const { return 0x00010001 ; } <nl> } ; <nl> namespace Microsoft { namespace MSR { namespace CNTK { <nl> double m_expAvgFactor ; <nl> / / Layout ( e . g . CHW ) . <nl> ImageLayoutKind m_imageLayoutKind ; <nl> - / / Sample count , used to compute cumulative moving average . <nl> - size_t m_sampleCount ; <nl> + / / Minibatch count , used to compute cumulative moving average . <nl> + size_t m_mbCount ; <nl> <nl> / / Stores pre - computed on forward pass mean values that are used in gradient computation . <nl> shared_ptr < Matrix < ElemType > > m_saveMean ; <nl>
Updated samples , added ResNet - 50 .
microsoft/CNTK
cc2a836c85e04525817529381ae43f1e1c2a2607
2016-01-12T22:02:43Z
mmm a / tensorflow / contrib / framework / __init__ . py <nl> ppp b / tensorflow / contrib / framework / __init__ . py <nl> <nl> <nl> # # Deprecation <nl> @ @ deprecated <nl> + @ @ deprecated_arg_values <nl> <nl> # # Arg_Scope <nl> @ @ arg_scope <nl> mmm a / tensorflow / contrib / framework / python / framework / __init__ . py <nl> ppp b / tensorflow / contrib / framework / python / framework / __init__ . py <nl> <nl> # pylint : disable = wildcard - import <nl> from tensorflow . contrib . framework . python . framework . checkpoint_utils import * <nl> from tensorflow . contrib . framework . python . framework . deprecation import deprecated <nl> + from tensorflow . contrib . framework . python . framework . deprecation import deprecated_arg_values <nl> from tensorflow . contrib . framework . python . framework . tensor_util import * <nl> mmm a / tensorflow / contrib / framework / python / framework / deprecation . py <nl> ppp b / tensorflow / contrib / framework / python / framework / deprecation . py <nl> <nl> from __future__ import division <nl> from __future__ import print_function <nl> <nl> + import functools <nl> + import inspect <nl> import re <nl> <nl> from tensorflow . python . platform import tf_logging as logging <nl> def _get_qualified_name ( function ) : <nl> return function . __name__ <nl> <nl> <nl> - def _add_deprecation_to_docstring ( doc , date , instructions ) : <nl> + def _add_deprecation_to_docstring ( <nl> + doc , instructions , no_doc_str , suffix_str , notice ) : <nl> " " " Adds a deprecation notice to a docstring . " " " <nl> if not doc : <nl> - lines = [ ' DEPRECATED FUNCTION ' ] <nl> + lines = [ no_doc_str ] <nl> else : <nl> lines = doc . splitlines ( ) <nl> - lines [ 0 ] + = ' ( deprecated ) ' <nl> + lines [ 0 ] + = ' ' + suffix_str <nl> <nl> - notice = [ <nl> - ' ' , <nl> - ' THIS FUNCTION IS DEPRECATED . It will be removed after % s . ' % date , <nl> - ' Instructions for updating : ' , <nl> - ' % s ' % instructions , <nl> - ] <nl> + notice = [ ' ' ] + notice + [ instructions ] <nl> <nl> if len ( lines ) > 1 : <nl> # Make sure that we keep our distance from the main body <nl> if lines [ 1 ] . strip ( ) : <nl> - notice + = [ ' ' ] <nl> + notice . append ( ' ' ) <nl> <nl> - lines = [ lines [ 0 ] ] + notice + lines [ 1 : ] <nl> + lines [ 1 : 1 ] = notice <nl> else : <nl> lines + = notice <nl> <nl> return ' \ n ' . join ( lines ) <nl> <nl> <nl> + def _add_deprecated_function_notice_to_docstring ( doc , date , instructions ) : <nl> + " " " Adds a deprecation notice to a docstring for deprecated functions . " " " <nl> + return _add_deprecation_to_docstring ( <nl> + doc , instructions , <nl> + ' DEPRECATED FUNCTION ' , <nl> + ' ( deprecated ) ' , [ <nl> + ' THIS FUNCTION IS DEPRECATED . It will be removed after % s . ' % date , <nl> + ' Instructions for updating : ' ] ) <nl> + <nl> + <nl> + def _add_deprecated_arg_notice_to_docstring ( doc , date , instructions ) : <nl> + " " " Adds a deprecation notice to a docstring for deprecated arguments . " " " <nl> + return _add_deprecation_to_docstring ( <nl> + doc , instructions , <nl> + ' DEPRECATED FUNCTION ARGUMENTS ' , <nl> + ' ( deprecated arguments ) ' , [ <nl> + ' SOME ARGUMENTS ARE DEPRECATED . ' <nl> + ' They will be removed after % s . ' % date , <nl> + ' Instructions for updating : ' ] ) <nl> + <nl> + <nl> + def _validate_deprecation_args ( date , instructions ) : <nl> + if not date : <nl> + raise ValueError ( ' Tell us what date this will be deprecated ! ' ) <nl> + if not re . match ( r ' 20 \ d \ d - [ 01 ] \ d - [ 0123 ] \ d ' , date ) : <nl> + raise ValueError ( ' Date must be YYYY - MM - DD . ' ) <nl> + if not instructions : <nl> + raise ValueError ( ' Don \ ' t deprecate things without conversion instructions ! ' ) <nl> + <nl> + <nl> + def _validate_callable ( func , decorator_name ) : <nl> + if not hasattr ( func , ' __call__ ' ) : <nl> + raise ValueError ( <nl> + ' % s is not a function . If this is a property , ' <nl> + ' apply @ % s after @ property . ' % ( func , decorator_name ) ) <nl> + <nl> + <nl> def deprecated ( date , instructions ) : <nl> " " " Decorator for marking functions or methods deprecated . <nl> <nl> - This decorator adds a deprecation warning to a function ' s docstring . It has <nl> - the following format : <nl> + This decorator logs a deprecation warning whenever the decorated function is <nl> + called . It has the following format : <nl> <nl> < function > ( from < module > ) is deprecated and will be removed after < date > . <nl> Instructions for updating : <nl> < instructions > <nl> <nl> - whenever the decorated function is called . < function > will include the class <nl> - name if it is a method . <nl> + < function > will include the class name if it is a method . <nl> <nl> It also edits the docstring of the function : ' ( deprecated ) ' is appended <nl> to the first line of the docstring and a deprecation notice is prepended <nl> def deprecated ( date , instructions ) : <nl> Raises : <nl> ValueError : If date is not in ISO 8601 format , or instructions are empty . <nl> " " " <nl> - if not date : <nl> - raise ValueError ( ' Tell us what date this will be deprecated ! ' ) <nl> - if not re . match ( r ' 20 \ d \ d - [ 01 ] \ d - [ 0123 ] \ d ' , date ) : <nl> - raise ValueError ( ' Date must be YYYY - MM - DD . ' ) <nl> - if not instructions : <nl> - raise ValueError ( ' Don \ ' t deprecate things without conversion instructions ! ' ) <nl> + _validate_deprecation_args ( date , instructions ) <nl> <nl> def deprecated_wrapper ( func ) : <nl> " " " Deprecation wrapper . " " " <nl> - if not hasattr ( func , ' __call__ ' ) : <nl> - raise ValueError ( <nl> - ' % s is not a function . ' <nl> - ' If this is a property , apply @ deprecated after @ property . ' % func ) <nl> + _validate_callable ( func , ' deprecated ' ) <nl> + @ functools . wraps ( func ) <nl> + def new_func ( * args , * * kwargs ) : <nl> + logging . warning ( <nl> + ' % s ( from % s ) is deprecated and will be removed after % s . \ n ' <nl> + ' Instructions for updating : \ n % s ' , <nl> + _get_qualified_name ( func ) , func . __module__ , date , instructions ) <nl> + return func ( * args , * * kwargs ) <nl> + new_func . __doc__ = _add_deprecated_function_notice_to_docstring ( <nl> + func . __doc__ , date , instructions ) <nl> + return new_func <nl> + return deprecated_wrapper <nl> + <nl> + <nl> + def deprecated_arg_values ( date , instructions , * * deprecated_kwargs ) : <nl> + " " " Decorator for marking specific function argument values as deprecated . <nl> + <nl> + This decorator logs a deprecation warning whenever the decorated function is <nl> + called with the deprecated argument values . It has the following format : <nl> + <nl> + Calling < function > ( from < module > ) with < arg > = < value > is deprecated and <nl> + will be removed after < date > . Instructions for updating : <nl> + < instructions > <nl> + <nl> + < function > will include the class name if it is a method . <nl> + <nl> + It also edits the docstring of the function : ' ( deprecated arguments ) ' is <nl> + appended to the first line of the docstring and a deprecation notice is <nl> + prepended to the rest of the docstring . <nl> + <nl> + Args : <nl> + date : String . The date the function is scheduled to be removed . Must be <nl> + ISO 8601 ( YYYY - MM - DD ) . <nl> + instructions : String . Instructions on how to update code using the <nl> + deprecated function . <nl> + * * deprecated_kwargs : The deprecated argument values . <nl> + <nl> + Returns : <nl> + Decorated function or method . <nl> + <nl> + Raises : <nl> + ValueError : If date is not in ISO 8601 format , or instructions are empty . <nl> + " " " <nl> + _validate_deprecation_args ( date , instructions ) <nl> + if not deprecated_kwargs : <nl> + raise ValueError ( ' Specify which argument values are deprecated . ' ) <nl> + <nl> + def deprecated_wrapper ( func ) : <nl> + " " " Deprecation decorator . " " " <nl> + _validate_callable ( func , ' deprecated_arg_values ' ) <nl> + @ functools . wraps ( func ) <nl> def new_func ( * args , * * kwargs ) : <nl> - logging . warning ( ' % s ( from % s ) is deprecated and will be removed after % s . ' <nl> - ' \ nInstructions for updating : \ n % s ' , <nl> - _get_qualified_name ( func ) , func . __module__ , <nl> - date , instructions ) <nl> + " " " Deprecation wrapper . " " " <nl> + named_args = inspect . getcallargs ( func , * args , * * kwargs ) <nl> + for arg_name , arg_value in deprecated_kwargs . items ( ) : <nl> + if arg_name in named_args and named_args [ arg_name ] = = arg_value : <nl> + logging . warning ( <nl> + ' Calling % s ( from % s ) with % s = % s is deprecated and will be ' <nl> + ' removed after % s . \ nInstructions for updating : \ n % s ' , <nl> + _get_qualified_name ( func ) , func . __module__ , <nl> + arg_name , arg_value , date , instructions ) <nl> return func ( * args , * * kwargs ) <nl> - new_func . __name__ = func . __name__ <nl> - new_func . __doc__ = _add_deprecation_to_docstring ( func . __doc__ , date , <nl> - instructions ) <nl> - new_func . __dict__ . update ( func . __dict__ ) <nl> + new_func . __doc__ = _add_deprecated_arg_notice_to_docstring ( <nl> + func . __doc__ , date , instructions ) <nl> return new_func <nl> return deprecated_wrapper <nl> mmm a / tensorflow / contrib / framework / python / framework / deprecation_test . py <nl> ppp b / tensorflow / contrib / framework / python / framework / deprecation_test . py <nl> def _fn ( arg0 , arg1 ) : <nl> <nl> Args : <nl> arg0 : Arg 0 . <nl> - arg1 : Arg 0 . <nl> + arg1 : Arg 1 . <nl> <nl> Returns : <nl> Sum of args . <nl> def _fn ( arg0 , arg1 ) : <nl> " \ n " <nl> " \ n Args : " <nl> " \ n arg0 : Arg 0 . " <nl> - " \ n arg1 : Arg 0 . " <nl> + " \ n arg1 : Arg 1 . " <nl> " \ n " <nl> " \ n Returns : " <nl> " \ n Sum of args . " <nl> " \ n " % ( date , instructions ) , <nl> _fn . __doc__ ) <nl> - self . assertEqual ( { } , _fn . __dict__ ) <nl> + <nl> + # Assert calling new fn issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> + self . assertEqual ( 1 , mock_warning . call_count ) <nl> + ( args , _ ) = mock_warning . call_args <nl> + self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> + self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> + <nl> + @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> + def test_static_fn_with_one_line_doc ( self , mock_warning ) : <nl> + date = " 2016 - 07 - 04 " <nl> + instructions = " This is how you update . . . " <nl> + <nl> + @ deprecation . deprecated ( date , instructions ) <nl> + def _fn ( arg0 , arg1 ) : <nl> + " " " fn doc . " " " <nl> + return arg0 + arg1 <nl> + <nl> + # Assert function docs are properly updated . <nl> + self . assertEqual ( " _fn " , _fn . __name__ ) <nl> + self . assertEqual ( <nl> + " fn doc . ( deprecated ) " <nl> + " \ n " <nl> + " \ nTHIS FUNCTION IS DEPRECATED . It will be removed after % s . " <nl> + " \ nInstructions for updating : \ n % s " % ( date , instructions ) , <nl> + _fn . __doc__ ) <nl> <nl> # Assert calling new fn issues log warning . <nl> self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> def _fn ( arg0 , arg1 ) : <nl> " \ nInstructions for updating : " <nl> " \ n % s " % ( date , instructions ) , <nl> _fn . __doc__ ) <nl> - self . assertEqual ( { } , _fn . __dict__ ) <nl> <nl> # Assert calling new fn issues log warning . <nl> self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> def _fn ( self , arg0 , arg1 ) : <nl> <nl> Args : <nl> arg0 : Arg 0 . <nl> - arg1 : Arg 0 . <nl> + arg1 : Arg 1 . <nl> <nl> Returns : <nl> Sum of args . <nl> def _fn ( self , arg0 , arg1 ) : <nl> " \ n " <nl> " \ n Args : " <nl> " \ n arg0 : Arg 0 . " <nl> - " \ n arg1 : Arg 0 . " <nl> + " \ n arg1 : Arg 1 . " <nl> " \ n " <nl> " \ n Returns : " <nl> " \ n Sum of args . " <nl> def _fn ( self , arg0 , arg1 ) : <nl> self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> <nl> + @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> + def test_instance_fn_with_one_line_doc ( self , mock_warning ) : <nl> + date = " 2016 - 07 - 04 " <nl> + instructions = " This is how you update . . . " <nl> + <nl> + class _Object ( object ) : <nl> + <nl> + def __init ( self ) : <nl> + pass <nl> + <nl> + @ deprecation . deprecated ( date , instructions ) <nl> + def _fn ( self , arg0 , arg1 ) : <nl> + " " " fn doc . " " " <nl> + return arg0 + arg1 <nl> + <nl> + # Assert function docs are properly updated . <nl> + self . assertEqual ( <nl> + " fn doc . ( deprecated ) " <nl> + " \ n " <nl> + " \ nTHIS FUNCTION IS DEPRECATED . It will be removed after % s . " <nl> + " \ nInstructions for updating : \ n % s " % ( date , instructions ) , <nl> + getattr ( _Object , " _fn " ) . __doc__ ) <nl> + <nl> + # Assert calling new fn issues log warning . <nl> + self . assertEqual ( 3 , _Object ( ) . _fn ( 1 , 2 ) ) <nl> + self . assertEqual ( 1 , mock_warning . call_count ) <nl> + ( args , _ ) = mock_warning . call_args <nl> + self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> + self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> + <nl> @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> def test_instance_fn_no_doc ( self , mock_warning ) : <nl> date = " 2016 - 07 - 04 " <nl> def _prop ( self ) : <nl> self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> <nl> <nl> + class DeprecatedArgsTest ( tf . test . TestCase ) : <nl> + <nl> + def _assert_subset ( self , expected_subset , actual_set ) : <nl> + self . assertTrue ( <nl> + actual_set . issuperset ( expected_subset ) , <nl> + msg = " % s is not a superset of % s . " % ( actual_set , expected_subset ) ) <nl> + <nl> + def test_deprecated_illegal_args ( self ) : <nl> + instructions = " This is how you update . . . " <nl> + with self . assertRaisesRegexp ( ValueError , " date " ) : <nl> + deprecation . deprecated_arg_values ( <nl> + None , instructions , deprecated = True ) <nl> + with self . assertRaisesRegexp ( ValueError , " date " ) : <nl> + deprecation . deprecated_arg_values ( <nl> + " " , instructions , deprecated = True ) <nl> + with self . assertRaisesRegexp ( ValueError , " YYYY - MM - DD " ) : <nl> + deprecation . deprecated_arg_values ( <nl> + " 07 - 04 - 2016 " , instructions , deprecated = True ) <nl> + date = " 2016 - 07 - 04 " <nl> + with self . assertRaisesRegexp ( ValueError , " instructions " ) : <nl> + deprecation . deprecated_arg_values ( <nl> + date , None , deprecated = True ) <nl> + with self . assertRaisesRegexp ( ValueError , " instructions " ) : <nl> + deprecation . deprecated_arg_values ( <nl> + date , " " , deprecated = True ) <nl> + with self . assertRaisesRegexp ( ValueError , " argument " , deprecated = True ) : <nl> + deprecation . deprecated_arg_values ( <nl> + date , instructions ) <nl> + <nl> + @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> + def test_static_fn_with_doc ( self , mock_warning ) : <nl> + date = " 2016 - 07 - 04 " <nl> + instructions = " This is how you update . . . " <nl> + <nl> + @ deprecation . deprecated_arg_values ( date , instructions , deprecated = True ) <nl> + def _fn ( arg0 , arg1 , deprecated = True ) : <nl> + " " " fn doc . <nl> + <nl> + Args : <nl> + arg0 : Arg 0 . <nl> + arg1 : Arg 1 . <nl> + deprecated : Deprecated ! <nl> + <nl> + Returns : <nl> + Sum of args . <nl> + " " " <nl> + return arg0 + arg1 if deprecated else arg1 + arg0 <nl> + <nl> + # Assert function docs are properly updated . <nl> + self . assertEqual ( " _fn " , _fn . __name__ ) <nl> + self . assertEqual ( <nl> + " fn doc . ( deprecated arguments ) " <nl> + " \ n " <nl> + " \ nSOME ARGUMENTS ARE DEPRECATED . They will be removed after % s . " <nl> + " \ nInstructions for updating : \ n % s " <nl> + " \ n " <nl> + " \ n Args : " <nl> + " \ n arg0 : Arg 0 . " <nl> + " \ n arg1 : Arg 1 . " <nl> + " \ n deprecated : Deprecated ! " <nl> + " \ n " <nl> + " \ n Returns : " <nl> + " \ n Sum of args . " <nl> + " \ n " % ( date , instructions ) , <nl> + _fn . __doc__ ) <nl> + <nl> + # Assert calling new fn with non - deprecated value logs nothing . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = False ) ) <nl> + self . assertEqual ( 0 , mock_warning . call_count ) <nl> + <nl> + # Assert calling new fn with deprecated value issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = True ) ) <nl> + self . assertEqual ( 1 , mock_warning . call_count ) <nl> + ( args , _ ) = mock_warning . call_args <nl> + self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> + self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> + <nl> + # Assert calling new fn with default deprecated value issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> + self . assertEqual ( 2 , mock_warning . call_count ) <nl> + <nl> + @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> + def test_static_fn_with_one_line_doc ( self , mock_warning ) : <nl> + date = " 2016 - 07 - 04 " <nl> + instructions = " This is how you update . . . " <nl> + <nl> + @ deprecation . deprecated_arg_values ( date , instructions , deprecated = True ) <nl> + def _fn ( arg0 , arg1 , deprecated = True ) : <nl> + " " " fn doc . " " " <nl> + return arg0 + arg1 if deprecated else arg1 + arg0 <nl> + <nl> + # Assert function docs are properly updated . <nl> + self . assertEqual ( " _fn " , _fn . __name__ ) <nl> + self . assertEqual ( <nl> + " fn doc . ( deprecated arguments ) " <nl> + " \ n " <nl> + " \ nSOME ARGUMENTS ARE DEPRECATED . They will be removed after % s . " <nl> + " \ nInstructions for updating : \ n % s " % ( date , instructions ) , <nl> + _fn . __doc__ ) <nl> + <nl> + # Assert calling new fn with non - deprecated value logs nothing . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = False ) ) <nl> + self . assertEqual ( 0 , mock_warning . call_count ) <nl> + <nl> + # Assert calling new fn with deprecated value issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = True ) ) <nl> + self . assertEqual ( 1 , mock_warning . call_count ) <nl> + ( args , _ ) = mock_warning . call_args <nl> + self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> + self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> + <nl> + # Assert calling new fn with default deprecated value issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> + self . assertEqual ( 2 , mock_warning . call_count ) <nl> + <nl> + @ tf . test . mock . patch . object ( logging , " warning " , autospec = True ) <nl> + def test_static_fn_no_doc ( self , mock_warning ) : <nl> + date = " 2016 - 07 - 04 " <nl> + instructions = " This is how you update . . . " <nl> + <nl> + @ deprecation . deprecated_arg_values ( date , instructions , deprecated = True ) <nl> + def _fn ( arg0 , arg1 , deprecated = True ) : <nl> + return arg0 + arg1 if deprecated else arg1 + arg0 <nl> + <nl> + # Assert function docs are properly updated . <nl> + self . assertEqual ( " _fn " , _fn . __name__ ) <nl> + self . assertEqual ( <nl> + " DEPRECATED FUNCTION ARGUMENTS " <nl> + " \ n " <nl> + " \ nSOME ARGUMENTS ARE DEPRECATED . They will be removed after % s . " <nl> + " \ nInstructions for updating : " <nl> + " \ n % s " % ( date , instructions ) , <nl> + _fn . __doc__ ) <nl> + <nl> + # Assert calling new fn with non - deprecated value logs nothing . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = False ) ) <nl> + self . assertEqual ( 0 , mock_warning . call_count ) <nl> + <nl> + # Assert calling new fn issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 , deprecated = True ) ) <nl> + self . assertEqual ( 1 , mock_warning . call_count ) <nl> + ( args , _ ) = mock_warning . call_args <nl> + self . assertRegexpMatches ( args [ 0 ] , r " deprecated and will be removed after " ) <nl> + self . _assert_subset ( set ( [ date , instructions ] ) , set ( args [ 1 : ] ) ) <nl> + <nl> + # Assert calling new fn with default deprecated value issues log warning . <nl> + self . assertEqual ( 3 , _fn ( 1 , 2 ) ) <nl> + self . assertEqual ( 2 , mock_warning . call_count ) <nl> + <nl> + <nl> if __name__ = = " __main__ " : <nl> tf . test . main ( ) <nl>
Add a new deprecation decorator for marking specific function argument values
tensorflow/tensorflow
22c28f0aa2e1db6fe6dbcd584c711fedd4792240
2016-08-03T18:03:13Z
mmm a / hphp / hhbbc / test / type - system . cpp <nl> ppp b / hphp / hhbbc / test / type - system . cpp <nl> std : : unique_ptr < php : : Program > make_program ( ) { <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - auto const test_empty_array = folly : : lazy ( [ & ] { <nl> + auto const test_empty_array = folly : : lazy ( [ ] { <nl> return staticEmptyArray ( ) ; <nl> } ) ; <nl> <nl> - auto const test_array_map_value = folly : : lazy ( [ & ] { <nl> + auto const test_array_map_value = folly : : lazy ( [ ] { <nl> auto ar = make_map_array ( <nl> s_A . get ( ) , s_B . get ( ) , <nl> s_test . get ( ) , 12 <nl> auto const test_array_map_value = folly : : lazy ( [ & ] { <nl> return ArrayData : : GetScalarArray ( ar . get ( ) ) ; <nl> } ) ; <nl> <nl> - auto const test_array_packed_value = folly : : lazy ( [ & ] { <nl> + auto const test_array_packed_value = folly : : lazy ( [ ] { <nl> auto ar = make_packed_array ( <nl> 42 , <nl> 23 , <nl> auto const test_array_packed_value = folly : : lazy ( [ & ] { <nl> return ArrayData : : GetScalarArray ( ar . get ( ) ) ; <nl> } ) ; <nl> <nl> - auto const test_array_packed_value2 = folly : : lazy ( [ & ] { <nl> + auto const test_array_packed_value2 = folly : : lazy ( [ ] { <nl> auto ar = make_packed_array ( <nl> 42 , <nl> 23 . 0 , <nl> auto const test_array_packed_value2 = folly : : lazy ( [ & ] { <nl> return ArrayData : : GetScalarArray ( ar . get ( ) ) ; <nl> } ) ; <nl> <nl> - auto const test_array_packed_value3 = folly : : lazy ( [ & ] { <nl> + auto const test_array_packed_value3 = folly : : lazy ( [ ] { <nl> auto ar = make_packed_array ( <nl> 1 , <nl> 2 , <nl> auto const test_array_packed_value3 = folly : : lazy ( [ & ] { <nl> return ArrayData : : GetScalarArray ( ar . get ( ) ) ; <nl> } ) ; <nl> <nl> - auto const with_data = folly : : lazy ( [ & ] { <nl> + auto const with_data = folly : : lazy ( [ ] { <nl> return std : : vector < Type > { <nl> ival ( 2 ) , <nl> dval ( 2 . 0 ) , <nl> auto const non_opt_unions = { <nl> <nl> auto const all_unions = boost : : join ( optionals , non_opt_unions ) ; <nl> <nl> - auto const all = folly : : lazy ( [ & ] { <nl> + auto const all = folly : : lazy ( [ ] { <nl> std : : vector < Type > ret ; <nl> auto const wdata = with_data ( ) ; <nl> ret . insert ( end ( ret ) , begin ( primitives ) , end ( primitives ) ) ; <nl> std : : vector < Type > all_with_waithandles ( const Index & index ) { <nl> return ret ; <nl> } <nl> <nl> - auto const specialized_array_examples = folly : : lazy ( [ & ] { <nl> + auto const specialized_array_examples = folly : : lazy ( [ ] { <nl> auto ret = std : : vector < Type > { } ; <nl> <nl> auto test_map_a = StructMap { } ; <nl>
hphp : placate newer clang regarding non - local lambda expressions
facebook/hhvm
1910321a2d0c52018eef52e069d4acc6e3b4f172
2014-08-07T00:30:22Z
mmm a / tests / nodeos_run_test . py <nl> ppp b / tests / nodeos_run_test . py <nl> def cmdError ( name , code = 0 , exitNow = False ) : <nl> cmdError ( " eos wallet create " ) <nl> errorExit ( " Failed to create wallet % s . " % ( testWalletName ) ) <nl> <nl> + Print ( " Wallet \ " % s \ " password = % s . " % ( testWalletName , testWallet . password . encode ( " utf - 8 " ) ) ) <nl> + <nl> for account in accounts : <nl> Print ( " Importing keys for account % s into wallet % s . " % ( account . name , testWallet . name ) ) <nl> if not walletMgr . importKey ( account , testWallet ) : <nl>
Added printing out wallet password so can continue to use wallet when using - - dont - kill . GH
EOSIO/eos
6b3a4efbc026527ad805a7de813c9aaaac41f66e
2018-04-04T19:16:57Z
mmm a / src / json . hpp <nl> ppp b / src / json . hpp <nl> struct has_mapped_type <nl> std : : is_integral < decltype ( detect ( std : : declval < T > ( ) ) ) > : : value ; <nl> } ; <nl> <nl> + template < typename T > <nl> + struct has_key_type <nl> + { <nl> + private : <nl> + template < typename U , typename = typename U : : key_type > <nl> + static int detect ( U & & ) ; <nl> + <nl> + static void detect ( . . . ) ; <nl> + public : <nl> + static constexpr bool value = <nl> + std : : is_integral < decltype ( detect ( std : : declval < T > ( ) ) ) > : : value ; <nl> + } ; <nl> + <nl> + template < typename T > <nl> + struct has_value_type <nl> + { <nl> + private : <nl> + template < typename U , typename = typename U : : value_type > <nl> + static int detect ( U & & ) ; <nl> + <nl> + static void detect ( . . . ) ; <nl> + public : <nl> + static constexpr bool value = <nl> + std : : is_integral < decltype ( detect ( std : : declval < T > ( ) ) ) > : : value ; <nl> + } ; <nl> + <nl> + template < bool B , class RealType , class CompatibleObjectType > <nl> + struct is_compatible_object_type_impl : std : : false_type { } ; <nl> + <nl> + template < class RealType , class CompatibleObjectType > <nl> + struct is_compatible_object_type_impl < true , RealType , CompatibleObjectType > <nl> + { <nl> + static constexpr auto value = <nl> + std : : is_constructible < typename RealType : : key_type , typename CompatibleObjectType : : key_type > : : value and <nl> + std : : is_constructible < typename RealType : : mapped_type , typename CompatibleObjectType : : mapped_type > : : value ; <nl> + } ; <nl> + <nl> + template < class RealType , class CompatibleObjectType , typename = enable_if_t < has_mapped_type < CompatibleObjectType > : : value and has_key_type < CompatibleObjectType > : : value > > <nl> + struct is_compatible_object_type <nl> + { <nl> + static auto constexpr value = is_compatible_object_type_impl < has_mapped_type < CompatibleObjectType > : : value and has_key_type < CompatibleObjectType > : : value , RealType , CompatibleObjectType > : : value ; <nl> + } ; <nl> + <nl> + template < bool B , class BasicJson , class CompatibleArrayType > <nl> + struct is_compatible_array_type_impl : std : : false_type { } ; <nl> + <nl> + template < class BasicJson , class CompatibleArrayType > <nl> + struct is_compatible_array_type_impl < true , BasicJson , CompatibleArrayType > <nl> + { <nl> + static constexpr auto value = <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : iterator > : : value and <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : const_iterator > : : value and <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : reverse_iterator > : : value and <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : const_reverse_iterator > : : value and <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : array_t : : iterator > : : value and <nl> + not std : : is_same < CompatibleArrayType , typename BasicJson : : array_t : : const_iterator > : : value and <nl> + std : : is_constructible < BasicJson , typename CompatibleArrayType : : value_type > : : value ; <nl> + <nl> + } ; <nl> + <nl> + template < class BasicJson , class CompatibleArrayType > <nl> + struct is_compatible_array_type <nl> + { <nl> + static auto constexpr value = is_compatible_array_type_impl < has_value_type < CompatibleArrayType > : : value , BasicJson , CompatibleArrayType > : : value ; <nl> + } ; <nl> + <nl> + template < typename RealIntegerType , typename CompatibleNumberIntegerType > <nl> + struct is_compatible_integer_type <nl> + { <nl> + static constexpr auto value = <nl> + std : : is_constructible < RealIntegerType , CompatibleNumberIntegerType > : : value and <nl> + std : : numeric_limits < CompatibleNumberIntegerType > : : is_integer and <nl> + std : : numeric_limits < CompatibleNumberIntegerType > : : is_signed ; <nl> + } ; <nl> + <nl> + template < typename RealInteger , typename CompatibleNumberUnsignedType > <nl> + struct is_compatible_unsigned_integer_type <nl> + { <nl> + static constexpr auto value = std : : is_constructible < RealInteger , CompatibleNumberUnsignedType > : : value and <nl> + std : : numeric_limits < CompatibleNumberUnsignedType > : : is_integer and <nl> + not std : : numeric_limits < CompatibleNumberUnsignedType > : : is_signed ; <nl> + } ; <nl> + <nl> + template < typename RealFloat , typename CompatibleFloat > <nl> + struct is_compatible_float_type <nl> + { <nl> + static constexpr auto value = std : : is_constructible < RealFloat , CompatibleFloat > : : value and <nl> + std : : is_floating_point < CompatibleFloat > : : value ; <nl> + } ; <nl> + <nl> template < template < typename , typename > class JSONSerializer , typename Json , <nl> typename T > <nl> struct has_from_json <nl> class basic_json <nl> BooleanType , NumberIntegerType , NumberUnsignedType , NumberFloatType , <nl> AllocatorType > ; <nl> <nl> + template < template < typename . . . > class T > <nl> + struct wrapper { } ; <nl> + <nl> + using supported_tpl_types = std : : tuple < wrapper < ObjectType > , wrapper < ArrayType > , wrapper < AllocatorType > , wrapper < JSONSerializer > > ; <nl> + <nl> public : <nl> / / forward declarations <nl> template < typename U > class iter_impl ; <nl> class basic_json <nl> <nl> @ since version 1 . 0 . 0 <nl> * / <nl> - template < class CompatibleObjectType , typename std : : enable_if < <nl> - std : : is_constructible < typename object_t : : key_type , typename CompatibleObjectType : : key_type > : : value and <nl> - std : : is_constructible < basic_json , typename CompatibleObjectType : : mapped_type > : : value , int > : : type = 0 > <nl> + template < class CompatibleObjectType , enable_if_t < detail : : is_compatible_object_type < object_t , CompatibleObjectType > : : value , int > = 0 > <nl> basic_json ( const CompatibleObjectType & val ) <nl> : m_type ( value_t : : object ) <nl> { <nl> class basic_json <nl> <nl> @ since version 1 . 0 . 0 <nl> * / <nl> - template < class CompatibleArrayType , typename std : : enable_if < <nl> - not std : : is_same < CompatibleArrayType , typename basic_json_t : : iterator > : : value and <nl> - not std : : is_same < CompatibleArrayType , typename basic_json_t : : const_iterator > : : value and <nl> - not std : : is_same < CompatibleArrayType , typename basic_json_t : : reverse_iterator > : : value and <nl> - not std : : is_same < CompatibleArrayType , typename basic_json_t : : const_reverse_iterator > : : value and <nl> - not std : : is_same < CompatibleArrayType , typename array_t : : iterator > : : value and <nl> - not std : : is_same < CompatibleArrayType , typename array_t : : const_iterator > : : value and <nl> - std : : is_constructible < basic_json , typename CompatibleArrayType : : value_type > : : value , int > : : type = 0 > <nl> + template < class CompatibleArrayType , enable_if_t < detail : : is_compatible_array_type < basic_json_t , CompatibleArrayType > : : value , int > = 0 > <nl> basic_json ( const CompatibleArrayType & val ) <nl> : m_type ( value_t : : array ) <nl> { <nl> class basic_json <nl> <nl> @ since version 1 . 0 . 0 <nl> * / <nl> - template < typename CompatibleNumberIntegerType , typename std : : enable_if < <nl> - std : : is_constructible < number_integer_t , CompatibleNumberIntegerType > : : value and <nl> - std : : numeric_limits < CompatibleNumberIntegerType > : : is_integer and <nl> - std : : numeric_limits < CompatibleNumberIntegerType > : : is_signed , <nl> - CompatibleNumberIntegerType > : : type = 0 > <nl> + template < typename CompatibleNumberIntegerType , enable_if_t < detail : : is_compatible_integer_type < number_integer_t , CompatibleNumberIntegerType > : : value , int > = 0 > <nl> basic_json ( const CompatibleNumberIntegerType val ) noexcept <nl> : m_type ( value_t : : number_integer ) , <nl> m_value ( static_cast < number_integer_t > ( val ) ) <nl> class basic_json <nl> <nl> @ since version 2 . 0 . 0 <nl> * / <nl> - template < typename CompatibleNumberUnsignedType , typename std : : enable_if < <nl> - std : : is_constructible < number_unsigned_t , CompatibleNumberUnsignedType > : : value and <nl> - std : : numeric_limits < CompatibleNumberUnsignedType > : : is_integer and <nl> - not std : : numeric_limits < CompatibleNumberUnsignedType > : : is_signed , <nl> - CompatibleNumberUnsignedType > : : type = 0 > <nl> + template < typename CompatibleNumberUnsignedType , enable_if_t < detail : : is_compatible_unsigned_integer_type < number_unsigned_t , CompatibleNumberUnsignedType > : : value , int > = 0 > <nl> basic_json ( const CompatibleNumberUnsignedType val ) noexcept <nl> : m_type ( value_t : : number_unsigned ) , <nl> m_value ( static_cast < number_unsigned_t > ( val ) ) <nl> class basic_json <nl> <nl> @ since version 1 . 0 . 0 <nl> * / <nl> - template < typename CompatibleNumberFloatType , typename = typename std : : enable_if < <nl> - std : : is_constructible < number_float_t , CompatibleNumberFloatType > : : value and <nl> - std : : is_floating_point < CompatibleNumberFloatType > : : value > : : type > <nl> + template < typename CompatibleNumberFloatType , enable_if_t < detail : : is_compatible_float_type < number_float_t , CompatibleNumberFloatType > : : value , int > = 0 > <nl> basic_json ( const CompatibleNumberFloatType val ) noexcept <nl> : basic_json ( number_float_t ( val ) ) <nl> { <nl> mmm a / test / src / unit - udt . cpp <nl> ppp b / test / src / unit - udt . cpp <nl> <nl> / * <nl> __ _____ _____ _____ <nl> __ | | __ | | | | JSON for Modern C + + ( test suite ) <nl> - | | | __ | | | | | | version 2 . 0 . 5 <nl> + | | | __ | | | | | | version 2 . 0 . 7 <nl> | _____ | _____ | _____ | _ | ___ | https : / / github . com / nlohmann / json <nl> <nl> Licensed under the MIT License < http : / / opensource . org / licenses / MIT > . <nl> TEST_CASE ( " from_json free function " , " [ udt ] " ) <nl> <nl> / / custom serializer , uses adl by default <nl> template < typename T , typename = void > <nl> - struct my_serializer ; <nl> - <nl> - template < > <nl> - struct my_serializer < udt : : pod_type > <nl> + struct my_serializer <nl> { <nl> template < typename Json > <nl> - static void from_json ( Json const & j , udt : : pod_type & val ) <nl> + static void from_json ( Json const & j , T & val ) <nl> { <nl> nlohmann : : from_json ( j , val ) ; <nl> } <nl> <nl> template < typename Json > <nl> - static void to_json ( Json & j , udt : : pod_type const & val ) <nl> + static void to_json ( Json & j , T const & val ) <nl> { <nl> nlohmann : : to_json ( j , val ) ; <nl> } <nl> } ; <nl> <nl> - using my_json = nlohmann : : basic_json < std : : map , std : : vector , std : : string , bool , <nl> + / * using my_json = nlohmann : : basic_json < std : : map , std : : vector , std : : string , bool , <nl> std : : int64_t , std : : uint64_t , double , <nl> std : : allocator , my_serializer > ; <nl> <nl> namespace udt <nl> <nl> TEST_CASE ( " custom serializer " ) <nl> { <nl> - <nl> - <nl> SECTION ( " default use works like default serializer " ) <nl> { <nl> udt : : pod_type pod { 1 , 2 , 3 } ; <nl> TEST_CASE ( " custom serializer " ) <nl> CHECK ( pod2 = = pod ) ; <nl> } <nl> } <nl> + * / <nl>
add is_compatible_ * traits
nlohmann/json
23bd2bce358230ea4d52aca35bbe328692256e83
2017-01-21T15:14:21Z
mmm a / CHANGES <nl> ppp b / CHANGES <nl> <nl> + Changes for 1 . 1 . 0 : <nl> + <nl> + * New feature : type - parameterized tests . <nl> + * New feature : exception assertions . <nl> + * New feature : printing elapsed time of tests . <nl> + * Improved the robustness of death tests . <nl> + * Added an Xcode project and samples . <nl> + * Adjusted the output format on Windows to be understandable by Visual Studio . <nl> + * Minor bug fixes . <nl> + <nl> Changes for 1 . 0 . 1 : <nl> <nl> * Added project files for Visual Studio 7 . 1 . <nl> mmm a / configure . ac <nl> ppp b / configure . ac <nl> <nl> # " [ 1 . 0 . 1 ] " ) . It also asumes that there won ' t be any closing parenthesis <nl> # between " AC_INIT ( " and the closing " ) " including comments and strings . <nl> AC_INIT ( [ Google C + + Testing Framework ] , <nl> - [ 1 . 0 . 1 ] , <nl> + [ 1 . 1 . 0 ] , <nl> [ googletestframework @ googlegroups . com ] , <nl> [ gtest ] ) <nl> <nl>
Prepares gtest for release 1 . 1 . 0 .
google/googletest
9e672bd5e303a9803fa5135c3c9f0122efa4c6bb
2008-09-16T23:48:19Z
mmm a / lib / AST / Mangle . cpp <nl> ppp b / lib / AST / Mangle . cpp <nl> void Mangler : : mangleContext ( const DeclContext * ctx , BindGenerics shouldBind ) { <nl> <nl> auto decl = ExtTy - > getAnyNominal ( ) ; <nl> assert ( decl & & " extension of non - nominal type ? " ) ; <nl> - / / Mangle the module name if extension is defined in a different module from <nl> - / / the actual nominal type decl . <nl> - if ( ExtD - > getParentModule ( ) ! = decl - > getParentModule ( ) ) { <nl> - Buffer < < ' E ' ; <nl> + / / Mangle the module name if : <nl> + / / - the extension is defined in a different module from the actual nominal <nl> + / / type decl , <nl> + / / - the extension is constrained , or <nl> + / / - the extension is to a protocol . <nl> + / / FIXME : In a world where protocol extensions are dynamically dispatched , <nl> + / / " extension is to a protocol " would no longer be a reason to use the <nl> + / / extension mangling , because an extension method implementation could be <nl> + / / resiliently moved into the original protocol itself . <nl> + if ( ExtD - > getParentModule ( ) ! = decl - > getParentModule ( ) <nl> + | | ExtD - > isConstrainedExtension ( ) <nl> + | | ExtD - > getDeclaredInterfaceType ( ) - > isExistentialType ( ) ) { <nl> + if ( auto sig = ExtD - > getGenericSignature ( ) ) { <nl> + Buffer < < ' e ' ; <nl> + Mod = ExtD - > getModuleContext ( ) ; <nl> + mangleGenericSignature ( sig , ResilienceExpansion : : Minimal ) ; <nl> + } else { <nl> + Buffer < < ' E ' ; <nl> + } <nl> mangleModule ( ExtD - > getParentModule ( ) ) ; <nl> } <nl> mangleNominalType ( decl , ResilienceExpansion : : Minimal , shouldBind , <nl> mmm a / lib / Basic / Demangle . cpp <nl> ppp b / lib / Basic / Demangle . cpp <nl> class Demangler { <nl> NodePointer demangleContext ( ) { <nl> / / context : : = module <nl> / / context : : = entity <nl> - / / context : : = E module ( extension defined in a different module ) <nl> + / / context : : = ' E ' module context ( extension defined in a different module ) <nl> + / / context : : = ' e ' generic - signature module context ( generic extension ) <nl> if ( ! Mangled ) return nullptr ; <nl> if ( Mangled . nextIf ( ' E ' ) ) { <nl> NodePointer ext = NodeFactory : : create ( Node : : Kind : : Extension ) ; <nl> class Demangler { <nl> ext - > addChild ( type ) ; <nl> return ext ; <nl> } <nl> + if ( Mangled . nextIf ( ' e ' ) ) { <nl> + NodePointer ext = NodeFactory : : create ( Node : : Kind : : Extension ) ; <nl> + NodePointer sig = demangleGenericSignature ( ) ; <nl> + / / The generic context is currently re - specified by the type mangling . <nl> + / / If we ever remove ' self ' from manglings , we should stop resetting the <nl> + / / context here . <nl> + resetGenericContext ( ) ; <nl> + if ( ! sig ) return nullptr ; <nl> + NodePointer def_module = demangleModule ( ) ; <nl> + if ( ! def_module ) return nullptr ; <nl> + NodePointer type = demangleContext ( ) ; <nl> + <nl> + ext - > addChild ( def_module ) ; <nl> + ext - > addChild ( type ) ; <nl> + ext - > addChild ( sig ) ; <nl> + return ext ; <nl> + } <nl> if ( Mangled . nextIf ( ' S ' ) ) <nl> return demangleSubstitutionIndex ( ) ; <nl> if ( isStartOfEntity ( Mangled . peek ( ) ) ) <nl> void NodePrinter : : print ( NodePointer pointer , bool asContext , bool suppressType ) <nl> Printer < < toString ( Directness ( pointer - > getIndex ( ) ) ) < < " " ; <nl> return ; <nl> case Node : : Kind : : Extension : <nl> - assert ( pointer - > getNumChildren ( ) = = 2 & & " Extension expects 2 children . " ) ; <nl> + assert ( ( pointer - > getNumChildren ( ) = = 2 | | pointer - > getNumChildren ( ) = = 3 ) <nl> + & & " Extension expects 2 or 3 children . " ) ; <nl> Printer < < " ext . " ; <nl> / / Print the module where extension is defined . <nl> - print ( pointer - > getChild ( 0 ) , true ) ; <nl> + print ( pointer - > getChild ( 0 ) , true ) ; <nl> Printer < < " . " ; <nl> print ( pointer - > getChild ( 1 ) , asContext ) ; <nl> + if ( pointer - > getNumChildren ( ) = = 3 ) <nl> + print ( pointer - > getChild ( 2 ) , true ) ; <nl> return ; <nl> case Node : : Kind : : Variable : <nl> case Node : : Kind : : Function : <nl> mmm a / lib / Basic / Remangle . cpp <nl> ppp b / lib / Basic / Remangle . cpp <nl> void Remangler : : mangleDeclContext ( Node * node ) { <nl> } <nl> <nl> void Remangler : : mangleExtension ( Node * node , EntityContext & ctx ) { <nl> - Out < < ' E ' ; <nl> - assert ( node - > getNumChildren ( ) = = 2 ) ; <nl> + assert ( node - > getNumChildren ( ) = = 2 | | node - > getNumChildren ( ) = = 3 ) ; <nl> + if ( node - > getNumChildren ( ) = = 3 ) { <nl> + Out < < ' e ' ; <nl> + mangleDependentGenericSignature ( node - > begin ( ) [ 2 ] . get ( ) ) ; / / generic sig <nl> + } else { <nl> + Out < < ' E ' ; <nl> + } <nl> mangleEntityContext ( node - > begin ( ) [ 0 ] . get ( ) , ctx ) ; / / module <nl> mangleEntityContext ( node - > begin ( ) [ 1 ] . get ( ) , ctx ) ; / / context <nl> } <nl> mmm a / test / Demangle / Inputs / manglings . txt <nl> ppp b / test / Demangle / Inputs / manglings . txt <nl> _TTWurGV23interface_type_mangling18GenericTypeContextq__S_18GenericWitnessTestS_ <nl> _TTWurGV23interface_type_mangling18GenericTypeContextq__S_18GenericWitnessTestS_FS1_16twoParamsAtDepthu_0_Rq_S1__fq_FTqd__1yqd_0__T_ mmm > protocol witness for interface_type_mangling . GenericWitnessTest . twoParamsAtDepth < A > < B , C where A : interface_type_mangling . GenericWitnessTest > ( A ) ( B , y : C ) - > ( ) in conformance < A > interface_type_mangling . GenericTypeContext < A > : interface_type_mangling . GenericWitnessTest in interface_type_mangling <nl> _TFC3red11BaseClassEHcfMS0_FzT1aSi_S0_ mmm > red . BaseClassEH . init ( red . BaseClassEH . Type ) ( a : Swift . Int ) throws - > red . BaseClassEH <nl> _TF4red23foofSifT1ySi_FT1zSi_Si mmm > red2 . foo ( Swift . Int ) ( y : Swift . Int ) ( z : Swift . Int ) - > Swift . Int <nl> + _TFeRq_27mangling_generic_extensions8Runcible_S_VS_3Foog1aSi mmm > ext . mangling_generic_extensions . mangling_generic_extensions . Foo < A where A : mangling_generic_extensions . Runcible > . a . getter : Swift . Int <nl> + _TFeRq_27mangling_generic_extensions8Runcible_S_VS_3Foog1bq_ mmm > ext . mangling_generic_extensions . mangling_generic_extensions . Foo < A where A : mangling_generic_extensions . Runcible > . b . getter : A <nl> mmm a / test / SILGen / guaranteed_self . swift <nl> ppp b / test / SILGen / guaranteed_self . swift <nl> func AO_curryThunk < T > ( ao : AO < T > ) - > ( AO < T > - > Int - > ( ) / * , Int - > ( ) * / ) { <nl> / / CHECK : copy_addr [ [ ARG1_PTR ] ] to [ initialization ] [ [ GUARANTEED_COPY_STACK_SLOT ] ] # 1 <nl> / / CHECK : [ [ ARG0 : % . * ] ] = load [ [ ARG0_PTR ] ] <nl> / / CHECK : [ [ GUARANTEED_COPY : % . * ] ] = load [ [ GUARANTEED_COPY_STACK_SLOT ] ] # 1 <nl> - / / CHECK : function_ref guaranteed_self . SequenceDefaultsType . _constrainElement < A where A : guaranteed_self . SequenceDefaultsType > ( A ) ( guaranteed_self . FakeElement ) - > ( ) <nl> + / / CHECK : function_ref ext . guaranteed_self . guaranteed_self . SequenceDefaultsType < A where A : guaranteed_self . SequenceDefaultsType > . _constrainElement < A where A : guaranteed_self . SequenceDefaultsType > ( A ) ( guaranteed_self . FakeElement ) - > ( ) <nl> / / CHECK : [ [ FUN : % . * ] ] = function_ref @ _ { { . * } } <nl> / / CHECK : [ [ TRANSLATION_STACK_SLOT : % . * ] ] = alloc_stack $ FakeArray <nl> / / CHECK : store [ [ GUARANTEED_COPY ] ] to [ [ TRANSLATION_STACK_SLOT : % . * ] ] # 1 <nl> new file mode 100644 <nl> index 000000000000 . . a873e1dc5f95 <nl> mmm / dev / null <nl> ppp b / test / SILGen / mangling_generic_extensions . swift <nl> <nl> + / / RUN : % target - swift - frontend - emit - silgen % s | FileCheck % s <nl> + <nl> + struct Foo < T > { <nl> + } <nl> + <nl> + protocol Runcible { <nl> + typealias Spoon <nl> + typealias Hat <nl> + } <nl> + <nl> + extension Foo { <nl> + / / An unconstrained extension in the same module doesn ' t use the extension <nl> + / / mangling , since the implementation can be resiliently moved into the <nl> + / / definition . <nl> + / / CHECK - LABEL : sil hidden @ _TFV27mangling_generic_extensions3Foog1aSi <nl> + var a : Int { return 0 } <nl> + } <nl> + <nl> + extension Foo where T : Runcible { <nl> + / / A constrained extension always uses the extension mangling . <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runcible_S_VS_3Foog1aSi <nl> + var a : Int { return 0 } <nl> + <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runcible_S_VS_3Foog1bq_ <nl> + var b : T { get { } } <nl> + } <nl> + <nl> + extension Foo where T : Runcible , T . Spoon : Runcible { <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runcibleqq_S0_5SpoonS0__S_VS_3Foog1aSi <nl> + var a : Int { return 0 } <nl> + <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runcibleqq_S0_5SpoonS0__S_VS_3Foog1bq_ <nl> + var b : T { get { } } <nl> + } <nl> + <nl> + / / Protocol extensions always use the extension mangling . <nl> + / / TODO : When default implementations are properly implemented , and protocol <nl> + / / extensions receive dynamic dispatch , it would be possible for an <nl> + / / unconstrained protocol extension method to be moved in or out of its <nl> + / / declaration , so we would no longer want to use the extension mangling <nl> + / / in unconstrained cases . <nl> + extension Runcible { <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runcible_S_S0_5runceuRq_S0__fq_FT_T_ <nl> + func runce ( ) { } <nl> + } <nl> + <nl> + extension Runcible where Self . Spoon = = Self . Hat { <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_27mangling_generic_extensions8Runciblezqq_S0_3Hatqq_S0_5Spoon_S_S0_5runceuRq_S0_zqq_S0_3Hatqq_S0_5Spoon_fq_FT_T_ <nl> + func runce ( ) { } <nl> + } <nl> mmm a / test / SILGen / protocol_extensions . swift <nl> ppp b / test / SILGen / protocol_extensions . swift <nl> public protocol P1 { <nl> } <nl> <nl> extension P1 { <nl> - / / CHECK - LABEL : sil hidden @ _TFP19protocol_extensions2P16extP1auRq_S0__fq_FT_T_ : $ @ convention ( method ) < Self where Self : P1 > ( @ in_guaranteed Self ) - > ( ) { <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_19protocol_extensions2P1_S_S0_6extP1auRq_S0__fq_FT_T_ : $ @ convention ( method ) < Self where Self : P1 > ( @ in_guaranteed Self ) - > ( ) { <nl> / / CHECK - NEXT : bb0 ( [ [ SELF : % [ 0 - 9 ] + ] ] : $ * Self ) : <nl> final func extP1a ( ) { <nl> / / CHECK : [ [ WITNESS : % [ 0 - 9 ] + ] ] = witness_method $ Self , # P1 . reqP1a ! 1 : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > ( ) <nl> extension P1 { <nl> / / CHECK : return <nl> } <nl> <nl> - / / CHECK - LABEL : sil @ _TFP19protocol_extensions2P16extP1buRq_S0__fq_FT_T_ : $ @ convention ( method ) < Self where Self : P1 > ( @ in_guaranteed Self ) - > ( ) { <nl> + / / CHECK - LABEL : sil @ _TFeRq_19protocol_extensions2P1_S_S0_6extP1buRq_S0__fq_FT_T_ : $ @ convention ( method ) < Self where Self : P1 > ( @ in_guaranteed Self ) - > ( ) { <nl> / / CHECK - NEXT : bb0 ( [ [ SELF : % [ 0 - 9 ] + ] ] : $ * Self ) : <nl> public final func extP1b ( ) { <nl> - / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P16extP1auRq_S0__fq_FT_T_ : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > ( ) <nl> + / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_6extP1auRq_S0__fq_FT_T_ : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > ( ) <nl> / / CHECK - NEXT : apply [ [ FN ] ] < Self > ( [ [ SELF ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > ( ) <nl> extP1a ( ) <nl> / / CHECK : return <nl> class D : C { } <nl> / / CHECK - NEXT : bb0 ( [ [ D : % [ 0 - 9 ] + ] ] : $ D ) : <nl> func testD ( d : D ) { <nl> / / CHECK : [ [ D2 : % [ 0 - 9 ] + ] ] = alloc_box $ D <nl> - / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P111returnsSelfuRq_S0__fq_FT_q_ <nl> + / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_11returnsSelfuRq_S0__fq_FT_q_ <nl> / / CHECK : [ [ DCOPY : % [ 0 - 9 ] + ] ] = alloc_stack $ D <nl> / / CHECK : store [ [ D ] ] to [ [ DCOPY ] ] # 1 : $ * D <nl> / / CHECK : [ [ RESULT : % [ 0 - 9 ] + ] ] = alloc_stack $ D <nl> extension P1 { <nl> / / CHECK : bb0 ( [ [ P : % [ 0 - 9 ] + ] ] : $ * P1 , [ [ B : % [ 0 - 9 ] + ] ] : $ Bool , [ [ I : % [ 0 - 9 ] + ] ] : $ Int64 ) : <nl> func testExistentials1 ( p1 : P1 , b : Bool , i : Int64 ) { <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) <nl> - / / CHECK : [ [ F1 : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P12f1uRq_S0__fq_FT_T_ <nl> + / / CHECK : [ [ F1 : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_2f1uRq_S0__fq_FT_T_ <nl> / / CHECK : apply [ [ F1 ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ POPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > ( ) <nl> p1 . f1 ( ) <nl> <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> - / / CHECK : [ [ CURRIED1 : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P18curried1uRq_S0__fq_fSbFVSs5Int64T_ <nl> + / / CHECK : [ [ CURRIED1 : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_8curried1uRq_S0__fq_fSbFVSs5Int64T_ <nl> / / CHECK : [ [ CURRIED1 ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ I ] ] , [ [ B ] ] , [ [ POPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Int64 , Bool , @ in_guaranteed τ_0_0 ) - > ( ) <nl> p1 . curried1 ( b ) ( i ) <nl> <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> / / CHECK : copy_addr [ [ POPENED ] ] to [ initialization ] [ [ POPENED_COPY : % . * ] ] # 1 <nl> - / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1g9subscriptFVSs5Int64Sb <nl> + / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_g9subscriptFVSs5Int64Sb <nl> / / CHECK : apply [ [ GETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ I ] ] , [ [ POPENED_COPY ] ] # 1 ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Int64 , @ in_guaranteed τ_0_0 ) - > Bool <nl> / / CHECK : destroy_addr [ [ POPENED_COPY ] ] # 1 <nl> / / CHECK : store { { . * } } : $ * Bool <nl> func testExistentials1 ( p1 : P1 , b : Bool , i : Int64 ) { <nl> <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> / / CHECK : copy_addr [ [ POPENED ] ] to [ initialization ] [ [ POPENED_COPY : % . * ] ] # 1 <nl> - / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1g4propSb <nl> + / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_g4propSb <nl> / / CHECK : apply [ [ GETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ POPENED_COPY ] ] # 1 ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > Bool <nl> / / CHECK : store { { . * } } : $ * Bool <nl> / / CHECK : dealloc_stack [ [ POPENED_COPY ] ] <nl> func testExistentials2 ( p1 : P1 ) { <nl> / / CHECK : [ [ P1A : % [ 0 - 9 ] + ] ] = alloc_box $ P1 <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> / / CHECK : [ [ P1AINIT : % [ 0 - 9 ] + ] ] = init_existential_addr [ [ P1A ] ] # 1 : $ * P1 , $ @ opened ( [ [ UUID2 : " . * " ] ] ) P1 <nl> - / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P111returnsSelfuRq_S0__fq_FT_q_ <nl> + / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_11returnsSelfuRq_S0__fq_FT_q_ <nl> / / CHECK : apply [ [ FN ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ P1AINIT ] ] , [ [ POPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ out τ_0_0 , @ in_guaranteed τ_0_0 ) - > ( ) <nl> var p1a : P1 = p1 . returnsSelf ( ) <nl> } <nl> func testExistentials2 ( p1 : P1 ) { <nl> func testExistentialsGetters ( p1 : P1 ) { <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> / / CHECK : copy_addr [ [ POPENED ] ] to [ initialization ] [ [ POPENED_COPY : % . * ] ] # 1 <nl> - / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1g5prop2Sb <nl> + / / CHECK : [ [ FN : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_g5prop2Sb <nl> / / CHECK : [ [ B : % [ 0 - 9 ] + ] ] = apply [ [ FN ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ POPENED_COPY ] ] # 1 ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( @ in_guaranteed τ_0_0 ) - > Bool <nl> let b : Bool = p1 . prop2 <nl> <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P ] ] : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> / / CHECK : copy_addr [ [ POPENED ] ] to [ initialization ] [ [ POPENED_COPY : % . * ] ] # 1 <nl> - / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1g9subscriptFSbSb <nl> + / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_g9subscriptFSbSb <nl> / / CHECK : apply [ [ GETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ B ] ] , [ [ POPENED_COPY ] ] # 1 ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , @ in_guaranteed τ_0_0 ) - > Bool <nl> let b2 : Bool = p1 [ b ] <nl> } <nl> func testExistentialSetters ( var p1 : P1 , b : Bool ) { <nl> / / CHECK : [ [ PBOX : % [ 0 - 9 ] + ] ] = alloc_box $ P1 <nl> / / CHECK - NEXT : copy_addr [ take ] [ [ P ] ] to [ initialization ] [ [ PBOX ] ] # 1 : $ * P1 <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ PBOX ] ] # 1 : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> - / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1s5prop2Sb <nl> + / / CHECK : [ [ GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_s5prop2Sb <nl> / / CHECK : apply [ [ GETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ B ] ] , [ [ POPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , @ inout τ_0_0 ) - > ( ) <nl> / / CHECK - NOT : deinit_existential_addr <nl> p1 . prop2 = b <nl> <nl> / / CHECK : [ [ POPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ PBOX ] ] # 1 : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> - / / CHECK : [ [ SUBSETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1s9subscriptFSbSb <nl> + / / CHECK : [ [ SUBSETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_s9subscriptFSbSb <nl> / / CHECK : apply [ [ SUBSETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ B ] ] , [ [ B ] ] , [ [ POPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , Bool , @ inout τ_0_0 ) - > ( ) <nl> / / CHECK - NOT : deinit_existential_addr [ [ PBOX ] ] # 1 : $ * P1 <nl> p1 [ b ] = b <nl> func testLogicalExistentialSetters ( var hasAP1 : HasAP1 , _ b : Bool ) { <nl> / / CHECK : [ [ SOMEP1_GETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFV19protocol_extensions6HasAP1g6someP1PS_2P1_ : $ @ convention ( method ) ( @ out P1 , @ in_guaranteed HasAP1 ) - > ( ) <nl> / / CHECK : [ [ RESULT : % [ 0 - 9 ] + ] ] = apply [ [ SOMEP1_GETTER ] ] ( [ [ P1_COPY ] ] # 1 , % 6 # 1 ) : $ @ convention ( method ) ( @ out P1 , @ in_guaranteed HasAP1 ) - > ( ) <nl> / / CHECK : [ [ P1_OPENED : % [ 0 - 9 ] + ] ] = open_existential_addr [ [ P1_COPY ] ] # 1 : $ * P1 to $ * @ opened ( [ [ UUID : " . * " ] ] ) P1 <nl> - / / CHECK : [ [ PROP2_SETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFP19protocol_extensions2P1s5prop2Sb : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , @ inout τ_0_0 ) - > ( ) <nl> + / / CHECK : [ [ PROP2_SETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFeRq_19protocol_extensions2P1_S_S0_s5prop2Sb : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , @ inout τ_0_0 ) - > ( ) <nl> / / CHECK : apply [ [ PROP2_SETTER ] ] < @ opened ( [ [ UUID ] ] ) P1 > ( [ [ B ] ] , [ [ P1_OPENED ] ] ) : $ @ convention ( method ) < τ_0_0 where τ_0_0 : P1 > ( Bool , @ inout τ_0_0 ) - > ( ) <nl> / / CHECK : [ [ SOMEP1_SETTER : % [ 0 - 9 ] + ] ] = function_ref @ _TFV19protocol_extensions6HasAP1s6someP1PS_2P1_ : $ @ convention ( method ) ( @ in P1 , @ inout HasAP1 ) - > ( ) <nl> / / CHECK : apply [ [ SOMEP1_SETTER ] ] ( [ [ P1_COPY ] ] # 1 , [ [ HASP1_BOX ] ] # 1 ) : $ @ convention ( method ) ( @ in P1 , @ inout HasAP1 ) - > ( ) <nl> protocol InitRequirement { <nl> } <nl> <nl> extension InitRequirement { <nl> - / / CHECK - LABEL : sil hidden @ _TFP19protocol_extensions15InitRequirementCuRq_S0__fMq_FT1dCS_1D_q_ : $ @ convention ( thin ) < Self where Self : InitRequirement > ( @ out Self , @ owned D , @ thick Self . Type ) - > ( ) <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_19protocol_extensions15InitRequirement_S_S0_CuRq_S0__fMq_FT1dCS_1D_q_ : $ @ convention ( thin ) < Self where Self : InitRequirement > ( @ out Self , @ owned D , @ thick Self . Type ) - > ( ) <nl> / / CHECK : bb0 ( [ [ OUT : % . * ] ] : $ * Self , [ [ ARG : % . * ] ] : $ D , [ [ SELF_TYPE : % . * ] ] : $ @ thick Self . Type ) : <nl> init ( d : D ) { <nl> / / CHECK : [ [ DELEGATEE : % . * ] ] = witness_method $ Self , # InitRequirement . init ! allocator . 1 : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : InitRequirement > ( @ out τ_0_0 , @ owned C , @ thick τ_0_0 . Type ) - > ( ) <nl> extension InitRequirement { <nl> self . init ( c : d ) <nl> } <nl> <nl> - / / CHECK - LABEL : sil hidden @ _TFP19protocol_extensions15InitRequirementCuRq_S0__fMq_FT2d2CS_1D_q_ <nl> - / / CHECK : function_ref @ _TFP19protocol_extensions15InitRequirementCuRq_S0__fMq_FT1dCS_1D_q_ <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_19protocol_extensions15InitRequirement_S_S0_CuRq_S0__fMq_FT2d2CS_1D_q_ <nl> + / / CHECK : function_ref @ _TFeRq_19protocol_extensions15InitRequirement_S_S0_CuRq_S0__fMq_FT1dCS_1D_q_ <nl> init ( d2 : D ) { <nl> self . init ( d : d2 ) <nl> } <nl> protocol ClassInitRequirement : class { <nl> } <nl> <nl> extension ClassInitRequirement { <nl> - / / CHECK - LABEL : sil hidden @ _TFP19protocol_extensions20ClassInitRequirementCuRq_S0__fMq_FT1dCS_1D_q_ : $ @ convention ( thin ) < Self where Self : ClassInitRequirement > ( @ owned D , @ thick Self . Type ) - > @ owned Self <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_19protocol_extensions20ClassInitRequirement_S_S0_CuRq_S0__fMq_FT1dCS_1D_q_ : $ @ convention ( thin ) < Self where Self : ClassInitRequirement > ( @ owned D , @ thick Self . Type ) - > @ owned Self <nl> / / CHECK : bb0 ( [ [ ARG : % . * ] ] : $ D , [ [ SELF_TYPE : % . * ] ] : $ @ thick Self . Type ) : <nl> / / CHECK : [ [ DELEGATEE : % . * ] ] = witness_method $ Self , # ClassInitRequirement . init ! allocator . 1 : $ @ convention ( witness_method ) < τ_0_0 where τ_0_0 : ClassInitRequirement > ( @ owned C , @ thick τ_0_0 . Type ) - > @ owned τ_0_0 <nl> / / CHECK : [ [ ARG_UP : % . * ] ] = upcast [ [ ARG ] ] <nl> func foo ( t : ObjCInitRequirement . Type , c : OC ) - > ObjCInitRequirement { <nl> } <nl> <nl> extension ObjCInitRequirement { <nl> - / / CHECK - LABEL : sil hidden @ _TFP19protocol_extensions19ObjCInitRequirementCuRq_S0__fMq_FT1dCS_2OD_q_ : $ @ convention ( thin ) < Self where Self : ObjCInitRequirement > ( @ owned OD , @ thick Self . Type ) - > @ owned Self <nl> + / / CHECK - LABEL : sil hidden @ _TFeRq_19protocol_extensions19ObjCInitRequirement_S_S0_CuRq_S0__fMq_FT1dCS_2OD_q_ : $ @ convention ( thin ) < Self where Self : ObjCInitRequirement > ( @ owned OD , @ thick Self . Type ) - > @ owned Self <nl> / / CHECK : bb0 ( [ [ ARG : % . * ] ] : $ OD , [ [ SELF_TYPE : % . * ] ] : $ @ thick Self . Type ) : <nl> / / CHECK : [ [ OBJC_SELF_TYPE : % . * ] ] = thick_to_objc_metatype [ [ SELF_TYPE ] ] <nl> / / CHECK : [ [ SELF : % . * ] ] = alloc_ref_dynamic [ objc ] [ [ OBJC_SELF_TYPE ] ] : $ @ objc_metatype Self . Type , $ Self <nl> mmm a / test / SILPasses / sil_combine_objc_bridge . sil <nl> ppp b / test / SILPasses / sil_combine_objc_bridge . sil <nl> bb0 ( % 0 : $ AnNSArray ) : <nl> } <nl> <nl> / / CHECK - LABEL : sil shared @ bridge_from_swift_array_to_NSObject_cast <nl> - / / CHECK : function_ref @ _TFE10FoundationSa19_bridgeToObjectiveCurfGSaq__FT_CSo7NSArray <nl> + / / CHECK : function_ref @ _TFer10FoundationSa19_bridgeToObjectiveCurfGSaq__FT_CSo7NSArray <nl> / / CHECK : retain_value <nl> / / CHECK : apply <nl> / / CHECK : release_value <nl> mmm a / test / Serialization / generic_extension . swift <nl> ppp b / test / Serialization / generic_extension . swift <nl> import generic_extension_1 <nl> <nl> [ " a " , " b " , " c " ] . wobble ( ) <nl> <nl> - / / CHECK : sil @ _TFE19generic_extension_1Sa6wobbleurfGSaq__FT_GSqq__ : $ @ convention ( method ) < τ_0_0 > ( @ out Optional < τ_0_0 > , @ guaranteed Array < τ_0_0 > ) - > ( ) <nl> + / / CHECK : sil @ _TFer19generic_extension_1Sa6wobbleurfGSaq__FT_GSqq__ : $ @ convention ( method ) < τ_0_0 > ( @ out Optional < τ_0_0 > , @ guaranteed Array < τ_0_0 > ) - > ( ) <nl>
AST : Mangle the generic params of constrained extensions .
apple/swift
7cb6fa320a3cef9f19f5caf3519ae134ba42b6d7
2015-06-01T21:25:54Z
mmm a / tensorflow / tools / pip_package / setup . py <nl> ppp b / tensorflow / tools / pip_package / setup . py <nl> <nl> <nl> REQUIRED_PACKAGES = [ <nl> ' absl - py ' , <nl> - ' enum34 > = 1 . 1 . 6 ' , <nl> ' numpy > = 1 . 12 . 1 ' , <nl> ' six > = 1 . 10 . 0 ' , <nl> ' protobuf > = 3 . 4 . 0 ' , <nl> <nl> REQUIRED_PACKAGES [ i ] = ' tb - nightly > = 1 . 5 . 0a0 , < 1 . 6 . 0a0 ' <nl> break <nl> <nl> - # weakref . finalize was introduced in Python 3 . 4 <nl> + # weakref . finalize and enum were introduced in Python 3 . 4 <nl> if sys . version_info < ( 3 , 4 ) : <nl> REQUIRED_PACKAGES . append ( ' backports . weakref > = 1 . 0rc1 ' ) <nl> + REQUIRED_PACKAGES . append ( ' enum34 > = 1 . 1 . 6 ' ) <nl> <nl> # pylint : disable = line - too - long <nl> CONSOLE_SCRIPTS = [ <nl>
Only install enum34 on Python < 3 . 4 versions ( )
tensorflow/tensorflow
1fa94d5a5da6849e78ee3b86cb7a5fd6e2d8ba10
2017-12-01T19:20:52Z
mmm a / src / gui / Src / Gui / MainWindow . cpp <nl> ppp b / src / gui / Src / Gui / MainWindow . cpp <nl> MainWindow : : MainWindow ( QWidget * parent ) <nl> makeCommandAction ( ui - > actioneStepInto , " eStepInto " ) ; <nl> makeCommandAction ( ui - > actioneRun , " eRun " ) ; <nl> makeCommandAction ( ui - > actioneRtr , " eRtr " ) ; <nl> - makeCommandAction ( ui - > actionRtu , " rtu " ) ; <nl> + makeCommandAction ( ui - > actionRtu , " TraceIntoConditional ! mod . party ( cip ) " ) ; <nl> connect ( ui - > actionTicnd , SIGNAL ( triggered ( ) ) , this , SLOT ( execTicnd ( ) ) ) ; <nl> connect ( ui - > actionTocnd , SIGNAL ( triggered ( ) ) , this , SLOT ( execTocnd ( ) ) ) ; <nl> connect ( ui - > actionTRBit , SIGNAL ( triggered ( ) ) , this , SLOT ( execTRBit ( ) ) ) ; <nl>
GUI : conditional tracing instead of rtu in run to user code
x64dbg/x64dbg
b1578540a8b531a87d471224f1ca22a8281c6481
2016-09-08T11:01:40Z
similarity index 100 % <nl> rename from jstests / replsets / priority1 . js <nl> rename to jstests / slowNightly / replsets_priority1 . js <nl>
Move slow replica set test to slowNightly directory .
mongodb/mongo
f9d784faf0f8d6178e2f1758d9b36521ca6acbc8
2011-09-07T22:07:29Z
mmm a / src / csharp / Grpc . Core . Tests / Grpc . Core . Tests . csproj <nl> ppp b / src / csharp / Grpc . Core . Tests / Grpc . Core . Tests . csproj <nl> <nl> < Compile Include = " MetadataTest . cs " / > <nl> < Compile Include = " PerformanceTest . cs " / > <nl> < Compile Include = " SanityTest . cs " / > <nl> + < Compile Include = " HalfcloseTest . cs " / > <nl> < / ItemGroup > <nl> < Import Project = " $ ( MSBuildBinPath ) \ Microsoft . CSharp . targets " / > <nl> < ItemGroup > <nl> new file mode 100644 <nl> index 00000000000 . . 7675edb4756 <nl> mmm / dev / null <nl> ppp b / src / csharp / Grpc . Core . Tests / HalfcloseTest . cs <nl> <nl> + # region Copyright notice and license <nl> + <nl> + / / Copyright 2016 , Google Inc . <nl> + / / All rights reserved . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without <nl> + / / modification , are permitted provided that the following conditions are <nl> + / / met : <nl> + / / <nl> + / / * Redistributions of source code must retain the above copyright <nl> + / / notice , this list of conditions and the following disclaimer . <nl> + / / * Redistributions in binary form must reproduce the above <nl> + / / copyright notice , this list of conditions and the following disclaimer <nl> + / / in the documentation and / or other materials provided with the <nl> + / / distribution . <nl> + / / * Neither the name of Google Inc . nor the names of its <nl> + / / contributors may be used to endorse or promote products derived from <nl> + / / this software without specific prior written permission . <nl> + / / <nl> + / / THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <nl> + / / " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT <nl> + / / LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR <nl> + / / A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT <nl> + / / OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , <nl> + / / SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT <nl> + / / LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + / / DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + / / THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + / / ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE <nl> + / / OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + <nl> + # endregion <nl> + <nl> + using System ; <nl> + using System . Collections . Generic ; <nl> + using System . Diagnostics ; <nl> + using System . Linq ; <nl> + using System . Threading ; <nl> + using System . Threading . Tasks ; <nl> + <nl> + using Grpc . Core ; <nl> + using Grpc . Core . Internal ; <nl> + using Grpc . Core . Utils ; <nl> + <nl> + using NUnit . Framework ; <nl> + <nl> + namespace Grpc . Core . Tests <nl> + { <nl> + public class HalfcloseTest <nl> + { <nl> + MockServiceHelper helper ; <nl> + Server server ; <nl> + Channel channel ; <nl> + <nl> + [ SetUp ] <nl> + public void Init ( ) <nl> + { <nl> + helper = new MockServiceHelper ( ) ; <nl> + <nl> + server = helper . GetServer ( ) ; <nl> + server . Start ( ) ; <nl> + channel = helper . GetChannel ( ) ; <nl> + } <nl> + <nl> + [ TearDown ] <nl> + public void Cleanup ( ) <nl> + { <nl> + channel . ShutdownAsync ( ) . Wait ( ) ; <nl> + server . ShutdownAsync ( ) . Wait ( ) ; <nl> + } <nl> + <nl> + / / / < summary > <nl> + / / / For client streaming and duplex streaming calls , if server does a full close <nl> + / / / before we halfclose the request stream , an attempt to halfclose <nl> + / / / ( complete the request stream ) shouldn ' t be treated as an error . <nl> + / / / < / summary > <nl> + / / / < returns > The after fullclose client streaming call . < / returns > <nl> + [ Test ] <nl> + public async Task HalfcloseAfterFullclose_ClientStreamingCall ( ) <nl> + { <nl> + helper . ClientStreamingHandler = new ClientStreamingServerMethod < string , string > ( async ( requestStream , context ) = > <nl> + { <nl> + return " PASS " ; <nl> + } ) ; <nl> + <nl> + var call = Calls . AsyncClientStreamingCall ( helper . CreateClientStreamingCall ( ) ) ; <nl> + / / make sure server has fullclosed on us <nl> + Assert . AreEqual ( " PASS " , await call . ResponseAsync ) ; <nl> + <nl> + / / sending close from client should be still fine because server can finish <nl> + / / the call anytime and we cannot do anything about it on the client side . <nl> + await call . RequestStream . CompleteAsync ( ) ; <nl> + <nl> + / / Second attempt to close from client is not allowed . <nl> + Assert . Throws ( typeof ( InvalidOperationException ) , async ( ) = > await call . RequestStream . CompleteAsync ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> mmm a / src / csharp / Grpc . Core / Internal / AsyncCall . cs <nl> ppp b / src / csharp / Grpc . Core / Internal / AsyncCall . cs <nl> public void StartSendCloseFromClient ( AsyncCompletionDelegate < object > completionD <nl> lock ( myLock ) <nl> { <nl> GrpcPreconditions . CheckNotNull ( completionDelegate , " Completion delegate cannot be null " ) ; <nl> - CheckSendingAllowed ( ) ; <nl> + CheckSendingAllowed ( allowFinished : true ) ; <nl> <nl> - call . StartSendCloseFromClient ( HandleHalfclosed ) ; <nl> + if ( ! disposed & & ! finished ) <nl> + { <nl> + call . StartSendCloseFromClient ( HandleSendCloseFromClientFinished ) ; <nl> + } <nl> + else <nl> + { <nl> + / / In case the call has already been finished by the serverside , <nl> + / / the halfclose has already been done implicitly , so we only <nl> + / / emit the notification for the completion delegate . <nl> + Task . Run ( ( ) = > HandleSendCloseFromClientFinished ( true ) ) ; <nl> + } <nl> <nl> halfcloseRequested = true ; <nl> sendCompletionDelegate = completionDelegate ; <nl> mmm a / src / csharp / Grpc . Core / Internal / AsyncCallBase . cs <nl> ppp b / src / csharp / Grpc . Core / Internal / AsyncCallBase . cs <nl> protected void StartSendMessageInternal ( TWrite msg , WriteFlags writeFlags , Async <nl> lock ( myLock ) <nl> { <nl> GrpcPreconditions . CheckNotNull ( completionDelegate , " Completion delegate cannot be null " ) ; <nl> - CheckSendingAllowed ( ) ; <nl> + CheckSendingAllowed ( allowFinished : false ) ; <nl> <nl> call . StartSendMessage ( HandleSendFinished , payload , writeFlags , ! initialMetadataSent ) ; <nl> <nl> protected virtual void OnAfterReleaseResources ( ) <nl> { <nl> } <nl> <nl> - protected void CheckSendingAllowed ( ) <nl> + protected void CheckSendingAllowed ( bool allowFinished ) <nl> { <nl> GrpcPreconditions . CheckState ( started ) ; <nl> CheckNotCancelled ( ) ; <nl> - GrpcPreconditions . CheckState ( ! disposed ) ; <nl> + GrpcPreconditions . CheckState ( ! disposed | | allowFinished ) ; <nl> <nl> GrpcPreconditions . CheckState ( ! halfcloseRequested , " Already halfclosed . " ) ; <nl> - GrpcPreconditions . CheckState ( ! finished , " Already finished . " ) ; <nl> + GrpcPreconditions . CheckState ( ! finished | | allowFinished , " Already finished . " ) ; <nl> GrpcPreconditions . CheckState ( sendCompletionDelegate = = null , " Only one write can be pending at a time " ) ; <nl> } <nl> <nl> protected void HandleSendFinished ( bool success ) <nl> } <nl> <nl> / / / < summary > <nl> - / / / Handles halfclose completion . <nl> + / / / Handles halfclose ( send close from client ) completion . <nl> + / / / < / summary > <nl> + protected void HandleSendCloseFromClientFinished ( bool success ) <nl> + { <nl> + AsyncCompletionDelegate < object > origCompletionDelegate = null ; <nl> + lock ( myLock ) <nl> + { <nl> + origCompletionDelegate = sendCompletionDelegate ; <nl> + sendCompletionDelegate = null ; <nl> + <nl> + ReleaseResourcesIfPossible ( ) ; <nl> + } <nl> + <nl> + if ( ! success ) <nl> + { <nl> + FireCompletion ( origCompletionDelegate , null , new InvalidOperationException ( " Sending close from client has failed . " ) ) ; <nl> + } <nl> + else <nl> + { <nl> + FireCompletion ( origCompletionDelegate , null , null ) ; <nl> + } <nl> + } <nl> + <nl> + / / / < summary > <nl> + / / / Handles send status from server completion . <nl> / / / < / summary > <nl> - protected void HandleHalfclosed ( bool success ) <nl> + protected void HandleSendStatusFromServerFinished ( bool success ) <nl> { <nl> AsyncCompletionDelegate < object > origCompletionDelegate = null ; <nl> lock ( myLock ) <nl> protected void HandleHalfclosed ( bool success ) <nl> <nl> if ( ! success ) <nl> { <nl> - FireCompletion ( origCompletionDelegate , null , new InvalidOperationException ( " Halfclose failed " ) ) ; <nl> + FireCompletion ( origCompletionDelegate , null , new InvalidOperationException ( " Error sending status from server . " ) ) ; <nl> } <nl> else <nl> { <nl> mmm a / src / csharp / Grpc . Core / Internal / AsyncCallServer . cs <nl> ppp b / src / csharp / Grpc . Core / Internal / AsyncCallServer . cs <nl> public void StartSendInitialMetadata ( Metadata headers , AsyncCompletionDelegate < o <nl> <nl> GrpcPreconditions . CheckState ( ! initialMetadataSent , " Response headers can only be sent once per call . " ) ; <nl> GrpcPreconditions . CheckState ( streamingWritesCounter = = 0 , " Response headers can only be sent before the first write starts . " ) ; <nl> - CheckSendingAllowed ( ) ; <nl> + CheckSendingAllowed ( allowFinished : false ) ; <nl> <nl> GrpcPreconditions . CheckNotNull ( completionDelegate , " Completion delegate cannot be null " ) ; <nl> <nl> public void StartSendStatusFromServer ( Status status , Metadata trailers , AsyncCom <nl> lock ( myLock ) <nl> { <nl> GrpcPreconditions . CheckNotNull ( completionDelegate , " Completion delegate cannot be null " ) ; <nl> - CheckSendingAllowed ( ) ; <nl> + CheckSendingAllowed ( allowFinished : false ) ; <nl> <nl> using ( var metadataArray = MetadataArraySafeHandle . Create ( trailers ) ) <nl> { <nl> - call . StartSendStatusFromServer ( HandleHalfclosed , status , metadataArray , ! initialMetadataSent ) ; <nl> + call . StartSendStatusFromServer ( HandleSendStatusFromServerFinished , status , metadataArray , ! initialMetadataSent ) ; <nl> } <nl> halfcloseRequested = true ; <nl> readingDone = true ; <nl> mmm a / src / csharp / tests . json <nl> ppp b / src / csharp / tests . json <nl> <nl> " Grpc . Core . Tests . CompressionTest " , <nl> " Grpc . Core . Tests . ContextPropagationTest " , <nl> " Grpc . Core . Tests . GrpcEnvironmentTest " , <nl> + " Grpc . Core . Tests . HalfcloseTest " , <nl> " Grpc . Core . Tests . MarshallingErrorsTest " , <nl> " Grpc . Core . Tests . MetadataTest " , <nl> " Grpc . Core . Tests . NUnitVersionTest " , <nl>
allow halfclose after close on clients
grpc/grpc
153c32a1eb696643095c60a4a98cd8507989fcf6
2016-04-01T21:38:32Z
mmm a / taskcluster / test - armbian - opt - base . tyml <nl> ppp b / taskcluster / test - armbian - opt - base . tyml <nl> then : <nl> DEEPSPEECH_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { linux_arm64_build } / artifacts / public <nl> DEEPSPEECH_NODEJS : https : / / queue . taskcluster . net / v1 / task / $ { node_package_cpu } / artifacts / public <nl> DEEPSPEECH_TEST_MODEL : https : / / queue . taskcluster . net / v1 / task / $ { training } / artifacts / public / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pbmm <nl> + DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pb <nl> + DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pbmm <nl> PIP_DEFAULT_TIMEOUT : " 60 " <nl> PIP_EXTRA_INDEX_URL : " https : / / lissyx . github . io / deepspeech - python - wheels / " <nl> EXTRA_PYTHON_CONFIGURE_OPTS : " - - with - fpectl " # Required by Debian Stretch <nl> mmm a / taskcluster / test - darwin - opt - base . tyml <nl> ppp b / taskcluster / test - darwin - opt - base . tyml <nl> then : <nl> DEEPSPEECH_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { darwin_amd64_build } / artifacts / public <nl> DEEPSPEECH_NODEJS : https : / / queue . taskcluster . net / v1 / task / $ { node_package_cpu } / artifacts / public <nl> DEEPSPEECH_TEST_MODEL : https : / / queue . taskcluster . net / v1 / task / $ { training } / artifacts / public / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pbmm <nl> + DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pb <nl> + DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pbmm <nl> EXPECTED_TENSORFLOW_VERSION : " $ { build . tensorflow_git_desc } " <nl> <nl> command : <nl> mmm a / taskcluster / test - linux - opt - base . tyml <nl> ppp b / taskcluster / test - linux - opt - base . tyml <nl> then : <nl> DEEPSPEECH_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { linux_amd64_build } / artifacts / public <nl> DEEPSPEECH_NODEJS : https : / / queue . taskcluster . net / v1 / task / $ { node_package_cpu } / artifacts / public <nl> DEEPSPEECH_TEST_MODEL : https : / / queue . taskcluster . net / v1 / task / $ { training } / artifacts / public / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pbmm <nl> + DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pb <nl> + DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pbmm <nl> DECODER_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { linux_amd64_ctc } / artifacts / public <nl> PIP_DEFAULT_TIMEOUT : " 60 " <nl> EXPECTED_TENSORFLOW_VERSION : " $ { build . tensorflow_git_desc } " <nl> mmm a / taskcluster / test - raspbian - opt - base . tyml <nl> ppp b / taskcluster / test - raspbian - opt - base . tyml <nl> then : <nl> DEEPSPEECH_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { linux_rpi3_build } / artifacts / public <nl> DEEPSPEECH_NODEJS : https : / / queue . taskcluster . net / v1 / task / $ { node_package_cpu } / artifacts / public <nl> DEEPSPEECH_TEST_MODEL : https : / / queue . taskcluster . net / v1 / task / $ { training } / artifacts / public / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pbmm <nl> + DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pb <nl> + DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pbmm <nl> PIP_DEFAULT_TIMEOUT : " 60 " <nl> PIP_EXTRA_INDEX_URL : " https : / / www . piwheels . org / simple " <nl> EXTRA_PYTHON_CONFIGURE_OPTS : " - - with - fpectl " # Required by Raspbian Stretch / PiWheels <nl> mmm a / taskcluster / test - win - opt - base . tyml <nl> ppp b / taskcluster / test - win - opt - base . tyml <nl> then : <nl> DEEPSPEECH_ARTIFACTS_ROOT : https : / / queue . taskcluster . net / v1 / task / $ { win_amd64_build } / artifacts / public <nl> DEEPSPEECH_NODEJS : https : / / queue . taskcluster . net / v1 / task / $ { node_package_cpu } / artifacts / public <nl> DEEPSPEECH_TEST_MODEL : https : / / queue . taskcluster . net / v1 / task / $ { training } / artifacts / public / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pb <nl> - DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 2 . 0 - prod - ctcdecode / output_graph . pbmm <nl> + DEEPSPEECH_PROD_MODEL : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pb <nl> + DEEPSPEECH_PROD_MODEL_MMAP : https : / / github . com / reuben / DeepSpeech / releases / download / v0 . 5 . 0 - alpha . 11 / output_graph . pbmm <nl> EXPECTED_TENSORFLOW_VERSION : " $ { build . tensorflow_git_desc } " <nl> TC_MSYS_VERSION : ' MSYS_NT - 6 . 3 ' <nl> MSYS : ' winsymlinks : nativestrict ' <nl> mmm a / tc - tests - utils . sh <nl> ppp b / tc - tests - utils . sh <nl> assert_correct_multi_ldc93s1 ( ) <nl> <nl> assert_correct_ldc93s1_prodmodel ( ) <nl> { <nl> - assert_correct_inference " $ 1 " " she had a due and greasy wash water year " " $ 2 " <nl> + assert_correct_inference " $ 1 " " she had reduce suit in greasy water all year " " $ 2 " <nl> } <nl> <nl> assert_correct_ldc93s1_prodmodel_stereo_44k ( ) <nl> { <nl> - assert_correct_inference " $ 1 " " she had a due and greasy wash water year " " $ 2 " <nl> + assert_correct_inference " $ 1 " " she had reduce suit in greasy water all year " " $ 2 " <nl> } <nl> <nl> assert_correct_warning_upsampling ( ) <nl>
Update prod tests to point to 0 . 5 model
mozilla/DeepSpeech
f02d79cca226914a7b05898b4aad107ed144ebba
2019-06-07T16:14:45Z
mmm a / tools / bazel . rc <nl> ppp b / tools / bazel . rc <nl> build - - copt = " - Werror = unused - variable " <nl> build - - copt = " - Werror = unused - but - set - variable " <nl> build - - copt = " - Werror = switch " <nl> <nl> - build - - per_file_copt = ^ modules / . * \ . cc , ^ cyber / . * \ . cc @ - Wconversion <nl> - # Strict check on cleared modules . <nl> - build - - per_file_copt = \ <nl> - ^ modules / calibration / . * \ . cc , \ <nl> - ^ modules / canbus / . * \ . cc , \ <nl> - ^ modules / common / . * \ . cc , \ <nl> - ^ modules / common / math / . * \ . cc , \ <nl> - ^ modules / common / util / . * \ . cc , \ <nl> - ^ modules / contrib / . * \ . cc , \ <nl> - ^ modules / control / . * \ . cc , \ <nl> - ^ modules / data / . * \ . cc , \ <nl> - ^ modules / dreamview / . * \ . cc , \ <nl> - ^ modules / drivers / velodyne / . * \ . cc , \ <nl> - ^ modules / guardian / . * \ . cc , \ <nl> - ^ modules / localization / . * \ . cc , \ <nl> - ^ modules / map / . * \ . cc , \ <nl> - ^ modules / monitor / . * \ . cc , \ <nl> - ^ modules / perception / . * \ . cc , \ <nl> - ^ modules / prediction / . * \ . cc , \ <nl> - ^ modules / planning / . * \ . cc , \ <nl> - ^ modules / routing / . * \ . cc , \ <nl> - ^ modules / third_party_perception / . * \ . cc , \ <nl> - ^ modules / tools / . * \ . cc , \ <nl> - ^ modules / transform / . * \ . cc , \ <nl> - ^ modules / v2x / . * \ . cc , \ <nl> - @ - Werror = conversion <nl> + # Strict check on type conversion . <nl> + # TODO ( all ) : Clear drivers module and remove it from exception . <nl> + build - - per_file_copt = ^ modules / . * \ . cc , - ^ modules / drivers / . * \ . cc @ - Werror = conversion <nl> + <nl> + # TODO ( all ) : Clear cyber warnings and add it to the strict check . <nl> + build - - per_file_copt = ^ cyber / . * \ . cc @ - Wconversion <nl> <nl> <nl> # Enable C + + 14 <nl>
Tools : Simplify type conversion check config and add comment . ( )
ApolloAuto/apollo
d5ef537eb8afa762790043310650dd94cb86493e
2018-12-13T23:21:09Z
mmm a / etc / evergreen . yml <nl> ppp b / etc / evergreen . yml <nl> tasks : <nl> - name : push <nl> patchable : false <nl> depends_on : <nl> - - name : " * " <nl> + - name : jsCore <nl> + - name : dbtest <nl> + - name : replica_sets_jscore_passthrough <nl> stepback : false <nl> commands : <nl> - func : " fetch artifacts " <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl> buildvariants : <nl> - name : dbtest <nl> - name : free_monitoring <nl> - name : jsCore <nl> + - name : replica_sets_jscore_passthrough <nl> - name : push <nl> distros : <nl> - ubuntu1604 - test <nl> buildvariants : <nl> - name : bulk_gle_passthrough <nl> - name : replica_sets_auth <nl> - name : replica_sets_ese <nl> + - name : replica_sets_jscore_passthrough <nl> - name : powercycle <nl> - name : sasl <nl> - name : sharding_auth <nl> buildvariants : <nl> - name : bulk_gle_passthrough <nl> - name : replica_sets_auth <nl> - name : replica_sets_ese <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : sharding_auth_audit <nl> buildvariants : <nl> - name : replica_sets_ese_5 <nl> - name : replica_sets_ese_6 <nl> - name : replica_sets_ese_misc <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharded_core_txns <nl> - name : sharding_auth_0 <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : ssl <nl> - name : sslSpecial <nl> buildvariants : <nl> - name : jstestfuzz_sharded <nl> - name : external_auth <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : sharding_auth_audit <nl> buildvariants : <nl> - name : compile_all_run_unittests_TG <nl> distros : <nl> - rhel67 - zseries - build <nl> + - name : dbtest <nl> - name : jsCore <nl> + - name : replica_sets_jscore_passthrough <nl> - name : ssl <nl> - name : push <nl> distros : <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl> buildvariants : <nl> - name : jstestfuzz_replication <nl> - name : jstestfuzz_sharded <nl> - name : replica_sets_auth <nl> + - name : replica_sets_jscore_passthrough <nl> - name : sasl <nl> - name : sharding_auth <nl> - name : snmp <nl>
SERVER - 35972 Run push tasks more often
mongodb/mongo
ceae29c2fc64445dcf832d2f82c44c1920d91933
2018-07-09T14:30:16Z
mmm a / tensorflow / compiler / mlir / tensorflow / ir / tf_ops . td <nl> ppp b / tensorflow / compiler / mlir / tensorflow / ir / tf_ops . td <nl> An n - way switch statement , implementing the following : <nl> let verifier = [ { <nl> return Verify ( * this ) ; <nl> } ] ; <nl> + <nl> + let hasCanonicalizer = 1 ; <nl> + <nl> } <nl> <nl> / / In MLIR , the TensorFlow tensor value is represented as an ElementsAttr , with <nl> else_branch : A region that computes the outputs of the op if cond = false . <nl> return Verify ( * this ) ; <nl> } ] ; <nl> <nl> + let builders = [ OpBuilder < <nl> + " OpBuilder & builder , OperationState & result , TypeRange resultTypes , ValueRange operands , llvm : : ArrayRef < : : mlir : : NamedAttribute > attributes , unsigned numRegions " , [ { <nl> + assert ( numRegions = = 2u & & " mismatched number of regions " ) ; <nl> + build ( builder , result , resultTypes , operands , attributes ) ; <nl> + } ] > ] ; <nl> + <nl> let hasCanonicalizer = 1 ; <nl> } <nl> <nl> mmm a / tensorflow / compiler / mlir / tensorflow / ir / tf_ops_a_m . cc <nl> ppp b / tensorflow / compiler / mlir / tensorflow / ir / tf_ops_a_m . cc <nl> static LogicalResult Verify ( CaseRegionOp op ) { <nl> return success ( ) ; <nl> } <nl> <nl> + namespace { <nl> + / / Eliminate values that pass through the CaseRegionOp or IfRegionOp branches . <nl> + template < class CaseOrIfRegionOp > <nl> + class CaseOrIfRegionEliminatePassThrough <nl> + : public OpRewritePattern < CaseOrIfRegionOp > { <nl> + using OpRewritePattern < CaseOrIfRegionOp > : : OpRewritePattern ; <nl> + <nl> + LogicalResult matchAndRewrite ( CaseOrIfRegionOp op , <nl> + PatternRewriter & rewriter ) const override { <nl> + RegionRange branches = op . getRegions ( ) ; <nl> + SmallVector < Type , 4 > new_result_types ; <nl> + / / Maps pass through results to extern values . <nl> + llvm : : SmallDenseMap < Value , Value , 4 > result_to_extern_value ; <nl> + <nl> + for ( auto result : op . getResults ( ) ) { <nl> + unsigned index = result . getResultNumber ( ) ; <nl> + Region * first_branch = * branches . begin ( ) ; <nl> + Operation * first_terminator = first_branch - > front ( ) . getTerminator ( ) ; <nl> + Value returned_val = first_terminator - > getOperand ( index ) ; <nl> + <nl> + / / Pass through values would be defined outside the branch region . Keep <nl> + / / the type of non pass through results to create a new op later , if <nl> + / / required . <nl> + if ( returned_val . getParentBlock ( ) = = & first_branch - > front ( ) ) { <nl> + new_result_types . push_back ( result . getType ( ) ) ; <nl> + continue ; <nl> + } <nl> + / / Check if the same extern value is returned in each branch . <nl> + for ( Region * region : branches . drop_front ( ) ) { <nl> + Operation * terminator = region - > front ( ) . getTerminator ( ) ; <nl> + if ( terminator - > getOperand ( index ) ! = returned_val ) return failure ( ) ; <nl> + } <nl> + result_to_extern_value [ result ] = returned_val ; <nl> + } <nl> + <nl> + / / If no pass through values are found , no change is required . <nl> + if ( result_to_extern_value . empty ( ) ) return failure ( ) ; <nl> + <nl> + / / Create new case / if region op . <nl> + auto new_op = rewriter . create < CaseOrIfRegionOp > ( <nl> + op . getLoc ( ) , new_result_types , op . getOperand ( ) , op . getAttrs ( ) , <nl> + op . getNumRegions ( ) ) ; <nl> + <nl> + int next_index = 0 ; <nl> + for ( auto result : op . getResults ( ) ) { <nl> + if ( ! result_to_extern_value . count ( result ) ) { <nl> + result . replaceAllUsesWith ( new_op . getResult ( next_index + + ) ) ; <nl> + continue ; <nl> + } <nl> + result . replaceAllUsesWith ( result_to_extern_value [ result ] ) ; <nl> + for ( Region * branch : branches ) <nl> + branch - > front ( ) . getTerminator ( ) - > eraseOperand ( next_index ) ; <nl> + } <nl> + <nl> + / / Move region bodies to the new op . <nl> + for ( auto region_index : llvm : : seq < int > ( 0 , branches . size ( ) ) ) <nl> + new_op . getRegion ( region_index ) . takeBody ( op . getRegion ( region_index ) ) ; <nl> + <nl> + op . erase ( ) ; <nl> + return success ( ) ; <nl> + } <nl> + } ; <nl> + } / / namespace <nl> + <nl> + void CaseRegionOp : : getCanonicalizationPatterns ( <nl> + OwningRewritePatternList & results , MLIRContext * context ) { <nl> + results . insert < CaseOrIfRegionEliminatePassThrough < TF : : CaseRegionOp > > ( context ) ; <nl> + } <nl> + <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> / / CastOp <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> LogicalResult FoldConstantIfRegionOp : : matchAndRewrite ( <nl> <nl> void IfRegionOp : : getCanonicalizationPatterns ( OwningRewritePatternList & results , <nl> MLIRContext * context ) { <nl> - results . insert < FoldConstantIfRegionOp > ( context ) ; <nl> + results . insert < FoldConstantIfRegionOp , <nl> + CaseOrIfRegionEliminatePassThrough < TF : : IfRegionOp > > ( context ) ; <nl> } <nl> <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / canonicalize . mlir <nl> ppp b / tensorflow / compiler / mlir / tensorflow / tests / canonicalize . mlir <nl> func @ foldIfRegionMismatchedTypes ( % arg0 : tensor < ? xf32 > , % arg1 : tensor < ? xf32 > , % a <nl> return % 0 : tensor < 1xf32 > <nl> } <nl> <nl> + / / CHECK - LABEL : func @ eliminatePassThroughIfRegion ( <nl> + / / CHECK - SAME : % [ [ ARG0 : . * ] ] : tensor < f32 > , % [ [ ARG1 : . * ] ] : tensor < f32 > , % [ [ ARG2 : . * ] ] : tensor < ! tf . resource > <nl> + func @ eliminatePassThroughIfRegion ( % arg0 : tensor < f32 > , % arg1 : tensor < f32 > , % arg2 : tensor < ! tf . resource > ) - > ( tensor < f32 > ) { <nl> + / / CHECK : % [ [ PRED : . * ] ] = " tf . _SomeOp " ( ) : ( ) - > tensor < i1 > <nl> + % pred = " tf . _SomeOp " ( ) : ( ) - > tensor < i1 > <nl> + / / CHECK : % [ [ IF_OUTPUT : . * ] ] = " tf . IfRegion " ( % [ [ PRED ] ] ) ( { <nl> + / / CHECK : % [ [ MUL : . * ] ] = " tf . Mul " ( % [ [ ARG0 ] ] , % [ [ ARG1 ] ] ) <nl> + / / CHECK : " tf . Yield " ( % [ [ MUL ] ] ) : ( tensor < f32 > ) <nl> + / / CHECK : } , { <nl> + / / CHECK : % [ [ SUB : . * ] ] = " tf . Sub " ( % [ [ ARG0 ] ] , % [ [ ARG1 ] ] ) <nl> + / / CHECK : " tf . Yield " ( % [ [ SUB ] ] ) : ( tensor < f32 > ) <nl> + / / CHECK : } ) { is_stateless = true } : ( tensor < i1 > ) - > tensor < f32 > <nl> + % 0 : 4 = " tf . IfRegion " ( % pred ) ( { <nl> + % true_value = " tf . Mul " ( % arg0 , % arg1 ) : ( tensor < f32 > , tensor < f32 > ) - > tensor < f32 > <nl> + " tf . Yield " ( % arg1 , % arg2 , % true_value , % arg2 ) : ( tensor < f32 > , tensor < ! tf . resource > , tensor < f32 > , tensor < ! tf . resource > ) - > ( ) <nl> + } , { <nl> + % false_value = " tf . Sub " ( % arg0 , % arg1 ) : ( tensor < f32 > , tensor < f32 > ) - > tensor < f32 > <nl> + " tf . Yield " ( % arg1 , % arg2 , % false_value , % arg2 ) : ( tensor < f32 > , tensor < ! tf . resource > , tensor < f32 > , tensor < ! tf . resource > ) - > ( ) <nl> + } ) { is_stateless = true } : ( tensor < i1 > ) - > ( tensor < f32 > , tensor < ! tf . resource > , tensor < f32 > , tensor < ! tf . resource > ) <nl> + / / CHECK : " tf . _SomeOp " ( % [ [ ARG2 ] ] , % [ [ ARG1 ] ] ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + " tf . _SomeOp " ( % 0 # 1 , % 0 # 0 ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + / / CHECK : " tf . _SomeOp " ( % [ [ ARG2 ] ] , % [ [ IF_OUTPUT ] ] ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + " tf . _SomeOp " ( % 0 # 3 , % 0 # 2 ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + / / CHECK : return % [ [ IF_OUTPUT ] ] : tensor < f32 > <nl> + return % 0 # 2 : tensor < f32 > <nl> + } <nl> + <nl> + / / CHECK - LABEL : func @ eliminatePassThroughCaseRegion ( <nl> + / / CHECK - SAME : % [ [ ARG0 : . * ] ] : tensor < f32 > , % [ [ ARG1 : . * ] ] : tensor < f32 > , % [ [ ARG2 : . * ] ] : tensor < ! tf . resource > <nl> + func @ eliminatePassThroughCaseRegion ( % arg0 : tensor < f32 > , % arg1 : tensor < f32 > , % arg2 : tensor < ! tf . resource > ) - > ( tensor < f32 > ) { <nl> + / / CHECK : % [ [ INDEX : . * ] ] = " tf . _SomeOp " ( ) : ( ) - > tensor < i32 > <nl> + % index = " tf . _SomeOp " ( ) : ( ) - > tensor < i32 > <nl> + / / CHECK : % [ [ CASE_OUTPUT : . * ] ] = " tf . CaseRegion " ( % [ [ INDEX ] ] ) ( { <nl> + / / CHECK : % [ [ MUL : . * ] ] = " tf . Mul " ( % [ [ ARG0 ] ] , % [ [ ARG1 ] ] ) <nl> + / / CHECK : " tf . Yield " ( % [ [ MUL ] ] ) : ( tensor < f32 > ) <nl> + / / CHECK : } , { <nl> + / / CHECK : % [ [ SUB : . * ] ] = " tf . Sub " ( % [ [ ARG0 ] ] , % [ [ ARG1 ] ] ) <nl> + / / CHECK : " tf . Yield " ( % [ [ SUB ] ] ) : ( tensor < f32 > ) <nl> + / / CHECK : } , { <nl> + / / CHECK : % [ [ ADD : . * ] ] = " tf . AddV2 " ( % [ [ ARG0 ] ] , % [ [ ARG1 ] ] ) <nl> + / / CHECK : " tf . Yield " ( % [ [ ADD ] ] ) : ( tensor < f32 > ) <nl> + / / CHECK : } ) { is_stateless = true } : ( tensor < i32 > ) - > tensor < f32 > <nl> + % 0 : 3 = " tf . CaseRegion " ( % index ) ( { <nl> + % mul = " tf . Mul " ( % arg0 , % arg1 ) : ( tensor < f32 > , tensor < f32 > ) - > tensor < f32 > <nl> + " tf . Yield " ( % arg1 , % mul , % arg2 ) : ( tensor < f32 > , tensor < f32 > , tensor < ! tf . resource > ) - > ( ) <nl> + } , { <nl> + % sub = " tf . Sub " ( % arg0 , % arg1 ) : ( tensor < f32 > , tensor < f32 > ) - > tensor < f32 > <nl> + " tf . Yield " ( % arg1 , % sub , % arg2 ) : ( tensor < f32 > , tensor < f32 > , tensor < ! tf . resource > ) - > ( ) <nl> + } , { <nl> + % add = " tf . AddV2 " ( % arg0 , % arg1 ) : ( tensor < f32 > , tensor < f32 > ) - > tensor < f32 > <nl> + " tf . Yield " ( % arg1 , % add , % arg2 ) : ( tensor < f32 > , tensor < f32 > , tensor < ! tf . resource > ) - > ( ) <nl> + } ) { is_stateless = true } : ( tensor < i32 > ) - > ( tensor < f32 > , tensor < f32 > , tensor < ! tf . resource > ) <nl> + / / CHECK : " tf . _SomeOp " ( % [ [ ARG2 ] ] , % [ [ ARG1 ] ] ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + " tf . _SomeOp " ( % 0 # 2 , % 0 # 0 ) : ( tensor < ! tf . resource > , tensor < f32 > ) - > ( ) <nl> + / / CHECK : return % [ [ CASE_OUTPUT ] ] : tensor < f32 > <nl> + return % 0 # 1 : tensor < f32 > <nl> + } <nl> + <nl> + <nl> / / CHECK - LABEL : foldCase <nl> func @ foldCase ( % arg0 : tensor < f32 > , % arg1 : tensor < f32 > ) - > ( tensor < f32 > ) { <nl> % 2 = constant dense < 1 > : tensor < i32 > <nl>
Canonicalize IfRegion and CaseRegion ops to eliminate pass through results .
tensorflow/tensorflow
8e9d65f93d4f27844ff713542e25a47a8a5cfc4a
2020-10-15T03:45:07Z
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> CMAKE_DEPENDENT_OPTION ( YUZU_USE_BUNDLED_QT " Download bundled Qt binaries " ON " EN <nl> <nl> option ( YUZU_USE_BUNDLED_UNICORN " Build / Download bundled Unicorn " ON ) <nl> <nl> + option ( ENABLE_CUBEB " Enables the cubeb audio backend " ON ) <nl> + <nl> if ( NOT EXISTS $ { CMAKE_SOURCE_DIR } / . git / hooks / pre - commit ) <nl> message ( STATUS " Copying pre - commit hook " ) <nl> file ( COPY hooks / pre - commit <nl> mmm a / externals / CMakeLists . txt <nl> ppp b / externals / CMakeLists . txt <nl> endif ( ) <nl> # Opus <nl> add_subdirectory ( opus ) <nl> target_include_directories ( opus INTERFACE . / opus / include ) <nl> + <nl> + # Cubeb <nl> + if ( ENABLE_CUBEB ) <nl> + set ( BUILD_TESTS OFF CACHE BOOL " " ) <nl> + add_subdirectory ( cubeb ) <nl> + endif ( ) <nl> mmm a / src / audio_core / CMakeLists . txt <nl> ppp b / src / audio_core / CMakeLists . txt <nl> add_library ( audio_core STATIC <nl> audio_out . cpp <nl> audio_out . h <nl> buffer . h <nl> + cubeb_sink . cpp <nl> + cubeb_sink . h <nl> null_sink . h <nl> stream . cpp <nl> stream . h <nl> add_library ( audio_core STATIC <nl> create_target_directory_groups ( audio_core ) <nl> <nl> target_link_libraries ( audio_core PUBLIC common core ) <nl> + <nl> + if ( ENABLE_CUBEB ) <nl> + target_link_libraries ( audio_core PRIVATE cubeb ) <nl> + target_compile_definitions ( audio_core PRIVATE - DHAVE_CUBEB = 1 ) <nl> + endif ( ) <nl> mmm a / src / audio_core / audio_out . cpp <nl> ppp b / src / audio_core / audio_out . cpp <nl> <nl> / / Refer to the license . txt file included . <nl> <nl> # include " audio_core / audio_out . h " <nl> + # include " audio_core / sink . h " <nl> + # include " audio_core / sink_details . h " <nl> # include " common / assert . h " <nl> # include " common / logging / log . h " <nl> <nl> static Stream : : Format ChannelsToStreamFormat ( u32 num_channels ) { <nl> <nl> StreamPtr AudioOut : : OpenStream ( u32 sample_rate , u32 num_channels , <nl> Stream : : ReleaseCallback & & release_callback ) { <nl> - streams . push_back ( std : : make_shared < Stream > ( sample_rate , ChannelsToStreamFormat ( num_channels ) , <nl> - std : : move ( release_callback ) ) ) ; <nl> - return streams . back ( ) ; <nl> + if ( ! sink ) { <nl> + const SinkDetails & sink_details = GetSinkDetails ( " auto " ) ; <nl> + sink = sink_details . factory ( " " ) ; <nl> + } <nl> + <nl> + return std : : make_shared < Stream > ( sample_rate , ChannelsToStreamFormat ( num_channels ) , <nl> + std : : move ( release_callback ) , <nl> + sink - > AcquireSinkStream ( sample_rate , num_channels ) ) ; <nl> } <nl> <nl> std : : vector < u64 > AudioOut : : GetTagsAndReleaseBuffers ( StreamPtr stream , size_t max_count ) { <nl> mmm a / src / audio_core / audio_out . h <nl> ppp b / src / audio_core / audio_out . h <nl> <nl> # include < vector > <nl> <nl> # include " audio_core / buffer . h " <nl> + # include " audio_core / sink . h " <nl> # include " audio_core / stream . h " <nl> # include " common / common_types . h " <nl> <nl> class AudioOut { <nl> <nl> private : <nl> SinkPtr sink ; <nl> - std : : vector < StreamPtr > streams ; <nl> } ; <nl> <nl> } / / namespace AudioCore <nl> new file mode 100644 <nl> index 00000000000 . . 34ae5b06236 <nl> mmm / dev / null <nl> ppp b / src / audio_core / cubeb_sink . cpp <nl> <nl> + / / Copyright 2018 yuzu Emulator Project <nl> + / / Licensed under GPLv2 or any later version <nl> + / / Refer to the license . txt file included . <nl> + <nl> + # include < algorithm > <nl> + # include < cstring > <nl> + <nl> + # include " audio_core / cubeb_sink . h " <nl> + # include " audio_core / stream . h " <nl> + # include " common / logging / log . h " <nl> + <nl> + namespace AudioCore { <nl> + <nl> + class SinkStreamImpl final : public SinkStream { <nl> + public : <nl> + SinkStreamImpl ( cubeb * ctx , cubeb_devid output_device ) : ctx { ctx } { <nl> + cubeb_stream_params params ; <nl> + params . rate = 48000 ; <nl> + params . channels = GetNumChannels ( ) ; <nl> + params . format = CUBEB_SAMPLE_S16NE ; <nl> + params . layout = CUBEB_LAYOUT_STEREO ; <nl> + <nl> + u32 minimum_latency = 0 ; <nl> + if ( cubeb_get_min_latency ( ctx , & params , & minimum_latency ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " Error getting minimum latency " ) ; <nl> + } <nl> + <nl> + if ( cubeb_stream_init ( ctx , & stream_backend , " yuzu Audio Output " , nullptr , nullptr , <nl> + output_device , & params , std : : max ( 512u , minimum_latency ) , <nl> + & SinkStreamImpl : : DataCallback , & SinkStreamImpl : : StateCallback , <nl> + this ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " Error initializing cubeb stream " ) ; <nl> + return ; <nl> + } <nl> + <nl> + if ( cubeb_stream_start ( stream_backend ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " Error starting cubeb stream " ) ; <nl> + return ; <nl> + } <nl> + } <nl> + <nl> + ~ SinkStreamImpl ( ) { <nl> + if ( ! ctx ) { <nl> + return ; <nl> + } <nl> + <nl> + if ( cubeb_stream_stop ( stream_backend ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " Error stopping cubeb stream " ) ; <nl> + } <nl> + <nl> + cubeb_stream_destroy ( stream_backend ) ; <nl> + } <nl> + <nl> + void EnqueueSamples ( u32 num_channels , const s16 * samples , size_t sample_count ) override { <nl> + if ( ! ctx ) { <nl> + return ; <nl> + } <nl> + <nl> + queue . reserve ( queue . size ( ) + sample_count * GetNumChannels ( ) ) ; <nl> + <nl> + if ( num_channels = = 2 ) { <nl> + / / Copy as - is <nl> + std : : copy ( samples , samples + sample_count * GetNumChannels ( ) , <nl> + std : : back_inserter ( queue ) ) ; <nl> + } else if ( num_channels = = 6 ) { <nl> + / / Downsample 6 channels to 2 <nl> + const size_t sample_count_copy_size = sample_count * num_channels * 2 ; <nl> + queue . reserve ( sample_count_copy_size ) ; <nl> + for ( size_t i = 0 ; i < sample_count * num_channels ; i + = num_channels ) { <nl> + queue . push_back ( samples [ i ] ) ; <nl> + queue . push_back ( samples [ i + 1 ] ) ; <nl> + } <nl> + } else { <nl> + ASSERT_MSG ( false , " Unimplemented " ) ; <nl> + } <nl> + } <nl> + <nl> + u32 GetNumChannels ( ) const { <nl> + / / Only support 2 - channel stereo output for now <nl> + return 2 ; <nl> + } <nl> + <nl> + private : <nl> + std : : vector < std : : string > device_list ; <nl> + <nl> + cubeb * ctx { } ; <nl> + cubeb_stream * stream_backend { } ; <nl> + <nl> + std : : vector < s16 > queue ; <nl> + <nl> + static long DataCallback ( cubeb_stream * stream , void * user_data , const void * input_buffer , <nl> + void * output_buffer , long num_frames ) ; <nl> + static void StateCallback ( cubeb_stream * stream , void * user_data , cubeb_state state ) ; <nl> + } ; <nl> + <nl> + CubebSink : : CubebSink ( std : : string target_device_name ) { <nl> + if ( cubeb_init ( & ctx , " yuzu " , nullptr ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " cubeb_init failed " ) ; <nl> + return ; <nl> + } <nl> + <nl> + if ( target_device_name ! = auto_device_name & & ! target_device_name . empty ( ) ) { <nl> + cubeb_device_collection collection ; <nl> + if ( cubeb_enumerate_devices ( ctx , CUBEB_DEVICE_TYPE_OUTPUT , & collection ) ! = CUBEB_OK ) { <nl> + LOG_WARNING ( Audio_Sink , " Audio output device enumeration not supported " ) ; <nl> + } else { <nl> + const auto collection_end { collection . device + collection . count } ; <nl> + const auto device { std : : find_if ( collection . device , collection_end , <nl> + [ & ] ( const cubeb_device_info & device ) { <nl> + return target_device_name = = device . friendly_name ; <nl> + } ) } ; <nl> + if ( device ! = collection_end ) { <nl> + output_device = device - > devid ; <nl> + } <nl> + cubeb_device_collection_destroy ( ctx , & collection ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + CubebSink : : ~ CubebSink ( ) { <nl> + if ( ! ctx ) { <nl> + return ; <nl> + } <nl> + <nl> + for ( auto & sink_stream : sink_streams ) { <nl> + sink_stream . reset ( ) ; <nl> + } <nl> + <nl> + cubeb_destroy ( ctx ) ; <nl> + } <nl> + <nl> + SinkStream & CubebSink : : AcquireSinkStream ( u32 sample_rate , u32 num_channels ) { <nl> + sink_streams . push_back ( std : : make_unique < SinkStreamImpl > ( ctx , output_device ) ) ; <nl> + return * sink_streams . back ( ) ; <nl> + } <nl> + <nl> + long SinkStreamImpl : : DataCallback ( cubeb_stream * stream , void * user_data , const void * input_buffer , <nl> + void * output_buffer , long num_frames ) { <nl> + SinkStreamImpl * impl = static_cast < SinkStreamImpl * > ( user_data ) ; <nl> + u8 * buffer = reinterpret_cast < u8 * > ( output_buffer ) ; <nl> + <nl> + if ( ! impl ) { <nl> + return { } ; <nl> + } <nl> + <nl> + const size_t frames_to_write { <nl> + std : : min ( impl - > queue . size ( ) / impl - > GetNumChannels ( ) , static_cast < size_t > ( num_frames ) ) } ; <nl> + <nl> + memcpy ( buffer , impl - > queue . data ( ) , frames_to_write * sizeof ( s16 ) * impl - > GetNumChannels ( ) ) ; <nl> + impl - > queue . erase ( impl - > queue . begin ( ) , <nl> + impl - > queue . begin ( ) + frames_to_write * impl - > GetNumChannels ( ) ) ; <nl> + <nl> + if ( frames_to_write < num_frames ) { <nl> + / / Fill the rest of the frames with silence <nl> + memset ( buffer + frames_to_write * sizeof ( s16 ) * impl - > GetNumChannels ( ) , 0 , <nl> + ( num_frames - frames_to_write ) * sizeof ( s16 ) * impl - > GetNumChannels ( ) ) ; <nl> + } <nl> + <nl> + return num_frames ; <nl> + } <nl> + <nl> + void SinkStreamImpl : : StateCallback ( cubeb_stream * stream , void * user_data , cubeb_state state ) { } <nl> + <nl> + std : : vector < std : : string > ListCubebSinkDevices ( ) { <nl> + std : : vector < std : : string > device_list ; <nl> + cubeb * ctx ; <nl> + <nl> + if ( cubeb_init ( & ctx , " Citra Device Enumerator " , nullptr ) ! = CUBEB_OK ) { <nl> + LOG_CRITICAL ( Audio_Sink , " cubeb_init failed " ) ; <nl> + return { } ; <nl> + } <nl> + <nl> + cubeb_device_collection collection ; <nl> + if ( cubeb_enumerate_devices ( ctx , CUBEB_DEVICE_TYPE_OUTPUT , & collection ) ! = CUBEB_OK ) { <nl> + LOG_WARNING ( Audio_Sink , " Audio output device enumeration not supported " ) ; <nl> + } else { <nl> + for ( size_t i = 0 ; i < collection . count ; i + + ) { <nl> + const cubeb_device_info & device = collection . device [ i ] ; <nl> + if ( device . friendly_name ) { <nl> + device_list . emplace_back ( device . friendly_name ) ; <nl> + } <nl> + } <nl> + cubeb_device_collection_destroy ( ctx , & collection ) ; <nl> + } <nl> + <nl> + cubeb_destroy ( ctx ) ; <nl> + return device_list ; <nl> + } <nl> + <nl> + } / / namespace AudioCore <nl> new file mode 100644 <nl> index 00000000000 . . d07113f1faf <nl> mmm / dev / null <nl> ppp b / src / audio_core / cubeb_sink . h <nl> <nl> + / / Copyright 2018 yuzu Emulator Project <nl> + / / Licensed under GPLv2 or any later version <nl> + / / Refer to the license . txt file included . <nl> + <nl> + # pragma once <nl> + <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include < cubeb / cubeb . h > <nl> + <nl> + # include " audio_core / sink . h " <nl> + <nl> + namespace AudioCore { <nl> + <nl> + class CubebSink final : public Sink { <nl> + public : <nl> + explicit CubebSink ( std : : string device_id ) ; <nl> + ~ CubebSink ( ) override ; <nl> + <nl> + SinkStream & AcquireSinkStream ( u32 sample_rate , u32 num_channels ) override ; <nl> + <nl> + private : <nl> + cubeb * ctx { } ; <nl> + cubeb_devid output_device { } ; <nl> + std : : vector < SinkStreamPtr > sink_streams ; <nl> + } ; <nl> + <nl> + std : : vector < std : : string > ListCubebSinkDevices ( ) ; <nl> + <nl> + } / / namespace AudioCore <nl> mmm a / src / audio_core / sink_details . cpp <nl> ppp b / src / audio_core / sink_details . cpp <nl> <nl> # include < vector > <nl> # include " audio_core / null_sink . h " <nl> # include " audio_core / sink_details . h " <nl> + # ifdef HAVE_CUBEB <nl> + # include " audio_core / cubeb_sink . h " <nl> + # endif <nl> # include " common / logging / log . h " <nl> <nl> namespace AudioCore { <nl> <nl> / / g_sink_details is ordered in terms of desirability , with the best choice at the top . <nl> const std : : vector < SinkDetails > g_sink_details = { <nl> + # ifdef HAVE_CUBEB <nl> + SinkDetails { " cubeb " , & std : : make_unique < CubebSink , std : : string > , & ListCubebSinkDevices } , <nl> + # endif <nl> SinkDetails { " null " , & std : : make_unique < NullSink , std : : string > , <nl> [ ] { return std : : vector < std : : string > { " null " } ; } } , <nl> } ; <nl> mmm a / src / audio_core / stream . cpp <nl> ppp b / src / audio_core / stream . cpp <nl> <nl> # include " core / core_timing . h " <nl> # include " core / core_timing_util . h " <nl> <nl> + # include " audio_core / sink . h " <nl> + # include " audio_core / sink_details . h " <nl> # include " audio_core / stream . h " <nl> <nl> namespace AudioCore { <nl> u32 Stream : : GetSampleSize ( ) const { <nl> return GetNumChannels ( ) * 2 ; <nl> } <nl> <nl> + Stream : : Stream ( u32 sample_rate , Format format , ReleaseCallback & & release_callback , <nl> + SinkStream & sink_stream ) <nl> + : sample_rate { sample_rate } , format { format } , release_callback { std : : move ( release_callback ) } , <nl> + sink_stream { sink_stream } { <nl> + <nl> release_event = CoreTiming : : RegisterEvent ( <nl> " Stream : : Release " , [ this ] ( u64 userdata , int cycles_late ) { ReleaseActiveBuffer ( ) ; } ) ; <nl> } <nl> void Stream : : PlayNextBuffer ( ) { <nl> active_buffer = queued_buffers . front ( ) ; <nl> queued_buffers . pop ( ) ; <nl> <nl> + sink_stream . EnqueueSamples ( GetNumChannels ( ) , <nl> + reinterpret_cast < const s16 * > ( active_buffer - > GetData ( ) . data ( ) ) , <nl> + active_buffer - > GetData ( ) . size ( ) / GetSampleSize ( ) ) ; <nl> + <nl> CoreTiming : : ScheduleEventThreadsafe ( GetBufferReleaseCycles ( * active_buffer ) , release_event , { } ) ; <nl> } <nl> <nl> mmm a / src / audio_core / stream . h <nl> ppp b / src / audio_core / stream . h <nl> <nl> # include < queue > <nl> <nl> # include " audio_core / buffer . h " <nl> + # include " audio_core / sink_stream . h " <nl> # include " common / assert . h " <nl> # include " common / common_types . h " <nl> # include " core / core_timing . h " <nl> class Stream { <nl> / / / Callback function type , used to change guest state on a buffer being released <nl> using ReleaseCallback = std : : function < void ( ) > ; <nl> <nl> - Stream ( int sample_rate , Format format , ReleaseCallback & & release_callback ) ; <nl> + Stream ( u32 sample_rate , Format format , ReleaseCallback & & release_callback , <nl> + SinkStream & sink_stream ) ; <nl> <nl> / / / Plays the audio stream <nl> void Play ( ) ; <nl> class Stream { <nl> / / / Gets the number of core cycles when the specified buffer will be released <nl> s64 GetBufferReleaseCycles ( const Buffer & buffer ) const ; <nl> <nl> - int sample_rate ; / / / < Sample rate of the stream <nl> + u32 sample_rate ; / / / < Sample rate of the stream <nl> Format format ; / / / < Format of the stream <nl> ReleaseCallback release_callback ; / / / < Buffer release callback for the stream <nl> State state { State : : Stopped } ; / / / < Playback state of the stream <nl> class Stream { <nl> BufferPtr active_buffer ; / / / < Actively playing buffer in the stream <nl> std : : queue < BufferPtr > queued_buffers ; / / / < Buffers queued to be played in the stream <nl> std : : queue < BufferPtr > released_buffers ; / / / < Buffers recently released from the stream <nl> + SinkStream & sink_stream ; / / / < Output sink for the stream <nl> } ; <nl> <nl> using StreamPtr = std : : shared_ptr < Stream > ; <nl>
audio_core : Implement Sink and SinkStream interfaces with cubeb .
yuzu-emu/yuzu
f437c11caf2c1afc0b7d0fdb808be10d7b1adfcf
2018-07-31T01:45:24Z
mmm a / validation - test / Evolution / test_backward_deploy_conformance . swift <nl> ppp b / validation - test / Evolution / test_backward_deploy_conformance . swift <nl> <nl> / / RUN : % target - resilience - test - - backward - deployment <nl> / / REQUIRES : executable_test <nl> <nl> + / / XFAIL : use_os_stdlib <nl> + <nl> import StdlibUnittest <nl> import backward_deploy_conformance <nl> <nl>
Merge pull request from slavapestov / disable - backward - deployment - test - on - backward - deployment - bot
apple/swift
1a59837e5cc936680b54b915bd59aeeb669afa80
2020-02-20T21:18:26Z
mmm a / test / cctest / test - disasm - arm64 . cc <nl> ppp b / test / cctest / test - disasm - arm64 . cc <nl> TEST_ ( debug ) { <nl> <nl> / / All debug codes should produce the same instruction , and the debug code <nl> / / can be any uint32_t . <nl> - COMPARE ( debug ( " message " , 0 , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 1 , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 0xffff , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 0x10000 , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 0x7fffffff , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 0x80000000u , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> - COMPARE ( debug ( " message " , 0xffffffffu , BREAK ) , " hlt # 0xdeb0 " ) ; <nl> + # ifdef USE_SIMULATOR <nl> + const char * expected_instruction = " hlt # 0xdeb0 " ; <nl> + # else <nl> + const char * expected_instruction = " brk # 0x0 " ; <nl> + # endif <nl> + <nl> + COMPARE ( debug ( " message " , 0 , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 1 , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 0xffff , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 0x10000 , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 0x7fffffff , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 0x80000000u , BREAK ) , expected_instruction ) ; <nl> + COMPARE ( debug ( " message " , 0xffffffffu , BREAK ) , expected_instruction ) ; <nl> <nl> CLEANUP ( ) ; <nl> } <nl>
[ arm64 ] [ cctest ] Fix disassembly debug test on hardware .
v8/v8
527f541fe8be3e242eb2d6ca2b67027aa8de6bd6
2017-07-14T08:39:32Z
mmm a / editor / editor_autoload_settings . cpp <nl> ppp b / editor / editor_autoload_settings . cpp <nl> void EditorAutoloadSettings : : _autoload_add ( ) { <nl> autoload_add_path - > get_line_edit ( ) - > set_text ( " " ) ; <nl> <nl> autoload_add_name - > set_text ( " " ) ; <nl> + add_autoload - > set_disabled ( true ) ; <nl> } <nl> <nl> void EditorAutoloadSettings : : _autoload_selected ( ) { <nl> void EditorAutoloadSettings : : _autoload_open ( const String & fpath ) { <nl> <nl> void EditorAutoloadSettings : : _autoload_file_callback ( const String & p_path ) { <nl> <nl> - autoload_add_name - > set_text ( p_path . get_file ( ) . get_basename ( ) ) ; <nl> + / / Convert the file name to PascalCase , which is the convention for classes in GDScript . <nl> + const String class_name = p_path . get_file ( ) . get_basename ( ) . capitalize ( ) . replace ( " " , " " ) ; <nl> + <nl> + / / If the name collides with a built - in class , prefix the name to make it possible to add without having to edit the name . <nl> + / / The prefix is subjective , but it provides better UX than leaving the Add button disabled : ) <nl> + const String prefix = ClassDB : : class_exists ( class_name ) ? " Global " : " " ; <nl> + <nl> + autoload_add_name - > set_text ( prefix + class_name ) ; <nl> + add_autoload - > set_disabled ( false ) ; <nl> + } <nl> + <nl> + void EditorAutoloadSettings : : _autoload_text_entered ( const String p_name ) { <nl> + <nl> + if ( autoload_add_path - > get_line_edit ( ) - > get_text ( ) ! = " " & & _autoload_name_is_valid ( p_name , NULL ) ) { <nl> + _autoload_add ( ) ; <nl> + } <nl> + } <nl> + <nl> + void EditorAutoloadSettings : : _autoload_path_text_changed ( const String p_path ) { <nl> + <nl> + add_autoload - > set_disabled ( <nl> + p_path = = " " | | ! _autoload_name_is_valid ( autoload_add_name - > get_text ( ) , NULL ) ) ; <nl> + } <nl> + <nl> + void EditorAutoloadSettings : : _autoload_text_changed ( const String p_name ) { <nl> + <nl> + add_autoload - > set_disabled ( <nl> + autoload_add_path - > get_line_edit ( ) - > get_text ( ) = = " " | | ! _autoload_name_is_valid ( p_name , NULL ) ) ; <nl> } <nl> <nl> Node * EditorAutoloadSettings : : _create_autoload ( const String & p_path ) { <nl> void EditorAutoloadSettings : : update_autoload ( ) { <nl> item - > set_editable ( 2 , true ) ; <nl> item - > set_text ( 2 , TTR ( " Enable " ) ) ; <nl> item - > set_checked ( 2 , info . is_singleton ) ; <nl> - item - > add_button ( 3 , get_icon ( " FileList " , " EditorIcons " ) , BUTTON_OPEN ) ; <nl> + item - > add_button ( 3 , get_icon ( " Load " , " EditorIcons " ) , BUTTON_OPEN ) ; <nl> item - > add_button ( 3 , get_icon ( " MoveUp " , " EditorIcons " ) , BUTTON_MOVE_UP ) ; <nl> item - > add_button ( 3 , get_icon ( " MoveDown " , " EditorIcons " ) , BUTTON_MOVE_DOWN ) ; <nl> item - > add_button ( 3 , get_icon ( " Remove " , " EditorIcons " ) , BUTTON_DELETE ) ; <nl> void EditorAutoloadSettings : : _bind_methods ( ) { <nl> ClassDB : : bind_method ( " _autoload_edited " , & EditorAutoloadSettings : : _autoload_edited ) ; <nl> ClassDB : : bind_method ( " _autoload_button_pressed " , & EditorAutoloadSettings : : _autoload_button_pressed ) ; <nl> ClassDB : : bind_method ( " _autoload_activated " , & EditorAutoloadSettings : : _autoload_activated ) ; <nl> + ClassDB : : bind_method ( " _autoload_path_text_changed " , & EditorAutoloadSettings : : _autoload_path_text_changed ) ; <nl> ClassDB : : bind_method ( " _autoload_text_entered " , & EditorAutoloadSettings : : _autoload_text_entered ) ; <nl> + ClassDB : : bind_method ( " _autoload_text_changed " , & EditorAutoloadSettings : : _autoload_text_changed ) ; <nl> ClassDB : : bind_method ( " _autoload_open " , & EditorAutoloadSettings : : _autoload_open ) ; <nl> ClassDB : : bind_method ( " _autoload_file_callback " , & EditorAutoloadSettings : : _autoload_file_callback ) ; <nl> <nl> EditorAutoloadSettings : : EditorAutoloadSettings ( ) { <nl> autoload_add_path - > set_h_size_flags ( SIZE_EXPAND_FILL ) ; <nl> autoload_add_path - > get_file_dialog ( ) - > set_mode ( EditorFileDialog : : MODE_OPEN_FILE ) ; <nl> autoload_add_path - > get_file_dialog ( ) - > connect ( " file_selected " , this , " _autoload_file_callback " ) ; <nl> + autoload_add_path - > get_line_edit ( ) - > connect ( " text_changed " , this , " _autoload_path_text_changed " ) ; <nl> + <nl> hbc - > add_child ( autoload_add_path ) ; <nl> <nl> l = memnew ( Label ) ; <nl> EditorAutoloadSettings : : EditorAutoloadSettings ( ) { <nl> autoload_add_name = memnew ( LineEdit ) ; <nl> autoload_add_name - > set_h_size_flags ( SIZE_EXPAND_FILL ) ; <nl> autoload_add_name - > connect ( " text_entered " , this , " _autoload_text_entered " ) ; <nl> + autoload_add_name - > connect ( " text_changed " , this , " _autoload_text_changed " ) ; <nl> hbc - > add_child ( autoload_add_name ) ; <nl> <nl> - Button * add_autoload = memnew ( Button ) ; <nl> + add_autoload = memnew ( Button ) ; <nl> add_autoload - > set_text ( TTR ( " Add " ) ) ; <nl> add_autoload - > connect ( " pressed " , this , " _autoload_add " ) ; <nl> + / / The button will be enabled once a valid name is entered ( either automatically or manually ) . <nl> + add_autoload - > set_disabled ( true ) ; <nl> hbc - > add_child ( add_autoload ) ; <nl> <nl> tree = memnew ( Tree ) ; <nl> mmm a / editor / editor_autoload_settings . h <nl> ppp b / editor / editor_autoload_settings . h <nl> class EditorAutoloadSettings : public VBoxContainer { <nl> Tree * tree ; <nl> EditorLineEditFileChooser * autoload_add_path ; <nl> LineEdit * autoload_add_name ; <nl> + Button * add_autoload ; <nl> <nl> bool _autoload_name_is_valid ( const String & p_name , String * r_error = NULL ) ; <nl> <nl> class EditorAutoloadSettings : public VBoxContainer { <nl> void _autoload_edited ( ) ; <nl> void _autoload_button_pressed ( Object * p_item , int p_column , int p_button ) ; <nl> void _autoload_activated ( ) ; <nl> - void _autoload_text_entered ( String ) { _autoload_add ( ) ; } <nl> + void _autoload_path_text_changed ( const String p_path ) ; <nl> + void _autoload_text_entered ( const String p_name ) ; <nl> + void _autoload_text_changed ( const String p_name ) ; <nl> void _autoload_open ( const String & fpath ) ; <nl> void _autoload_file_callback ( const String & p_path ) ; <nl> Node * _create_autoload ( const String & p_path ) ; <nl>
Improve the AutoLoad editor UX
godotengine/godot
352be7dbcc1aa782a34381325e89404aad06a6b9
2020-01-31T10:51:21Z
mmm a / lib / IRGen / GenProto . cpp <nl> ppp b / lib / IRGen / GenProto . cpp <nl> static llvm : : Value * computeResilientWitnessTableIndex ( <nl> auto ptrSize = dataLayout . getTypeAllocSizeInBits ( IGF . IGM . Int8PtrTy ) ; <nl> assert ( protoReqSize > = ptrSize & & " > 64 - bit pointers ? " ) ; <nl> assert ( ( protoReqSize % ptrSize = = 0 ) & & " Must be evenly divisible " ) ; <nl> - unsigned factor = ( protoReqSize / ptrSize ) * 8 ; <nl> + ( void ) ptrSize ; <nl> + unsigned factor = protoReqSize / 8 ; <nl> auto factorConstant = llvm : : ConstantInt : : get ( IGF . IGM . IntPtrTy , factor ) ; <nl> return IGF . Builder . CreateUDiv ( offset , factorConstant ) ; <nl> } <nl> mmm a / test / IRGen / protocol_resilience_descriptors . swift <nl> ppp b / test / IRGen / protocol_resilience_descriptors . swift <nl> where Element : ProtocolWithRequirements , Element . T = = Y { <nl> <nl> / / CHECK - USAGE : define { { ( dllexport ) ? } } { { ( protected ) ? } } swiftcc % swift . type * @ " $ S31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF " ( % swift . type * , % swift . type * [ [ PWD : % . * ] ] , i8 * * [ [ WTABLE : % . * ] ] ) <nl> public func assocTypeMetadata < PWR : ProtocolWithRequirements > ( _ : PWR . Type ) - > PWR . T . Type { <nl> - / / CHECK - USAGE : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % PWR . ProtocolWithRequirements , [ [ INT ] ] udiv ( [ [ INT ] ] sub ( [ [ INT ] ] ptrtoint ( % swift . protocol_requirement * @ " $ S1T18resilient_protocol24ProtocolWithRequirementsPTl " to [ [ INT ] ] ) , [ [ INT ] ] ptrtoint ( % swift . protocol_requirement * @ " $ S18resilient_protocol24ProtocolWithRequirementsTL " to [ [ INT ] ] ) ) , [ [ INT ] ] { { ( 8 | 16 ) } } ) <nl> - / / CHECK - USAGE : load i8 * , i8 * * [ [ WITNESS_ADDR ] ] , align 8 <nl> + / / CHECK - USAGE : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % PWR . ProtocolWithRequirements , [ [ INT ] ] udiv ( [ [ INT ] ] sub ( [ [ INT ] ] ptrtoint ( % swift . protocol_requirement * @ " $ S1T18resilient_protocol24ProtocolWithRequirementsPTl " to [ [ INT ] ] ) , [ [ INT ] ] ptrtoint ( % swift . protocol_requirement * @ " $ S18resilient_protocol24ProtocolWithRequirementsTL " to [ [ INT ] ] ) ) , [ [ INT ] ] 8 <nl> + / / CHECK - USAGE : load i8 * , i8 * * [ [ WITNESS_ADDR ] ] , align { { ( 4 | 8 ) } } <nl> return PWR . T . self <nl> } <nl> mmm a / test / IRGen / witness_table_indirect_conformances . swift <nl> ppp b / test / IRGen / witness_table_indirect_conformances . swift <nl> struct Z : P2 { <nl> / / CHECK : @ " $ S35witness_table_indirect_conformances1WVAA2P3AAWP " = hidden constant [ 5 x i8 * ] [ <nl> / / CHECK - SAME : @ " $ S35witness_table_indirect_conformances1WVAA2P3AAMc " <nl> / / CHECK - SAME : i8 * bitcast ( i8 * * ( ) * @ " $ S35witness_table_indirect_conformances1YVAA1QAAWa " to i8 * ) , <nl> - / / CHECK - SAME : i8 * bitcast ( % swift . metadata_response ( i64 ) * @ " $ S35witness_table_indirect_conformances1ZVMa " to i8 * ) , <nl> + / / CHECK - SAME : i8 * bitcast ( % swift . metadata_response ( [ [ INT ] ] ) * @ " $ S35witness_table_indirect_conformances1ZVMa " to i8 * ) , <nl> / / CHECK - SAME : i8 * bitcast ( void ( % T35witness_table_indirect_conformances1ZV * , % T35witness_table_indirect_conformances1WV * , % swift . type * , i8 * * ) * @ " $ S35witness_table_indirect_conformances1WVAA2P3A2aDP08getAssocE00gE0QzyFTW " to i8 * ) ] <nl> struct W : P3 { <nl> typealias AssocP3 = Z <nl>
[ IRGen ] Fix associated type resilience for 32 - bit platforms .
apple/swift
0fa1590e16c9cbc43950f63571d9a6236c5dbde6
2018-09-15T05:29:38Z
mmm a / tensorflow / python / util / nest . py <nl> ppp b / tensorflow / python / util / nest . py <nl> <nl> " type { shallow_type } , while shallow structure has type { input_type } . " ) <nl> <nl> _INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = ( <nl> - " The input_tree has fewer elements than the input_tree . Input structure " <nl> + " The input_tree has fewer elements than the shallow_tree . Input structure " <nl> " has length { input_size } , while shallow structure has length " <nl> " { shallow_size } . " ) <nl> <nl>
Fix error message
tensorflow/tensorflow
6b08486ebdd993a516bb4eb7feade30f6977fced
2019-04-22T22:26:28Z