<s> import collections <EOL> from . . import scalartypes as scalars <EOL> from . . import ir <EOL> def allocateRequiredConstants ( pool , long_irs ) : <EOL> narrow_pairs = collections . Counter ( ) <EOL> wide_pairs = collections . Counter ( ) <EOL> alt_lens = { } <EOL> for _ir in long_irs : <EOL> for ins in _ir . flat_instructions : <EOL> if isinstance ( ins , ir . PrimConstant ) : <EOL> key = ins . cpool_key ( ) <EOL> alt_lens [ key ] = len ( ins . bytecode ) <EOL> if scalars . iswide ( ins . st ) : <EOL> if len ( ins . bytecode ) > <NUM_LIT:3> : <EOL> wide_pairs [ key ] += <NUM_LIT:1> <EOL> else : <EOL> if len ( ins . bytecode ) > <NUM_LIT:2> : <EOL> narrow_pairs [ key ] += <NUM_LIT:1> <EOL> for x in pool . vals : <EOL> del narrow_pairs [ x ] <EOL> del wide_pairs [ x ] <EOL> if pool . space ( ) >= len ( narrow_pairs ) + <NUM_LIT:2> * len ( wide_pairs ) and pool . lowspace ( ) > <NUM_LIT:0> : <EOL> most_common = sorted ( narrow_pairs , key = lambda p : ( - narrow_pairs [ p ] , p ) ) <EOL> for key in most_common [ : pool . lowspace ( ) ] : <EOL> pool . insertDirectly ( key , True ) <EOL> del narrow_pairs [ key ] <EOL> scores = { } <EOL> for p , count in narrow_pairs . items ( ) : <EOL> scores [ p ] = ( alt_lens [ p ] - <NUM_LIT:3> ) * count <EOL> for p , count in wide_pairs . items ( ) : <EOL> scores [ p ] = ( alt_lens [ p ] - <NUM_LIT:3> ) * count <EOL> narrowq = sorted ( narrow_pairs , key = lambda p : ( scores [ p ] , p ) ) <EOL> wideq = sorted ( wide_pairs , key = lambda p : ( scores [ p ] , p ) ) <EOL> while pool . space ( ) >= <NUM_LIT:1> and ( narrowq or wideq ) : <EOL> if not narrowq and pool . space ( ) < <NUM_LIT:2> : <EOL> break <EOL> wscore = sum ( scores [ p ] for p in wideq [ - <NUM_LIT:1> : ] ) <EOL> nscore = sum ( scores [ p ] for p in narrowq [ - <NUM_LIT:2> : ] ) <EOL> if pool . space ( ) >= <NUM_LIT:2> and wscore > nscore and wscore > <NUM_LIT:0> : <EOL> pool . insertDirectly ( wideq . pop ( ) , False ) <EOL> elif nscore > <NUM_LIT:0> : <EOL> pool . insertDirectly ( narrowq . pop ( ) , True ) <EOL> else : <EOL> break </s>
