text
stringlengths 1
1.05M
|
|---|
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Mult.asm
// Multiplies R0 and R1 and stores the result in R2.
// (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.)
//
// This program only needs to handle arguments that satisfy
// R0 >= 0, R1 >= 0, and R0*R1 < 32768.
// Put your code here.
@R1
D=M
@i
M=D
@total
M=0
(LOOP)
@i
D=M-1
@i
M=D
@STOP
D;JLT
@R0
D=M
@total
M=M+D
@LOOP
0;JMP
(STOP)
@total
D=M
@R2
M=D
(END)
@END
0;JMP
|
; A113935: a(n) = prime(n) + 3.
; Submitted by Jamie Morken(s3)
; 5,6,8,10,14,16,20,22,26,32,34,40,44,46,50,56,62,64,70,74,76,82,86,92,100,104,106,110,112,116,130,134,140,142,152,154,160,166,170,176,182,184,194,196,200,202,214,226,230,232,236,242,244,254,260,266,272,274,280,284,286,296,310,314,316,320,334,340,350,352,356,362,370,376,382,386,392,400,404,412,422,424,434,436,442,446,452,460,464,466,470,482,490,494,502,506,512,524,526,544
mul $0,2
max $0,1
seq $0,173919 ; Numbers that are prime or one less than a prime.
add $0,3
|
# $Id: 04_sub_r0.asm,v 1.3 2001/03/22 00:38:59 ellard Exp $
#
# Copyright 1999-2001 by the President and Fellows of Harvard College.
# See LICENSE.txt for license information.
#
#@ tests sub for r0.
# OK
lc r2, -100
lc r3, 100
sub r0, r2, r3
add r5, r1, r0
hlt
|
; See also data/items/heal_status.asm
HeldStatusHealingEffects:
db HELD_HEAL_POISON, 1 << PSN
db HELD_HEAL_FREEZE, 1 << FRZ
db HELD_HEAL_BURN, 1 << BRN
db HELD_HEAL_SLEEP, SLP
db HELD_HEAL_PARALYZE, 1 << PAR
db HELD_HEAL_STATUS, ALL_STATUS
db -1 ; end
|
;;
;; Copyright (c) 2021-2022, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/mb_mgr_datastruct.asm"
%include "include/transpose_avx512.asm"
%include "include/imb_job.asm"
%include "include/constant_lookup.asm"
mksection .rodata
default rel
align 64
dw_len_to_db_mask:
dq 0x0000000000000000, 0x000000000000000f, 0x00000000000000ff, 0x0000000000000fff
dq 0x000000000000ffff, 0x00000000000fffff, 0x0000000000ffffff, 0x000000000fffffff
dq 0x00000000ffffffff, 0x0000000fffffffff, 0x000000ffffffffff, 0x00000fffffffffff
dq 0x0000ffffffffffff, 0x000fffffffffffff, 0x00ffffffffffffff, 0x0fffffffffffffff
dq 0xffffffffffffffff, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000
align 64
const_byte_shuff_mask:
times 4 dq 0x0405060700010203, 0x0c0d0e0f08090a0b
align 64
const_byte_mix_col_rev:
dd 0x00030201, 0x04070605
dd 0x080b0a09, 0x0c0f0e0d
dd 0x00030201, 0x04070605
dd 0x080b0a09, 0x0c0f0e0d
dd 0x00030201, 0x04070605
dd 0x080b0a09, 0x0c0f0e0d
dd 0x00030201, 0x04070605
dd 0x080b0a09, 0x0c0f0e0d
align 64
const_fixup:
;; MS bits in quad word shuffled according to AES mix col matrix mul
times 8 dq 0x273f372f071f170f
align 64
const_fixup_mask:
times 8 dq 0x7272727272727272
align 64
const_fixed_rotate_mask:
;; inverse of AESENC shift rows operation
times 4 dq 0x0b0e0104070a0d00, 0x0306090c0f020508
align 64
const_mulalpha_map_00_0f:
dq 0xe19fcf1300000000, 0x8a08f8356b973726
dq 0x3718a15fd6876e4c, 0x5c8f9679bd10596a
dq 0xe438138b05a7dc98, 0x8faf24ad6e30ebbe
dq 0x32bf7dc7d320b2d4, 0x59284ae1b8b785f2
dq 0xeb78de8a0ae71199, 0x80efe9ac617026bf
dq 0x3dffb0c6dc607fd5, 0x566887e0b7f748f3
dq 0xeedf02120f40cd01, 0x8548353464d7fa27
dq 0x38586c5ed9c7a34d, 0x53cf5b78b250946b
dq 0xf5f8ed881467229b, 0x9e6fdaae7ff015bd
dq 0x237f83c4c2e04cd7, 0x48e8b4e2a9777bf1
dq 0xf05f311011c0fe03, 0x9bc806367a57c925
dq 0x26d85f5cc747904f, 0x4d4f687aacd0a769
dq 0xff1ffc111e803302, 0x9488cb3775170424
dq 0x2998925dc8075d4e, 0x420fa57ba3906a68
dq 0xfab820891b27ef9a, 0x912f17af70b0d8bc
dq 0x2c3f4ec5cda081d6, 0x47a879e3a637b6f0
dq 0xc9518b8c28ce449f, 0xa2c6bcaa435973b9
dq 0x1fd6e5c0fe492ad3, 0x7441d2e695de1df5
dq 0xccf657142d699807, 0xa761603246feaf21
dq 0x1a713958fbeef64b, 0x71e60e7e9079c16d
dq 0xc3b69a1522295506, 0xa821ad3349be6220
dq 0x1531f459f4ae3b4a, 0x7ea6c37f9f390c6c
dq 0xc611468d278e899e, 0xad8671ab4c19beb8
dq 0x109628c1f109e7d2, 0x7b011fe79a9ed0f4
dq 0xdd36a9173ca96604, 0xb6a19e31573e5122
dq 0x0bb1c75bea2e0848, 0x6026f07d81b93f6e
dq 0xd891758f390eba9c, 0xb30642a952998dba
dq 0x0e161bc3ef89d4d0, 0x65812ce5841ee3f6
dq 0xd7d1b88e364e779d, 0xbc468fa85dd940bb
dq 0x0156d6c2e0c919d1, 0x6ac1e1e48b5e2ef7
dq 0xd276641633e9ab05, 0xb9e15330587e9c23
dq 0x04f10a5ae56ec549, 0x6f663d7c8ef9f26f
align 64
const_mulalpha_map_80_8f:
dq 0xb1aa478450358897, 0xda3d70a23ba2bfb1
dq 0x672d29c886b2e6db, 0x0cba1eeeed25d1fd
dq 0xb40d9b1c5592540f, 0xdf9aac3a3e056329
dq 0x628af55083153a43, 0x091dc276e8820d65
dq 0xbb4d561d5ad2990e, 0xd0da613b3145ae28
dq 0x6dca38518c55f742, 0x065d0f77e7c2c064
dq 0xbeea8a855f754596, 0xd57dbda334e272b0
dq 0x686de4c989f22bda, 0x03fad3efe2651cfc
dq 0xa5cd651f4452aa0c, 0xce5a52392fc59d2a
dq 0x734a0b5392d5c440, 0x18dd3c75f942f366
dq 0xa06ab98741f57694, 0xcbfd8ea12a6241b2
dq 0x76edd7cb977218d8, 0x1d7ae0edfce52ffe
dq 0xaf2a74864eb5bb95, 0xc4bd43a025228cb3
dq 0x79ad1aca9832d5d9, 0x123a2decf3a5e2ff
dq 0xaa8da81e4b12670d, 0xc11a9f382085502b
dq 0x7c0ac6529d950941, 0x179df174f6023e67
dq 0x9964031b78fbcc08, 0xf2f3343d136cfb2e
dq 0x4fe36d57ae7ca244, 0x24745a71c5eb9562
dq 0x9cc3df837d5c1090, 0xf754e8a516cb27b6
dq 0x4a44b1cfabdb7edc, 0x21d386e9c04c49fa
dq 0x93831282721cdd91, 0xf81425a4198beab7
dq 0x45047ccea49bb3dd, 0x2e934be8cf0c84fb
dq 0x9624ce1a77bb0109, 0xfdb3f93c1c2c362f
dq 0x40a3a056a13c6f45, 0x2b349770caab5863
dq 0x8d0321806c9cee93, 0xe69416a6070bd9b5
dq 0x5b844fccba1b80df, 0x301378ead18cb7f9
dq 0x88a4fd18693b320b, 0xe333ca3e02ac052d
dq 0x5e239354bfbc5c47, 0x35b4a472d42b6b61
dq 0x87e43019667bff0a, 0xec73073f0decc82c
dq 0x51635e55b0fc9146, 0x3af46973db6ba660
dq 0x8243ec8163dc2392, 0xe9d4dba7084b14b4
dq 0x54c482cdb55b4dde, 0x3f53b5ebdecc7af8
align 64
const_divalpha_map_00_0f:
dq 0x180f40cd00000000, 0x2811c0fe301e8033
dq 0x7833e9ab603ca966, 0x482d699850222955
dq 0xd877bb01c078fbcc, 0xe8693b32f0667bff
dq 0xb84b1267a04452aa, 0x88559254905ad299
dq 0x31ff1ffc29f05f31, 0x01e19fcf19eedf02
dq 0x51c3b69a49ccf657, 0x61dd36a979d27664
dq 0xf187e430e988a4fd, 0xc1996403d99624ce
dq 0x91bb4d5689b40d9b, 0xa1a5cd65b9aa8da8
dq 0x4a46feaf5249be62, 0x7a587e9c62573e51
dq 0x2a7a57c932751704, 0x1a64d7fa026b9737
dq 0x8a3e0563923145ae, 0xba208550a22fc59d
dq 0xea02ac05f20decc8, 0xda1c2c36c2136cfb
dq 0x63b6a19e7bb9e153, 0x53a821ad4ba76160
dq 0x038a08f81b854835, 0x339488cb2b9bc806
dq 0xa3ce5a52bbc11a9f, 0x93d0da618bdf9aac
dq 0xc3f2f334dbfdb3f9, 0xf3ec7307ebe333ca
dq 0xbc9d9509a492d5c4, 0x8c83153a948c55f7
dq 0xdca13c6fc4ae7ca2, 0xecbfbc5cf4b0fc91
dq 0x7ce56ec564ea2e08, 0x4cfbeef654f4ae3b
dq 0x1cd9c7a304d6876e, 0x2cc7479034c8075d
dq 0x956dca388d628af5, 0xa5734a0bbd7c0ac6
dq 0xf551635eed5e2393, 0xc54fe36ddd40a3a0
dq 0x551531f44d1a7139, 0x650bb1c77d04f10a
dq 0x352998922d26d85f, 0x053718a11d38586c
dq 0xeed42b6bf6db6ba6, 0xdecaab58c6c5eb95
dq 0x8ee8820d96e7c2c0, 0xbef6023ea6f942f3
dq 0x2eacd0a736a3906a, 0x1eb2509406bd1059
dq 0x4e9079c1569f390c, 0x7e8ef9f26681b93f
dq 0xc724745adf2b3497, 0xf73af469ef35b4a4
dq 0xa718dd3cbf179df1, 0x97065d0f8f091dc2
dq 0x075c8f961f53cf5b, 0x37420fa52f4d4f68
dq 0x676026f07f6f663d, 0x577ea6c34f71e60e
align 64
const_divalpha_map_80_8f:
dq 0xf98243ece18d0321, 0xc99cc3dfd1938312
dq 0x99beea8a81b1aa47, 0xa9a06ab9b1af2a74
dq 0x39fab82021f5f8ed, 0x09e4381311eb78de
dq 0x59c6114641c9518b, 0x69d8917571d7d1b8
dq 0xd0721cddc87d5c10, 0xe06c9ceef863dc23
dq 0xb04eb5bba841f576, 0x80503588985f7545
dq 0x100ae7110805a7dc, 0x20146722381b27ef
dq 0x70364e7768390eba, 0x4028ce4458278e89
dq 0xabcbfd8eb3c4bd43, 0x9bd57dbd83da3d70
dq 0xcbf754e8d3f81425, 0xfbe9d4dbe3e69416
dq 0x6bb3064273bc468f, 0x5bad867143a2c6bc
dq 0x0b8faf241380efe9, 0x3b912f17239e6fda
dq 0x823ba2bf9a34e272, 0xb225228caa2a6241
dq 0xe2070bd9fa084b14, 0xd2198beaca16cb27
dq 0x424359735a4c19be, 0x725dd9406a52998d
dq 0x227ff0153a70b0d8, 0x126170260a6e30eb
dq 0x5d109628451fd6e5, 0x6d0e161b750156d6
dq 0x3d2c3f4e25237f83, 0x0d32bf7d153dffb0
dq 0x9d686de485672d29, 0xad76edd7b579ad1a
dq 0xfd54c482e55b844f, 0xcd4a44b1d545047c
dq 0x74e0c9196cef89d4, 0x44fe492a5cf109e7
dq 0x14dc607f0cd320b2, 0x24c2e04c3ccda081
dq 0xb49832d5ac977218, 0x8486b2e69c89f22b
dq 0xd4a49bb3ccabdb7e, 0xe4ba1b80fcb55b4d
dq 0x0f59284a17566887, 0x3f47a8792748e8b4
dq 0x6f65812c776ac1e1, 0x5f7b011f477441d2
dq 0xcf21d386d72e934b, 0xff3f53b5e7301378
dq 0xaf1d7ae0b7123a2d, 0x9f03fad3870cba1e
dq 0x26a9777b3ea637b6, 0x16b7f7480eb8b785
dq 0x4695de1d5e9a9ed0, 0x768b5e2e6e841ee3
dq 0xe6d18cb7fedecc7a, 0xd6cf0c84cec04c49
dq 0x86ed25d19ee2651c, 0xb6f3a5e2aefce52f
align 64
const_transf_map:
dq 0x08A7BE0D0A8FA6C2, 0x9F11D2135945991D
dq 0xC1588D92A4D4E6AE, 0x3BBC4F9D84C897D0
dq 0xEEE34E725327EB2D, 0xDB442F5C4DAA7FDA
dq 0x4C166AC3C5673A3E, 0x19F26270DDD7CC38
dq 0x0386C9614B980910, 0x8C5D546E335A6BA8
dq 0x80F8C682F6F71A41, 0xBA7B2C65B3FEC7C0
dq 0x5FF5730C222AFCB4, 0x143524B2942E6864
dq 0x0743EDDE48BFFB78, 0x46577D74BDE432B6
dq 0x55F38A51B7C4373C, 0x93E1A377AB79CF6C
dq 0x8B7E9A2B5B816DD5, 0x5247A191D385B504
dq 0xF0268720BBD6ECA5, 0x50CB25CEF4894AAF
dq 0xA93D219042D93F00, 0xCDFA5E36F10129E7
dq 0x76A09EFD051B31E5, 0x1CEA569BB075B130
dq 0xFF1588957A6906EF, 0x0B280FD8230EACCA
dq 0x9C3966831E63F918, 0xA27C34D1E81F49E2
dq 0x71ADDFE91202E0B9, 0xDC176040B86F8E96
align 64
dw_e0s:
times 16 dd 0x000000e0
align 64
dw_20s:
times 16 dd 0x00000020
align 64
dw_40s:
times 16 dd 0x00000040
align 64
dw_60s:
times 16 dd 0x00000060
align 64
dw_80s:
times 16 dd 0x00000080
align 64
dw_a0s:
times 16 dd 0x000000a0
align 64
dw_c0s:
times 16 dd 0x000000c0
align 64
all_fs:
times 16 dq 0xffffffffffffffff
mksection .text
%xdefine KEYSTREAM zmm0
%xdefine KEYSTREAM_XMM_TEMP XWORD(KEYSTREAM)
%xdefine FSM1 zmm1
%xdefine FSM2 zmm2
%xdefine FSM3 zmm3
%xdefine FIXED_ROTATE_MASK zmm4
%xdefine FIXED_M_MASK zmm5
%xdefine FIXED_PATTERN_SHUF zmm6
%xdefine FIXED_MAP_TAB_0 zmm7
%xdefine FIXED_MAP_TAB_1 zmm8
%xdefine FIXED_MAP_TAB_2 zmm9
%xdefine FIXED_MAP_TAB_3 zmm10
%xdefine TEMP_27 zmm11
%xdefine TEMP_28 zmm12
%xdefine TEMP_29 zmm13
%xdefine TEMP_30 zmm14
%xdefine TEMP_31 zmm15
%xdefine LFSR_0 zmm16
%xdefine LFSR_1 zmm17
%xdefine LFSR_2 zmm18
%xdefine LFSR_3 zmm19
%xdefine LFSR_4 zmm20
%xdefine LFSR_5 zmm21
%xdefine LFSR_6 zmm22
%xdefine LFSR_7 zmm23
%xdefine LFSR_8 zmm24
%xdefine LFSR_9 zmm25
%xdefine LFSR_10 zmm26
%xdefine LFSR_11 zmm27
%xdefine LFSR_12 zmm28
%xdefine LFSR_13 zmm29
%xdefine LFSR_14 zmm30
%xdefine LFSR_15 zmm31
struc STACK
_keystream: resb (16 * 64)
_gpr_save: resq 8
_rsp_save: resq 1
endstruc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Saves register contents and creates stack frame for key stream
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro SNOW3G_FUNC_START 0
mov rax, rsp
sub rsp, STACK_size
and rsp, ~63
mov [rsp + _gpr_save + 8 * 0], rbx
mov [rsp + _gpr_save + 8 * 1], rbp
mov [rsp + _gpr_save + 8 * 2], r12
mov [rsp + _gpr_save + 8 * 3], r13
mov [rsp + _gpr_save + 8 * 4], r14
mov [rsp + _gpr_save + 8 * 5], r15
%ifndef LINUX
mov [rsp + _gpr_save + 8 * 6], rsi
mov [rsp + _gpr_save + 8 * 7], rdi
%endif
mov [rsp + _rsp_save], rax ;; original SP
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Restores register contents and removes the stack frame
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro SNOW3G_FUNC_END 0
%ifndef SAFE_DATA
vzeroupper
%endif
mov rbx, [rsp + _gpr_save + 8 * 0]
mov rbp, [rsp + _gpr_save + 8 * 1]
mov r12, [rsp + _gpr_save + 8 * 2]
mov r13, [rsp + _gpr_save + 8 * 3]
mov r14, [rsp + _gpr_save + 8 * 4]
mov r15, [rsp + _gpr_save + 8 * 5]
%ifndef LINUX
mov rsi, [rsp + _gpr_save + 8 * 6]
mov rdi, [rsp + _gpr_save + 8 * 7]
%endif
mov rsp, [rsp + _rsp_save] ; original SP
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLOCK FSM
;; Updates FSM state and returns generated key stream for 16 buffers
;; The same macro is used for initialization and working phase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro FSM_CLOCK 19
%define %%FSM_X1 %1 ;; [in/out] zmm with 16 FSM 1 values
%define %%FSM_X2 %2 ;; [in/out] zmm with 16 FSM 2 values
%define %%FSM_X3 %3 ;; [in/out] zmm with 16 FSM 3 values
%define %%LFSR_5 %4 ;; [in] zmm with 16 LFSR 5 values
%define %%LFSR_15 %5 ;; [in] zmm with 16 LFSR 15 values
%define %%OUT_F %6 ;; [out] zmm for generated key streams
%define %%ZERO %7 ;; [clobbered] temporary zmm register
%define %%TEMP_R %8 ;; [clobbered] temporary zmm register
%define %%TEMP_MIX %9 ;; [clobbered] temporary zmm register
%define %%TEMP_NO_MIX %10 ;; [clobbered] temporary zmm register
%define %%TEMP %11 ;; [clobbered] temporary zmm register
%define %%MAP_TAB_0 %12 ;; [in] lookup values for indices 0-3f
%define %%MAP_TAB_1 %13 ;; [in] lookup values for indices 40-7f
%define %%MAP_TAB_2 %14 ;; [in] lookup values for indices 80-bf
%define %%MAP_TAB_3 %15 ;; [in] lookup values for indices c0-ff
%define %%KR1 %16 ;; [clobbered] temporary k-register
%define %%KR2 %17 ;; [clobbered] temporary k-register
%define %%KR3 %18 ;; [clobbered] temporary k-register
%define %%KR4 %19 ;; [clobbered] temporary k-register
;; TEMP_R = S2(FSM[2])
LOOKUP8_64_AVX512_VBMI_4_MAP_TABLES \
%%FSM_X2, %%TEMP_R, %%ZERO, \
%%TEMP_MIX, %%TEMP_NO_MIX, \
%%MAP_TAB_0, %%MAP_TAB_1, \
%%MAP_TAB_2, %%MAP_TAB_3, %%KR1
vpxord %%ZERO, %%ZERO, %%ZERO
vpshufb %%TEMP, %%TEMP_R, FIXED_ROTATE_MASK
;; u32 r = ( FSM[2] + ( FSM[3] ^ LFSR[5] ) ) & 0xffffffff
vpxord %%TEMP_R, %%FSM_X3, %%LFSR_5
vpaddd %%TEMP_R, %%TEMP_R, %%FSM_X2
;; u32 F = ( ( LFSR[15] + FSM[1] ) & 0xffffffff ) ^ FSM[2]
vpaddd %%TEMP_NO_MIX, %%FSM_X1, %%LFSR_15
vpxord %%OUT_F, %%TEMP_NO_MIX, %%FSM_X2
vaesenc %%TEMP_MIX, %%TEMP, %%ZERO
vaesenclast %%TEMP_NO_MIX, %%TEMP, %%ZERO
vpcmpgtb %%KR1, %%ZERO, %%TEMP_NO_MIX
vpshufbitqmb %%KR2, %%TEMP_NO_MIX, FIXED_PATTERN_SHUF
kxorq %%KR3, %%KR1, %%KR2
vmovdqu8 %%ZERO{%%KR3}, FIXED_M_MASK
vpxord %%FSM_X3, %%TEMP_MIX, %%ZERO
;; FSM[2] = S1(FSM[1])
vpxord %%ZERO, %%ZERO, %%ZERO
vpshufb %%TEMP, %%FSM_X1, FIXED_ROTATE_MASK
vaesenc %%FSM_X2, %%TEMP, %%ZERO
;; FSM[1] = R
vmovdqa32 %%FSM_X1, %%TEMP_R
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLOCK FSM
;; Updates FSM state and returns generated key stream for 16 buffers
;; The same macro is used for initialization and working phase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro FSM_CLOCK_NO_VAES 19
%define %%FSM_X1 %1 ;; [in/out] zmm with 16 FSM 1 values
%define %%FSM_X2 %2 ;; [in/out] zmm with 16 FSM 2 values
%define %%FSM_X3 %3 ;; [in/out] zmm with 16 FSM 3 values
%define %%LFSR_5 %4 ;; [in] zmm with 16 LFSR 5 values
%define %%LFSR_15 %5 ;; [in] zmm with 16 LFSR 15 values
%define %%OUT_F %6 ;; [out] zmm for generated key streams
%define %%ZERO %7 ;; [clobbered] temporary zmm register
%define %%TEMP_R %8 ;; [clobbered] temporary zmm register
%define %%TEMP_MIX %9 ;; [clobbered] temporary zmm register
%define %%TEMP_NO_MIX %10 ;; [clobbered] temporary zmm register
%define %%TEMP %11 ;; [clobbered] temporary zmm register
%define %%TEMP_1 %12 ;; [clobbered] temporary zmm register
%define %%TEMP_2 %13 ;; [clobbered] temporary zmm register
%define %%TEMP_3 %14 ;; [clobbered] temporary zmm register
%define %%TEMP_4 %15 ;; [clobbered] temporary zmm register
%define %%KR1 %16 ;; [clobbered] temporary k-register
%define %%KR2 %17 ;; [clobbered] temporary k-register
%define %%KR3 %18 ;; [clobbered] temporary k-register
%define %%KR4 %19 ;; [clobbered] temporary k-register
;; TEMP_R = S2(FSM[2])
LOOKUP8_64_AVX512 %%FSM_X2, %%TEMP_R, {rel const_transf_map}, \
%%ZERO, %%TEMP_MIX, %%TEMP_NO_MIX, %%TEMP, \
%%TEMP_1, %%TEMP_2, \
%%KR1, %%KR2, %%KR3, %%KR4
vpshufb %%TEMP, %%TEMP_R, FIXED_ROTATE_MASK
;; u32 r = ( FSM[2] + ( FSM[3] ^ LFSR[5] ) ) & 0xffffffff
vpxord %%TEMP_R, %%FSM_X3, %%LFSR_5
vpaddd %%TEMP_R, %%TEMP_R, %%FSM_X2
;; u32 F = ( ( LFSR[15] + FSM[1] ) & 0xffffffff ) ^ FSM[2]
vpaddd %%OUT_F, %%FSM_X1, %%LFSR_15
vpxord %%OUT_F, %%OUT_F, %%FSM_X2
vpxord %%ZERO, %%ZERO, %%ZERO
vaesenc XWORD(%%TEMP_MIX), XWORD(%%TEMP), XWORD(%%ZERO)
vaesenclast XWORD(%%TEMP_NO_MIX), XWORD(%%TEMP), XWORD(%%ZERO)
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 1
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vaesenclast XWORD(%%TEMP_3), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%TEMP_MIX, XWORD(%%TEMP_4), 1
vinserti32x4 %%TEMP_NO_MIX, XWORD(%%TEMP_3), 1
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 2
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vaesenclast XWORD(%%TEMP_3), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%TEMP_MIX, XWORD(%%TEMP_4), 2
vinserti32x4 %%TEMP_NO_MIX, XWORD(%%TEMP_3), 2
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 3
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vaesenclast XWORD(%%TEMP_3), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%TEMP_MIX, XWORD(%%TEMP_4), 3
vinserti32x4 %%TEMP_NO_MIX, XWORD(%%TEMP_3), 3
vpcmpgtb %%KR1, %%ZERO, %%TEMP_NO_MIX
vpshufb %%TEMP_NO_MIX, %%TEMP_NO_MIX, [ rel const_byte_mix_col_rev ]
vpcmpgtb %%KR2, %%ZERO, %%TEMP_NO_MIX
kxorq %%KR3, %%KR1, %%KR2
vmovdqu8 %%ZERO{%%KR3}, FIXED_M_MASK
vpxord %%FSM_X3, %%TEMP_MIX, %%ZERO
;; FSM[2] = S1(FSM[1])
vpxord %%ZERO, %%ZERO, %%ZERO
vpshufb %%TEMP, %%FSM_X1, FIXED_ROTATE_MASK
vaesenc XWORD(%%FSM_X2), XWORD(%%TEMP), XWORD(%%ZERO)
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 1
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%FSM_X2, %%FSM_X2, XWORD(%%TEMP_4), 1
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 2
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%FSM_X2, %%FSM_X2, XWORD(%%TEMP_4), 2
vextracti32x4 XWORD(%%TEMP_3), %%TEMP, 3
vaesenc XWORD(%%TEMP_4), XWORD(%%TEMP_3), XWORD(%%ZERO)
vinserti32x4 %%FSM_X2, %%FSM_X2, XWORD(%%TEMP_4), 3
;; FSM[1] = R
vmovdqa32 %%FSM_X1, %%TEMP_R
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; LFSR & FSM INITIALIZATION for a new job
;; - initialize LFSR & FSM for single key-iv pair
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro LFSR_FSM_INIT_SUBMIT 9
%define %%STATE %1 ;; [in] pointer to state structure
%define %%KPOS %2 ;; [in] k-register with lane mask
%define %%KEY %3 ;; [in] address of key
%define %%IV %4 ;; [in] address of iv
%define %%ZTMP1 %5 ;; [clobbered] temporary zmm register
%define %%ZTMP2 %6 ;; [clobbered] temporary zmm register
%define %%ZTMP3 %7 ;; [clobbered] temporary zmm register
%define %%GP1 %8 ;; [clobbered] temporary GP register
%define %%GP2 %9 ;; [clobbered] temporary GP register
;; LFSR 4, 12, 0 and 8
mov DWORD(%%GP1), [%%KEY]
vpbroadcastd %%ZTMP1, DWORD(%%GP1)
not DWORD(%%GP1)
vpbroadcastd %%ZTMP2, DWORD(%%GP1)
movbe DWORD(%%GP2), [%%IV + 8]
vpbroadcastd %%ZTMP3, DWORD(%%GP2)
vmovdqa32 [%%STATE + _snow3g_args_LFSR_4]{%%KPOS}, %%ZTMP1
vpxord %%ZTMP3, %%ZTMP3, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_12]{%%KPOS}, %%ZTMP3
vmovdqa32 [%%STATE + _snow3g_args_LFSR_0]{%%KPOS}, %%ZTMP2
vmovdqa32 [%%STATE + _snow3g_args_LFSR_8]{%%KPOS}, %%ZTMP2
;; LFSR 5, 13, 1 and 9
mov DWORD(%%GP1), [%%KEY + 4]
vpbroadcastd %%ZTMP1, DWORD(%%GP1)
not DWORD(%%GP1)
vpbroadcastd %%ZTMP2, DWORD(%%GP1)
movbe DWORD(%%GP2), [%%IV]
vpbroadcastd %%ZTMP3, DWORD(%%GP2)
vmovdqa32 [%%STATE + _snow3g_args_LFSR_5]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_13]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_1]{%%KPOS}, %%ZTMP2
vpxord %%ZTMP3, %%ZTMP3, %%ZTMP2
vmovdqa32 [%%STATE + _snow3g_args_LFSR_9]{%%KPOS}, %%ZTMP3
;; LFSR 6, 14, 2 and 10
mov DWORD(%%GP1), [%%KEY + 8]
vpbroadcastd %%ZTMP1, DWORD(%%GP1)
not DWORD(%%GP1)
vpbroadcastd %%ZTMP2, DWORD(%%GP1)
movbe DWORD(%%GP2), [%%IV + 4]
vpbroadcastd %%ZTMP3, DWORD(%%GP2)
vmovdqa32 [%%STATE + _snow3g_args_LFSR_6]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_14]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_2]{%%KPOS}, %%ZTMP2
vpxord %%ZTMP3, %%ZTMP3, %%ZTMP2
vmovdqa32 [%%STATE + _snow3g_args_LFSR_10]{%%KPOS}, %%ZTMP3
;; LFSR 7, 15, 3 and 11
mov DWORD(%%GP1), [%%KEY + 12]
vpbroadcastd %%ZTMP1, DWORD(%%GP1)
not DWORD(%%GP1)
vpbroadcastd %%ZTMP2, DWORD(%%GP1)
movbe DWORD(%%GP2), [%%IV + 12]
vpbroadcastd %%ZTMP3, DWORD(%%GP2)
vmovdqa32 [%%STATE + _snow3g_args_LFSR_7]{%%KPOS}, %%ZTMP1
vpxord %%ZTMP3, %%ZTMP3, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_LFSR_15]{%%KPOS}, %%ZTMP3
vmovdqa32 [%%STATE + _snow3g_args_LFSR_3]{%%KPOS}, %%ZTMP2
vmovdqa32 [%%STATE + _snow3g_args_LFSR_11]{%%KPOS}, %%ZTMP2
;; FSM 1, 2 and 3
vpxord %%ZTMP1, %%ZTMP1, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_FSM_1]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_FSM_2]{%%KPOS}, %%ZTMP1
vmovdqa32 [%%STATE + _snow3g_args_FSM_3]{%%KPOS}, %%ZTMP1
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; LFSR INITIALIZATION
;; Initialize LFSR and FSM registers for 16 key-iv pairs
;;
;; OUTPUT: LFSR_0-LFSR_15 and FSM1-FSM3 registers
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro LFSR_FSM_INIT_AUTH 4
%xdefine %%KEY %1 ;; [in] address of key
%xdefine %%IV %2 ;; [in] address of iv
%xdefine %%GP1 %3 ;; [clobbered] temporary GP register
%xdefine %%GP2 %4 ;; [clobbered] temporary GP register
%define %%ZKEY1 LFSR_4
%define %%ZKEY2 LFSR_5
%define %%ZKEY3 LFSR_6
%define %%ZKEY4 LFSR_7
%define %%ZKEY5 LFSR_8
%define %%ZKEY6 LFSR_9
%define %%ZKEY7 LFSR_10
%define %%ZKEY8 LFSR_11
%define %%ZIV1 FSM1
%define %%ZIV2 FSM2
%define %%ZIV3 FSM3
%define %%ZIV4 TEMP_27
%define %%ZIV5 LFSR_12
%define %%ZIV6 LFSR_13
%define %%ZIV7 LFSR_14
%define %%ZIV8 LFSR_15
%define %%ZTMP1 TEMP_28
%define %%ZTMP2 TEMP_29
%define %%ALL_FS TEMP_30
mov %%GP1, [%%KEY + 0*8]
mov %%GP2, [%%KEY + 1*8]
vmovdqu64 XWORD(%%ZKEY1), [%%GP1]
vmovdqu64 XWORD(%%ZKEY2), [%%GP2]
mov %%GP1, [%%IV + 0*8]
mov %%GP2, [%%IV + 1*8]
vinserti32x4 YWORD(%%ZKEY1), [%%GP1], 1
vinserti32x4 YWORD(%%ZKEY2), [%%GP2], 1
mov %%GP1, [%%KEY + 2*8]
mov %%GP2, [%%KEY + 3*8]
vmovdqu64 XWORD(%%ZKEY3), [%%GP1]
vmovdqu64 XWORD(%%ZKEY4), [%%GP2]
mov %%GP1, [%%IV + 2*8]
mov %%GP2, [%%IV + 3*8]
vinserti32x4 YWORD(%%ZKEY3), [%%GP1], 1
vinserti32x4 YWORD(%%ZKEY4), [%%GP2], 1
mov %%GP1, [%%KEY + 4*8]
mov %%GP2, [%%KEY + 5*8]
vmovdqu64 XWORD(%%ZIV1), [%%GP1]
vmovdqu64 XWORD(%%ZIV2), [%%GP2]
mov %%GP1, [%%IV + 4*8]
mov %%GP2, [%%IV + 5*8]
vinserti32x4 YWORD(%%ZIV1), [%%GP1], 1
vinserti32x4 YWORD(%%ZIV2), [%%GP2], 1
mov %%GP1, [%%KEY + 6*8]
mov %%GP2, [%%KEY + 7*8]
vmovdqu64 XWORD(%%ZIV3), [%%GP1]
vmovdqu64 XWORD(%%ZIV4), [%%GP2]
mov %%GP1, [%%IV + 6*8]
mov %%GP2, [%%IV + 7*8]
vinserti32x4 YWORD(%%ZIV3), [%%GP1], 1
vinserti32x4 YWORD(%%ZIV4), [%%GP2], 1
TRANSPOSE8_U32_AVX512 YWORD(%%ZKEY1), YWORD(%%ZKEY2), YWORD(%%ZKEY3), YWORD(%%ZKEY4), \
YWORD(%%ZIV1), YWORD(%%ZIV2), YWORD(%%ZIV3), YWORD(%%ZIV4), \
YWORD(%%ZTMP1), YWORD(%%ZTMP2)
mov %%GP1, [%%KEY + 8*8]
mov %%GP2, [%%KEY + 9*8]
vmovdqu64 XWORD(%%ZKEY5), [%%GP1]
vmovdqu64 XWORD(%%ZKEY6), [%%GP2]
mov %%GP1, [%%IV + 8*8]
mov %%GP2, [%%IV + 9*8]
vinserti32x4 YWORD(%%ZKEY5), [%%GP1], 1
vinserti32x4 YWORD(%%ZKEY6), [%%GP2], 1
mov %%GP1, [%%KEY + 10*8]
mov %%GP2, [%%KEY + 11*8]
vmovdqu64 XWORD(%%ZKEY7), [%%GP1]
vmovdqu64 XWORD(%%ZKEY8), [%%GP2]
mov %%GP1, [%%IV + 10*8]
mov %%GP2, [%%IV + 11*8]
vinserti32x4 YWORD(%%ZKEY7), [%%GP1], 1
vinserti32x4 YWORD(%%ZKEY8), [%%GP2], 1
mov %%GP1, [%%KEY + 12*8]
mov %%GP2, [%%KEY + 13*8]
vmovdqu64 XWORD(%%ZIV5), [%%GP1]
vmovdqu64 XWORD(%%ZIV6), [%%GP2]
mov %%GP1, [%%IV + 12*8]
mov %%GP2, [%%IV + 13*8]
vinserti32x4 YWORD(%%ZIV5), [%%GP1], 1
vinserti32x4 YWORD(%%ZIV6), [%%GP2], 1
mov %%GP1, [%%KEY + 14*8]
mov %%GP2, [%%KEY + 15*8]
vmovdqu64 XWORD(%%ZIV7), [%%GP1]
vmovdqu64 XWORD(%%ZIV8), [%%GP2]
mov %%GP1, [%%IV + 14*8]
mov %%GP2, [%%IV + 15*8]
vinserti32x4 YWORD(%%ZIV7), [%%GP1], 1
vinserti32x4 YWORD(%%ZIV8), [%%GP2], 1
TRANSPOSE8_U32_AVX512 YWORD(%%ZKEY5), YWORD(%%ZKEY6), YWORD(%%ZKEY7), YWORD(%%ZKEY8), \
YWORD(%%ZIV5), YWORD(%%ZIV6), YWORD(%%ZIV7), YWORD(%%ZIV8), \
YWORD(%%ZTMP1), YWORD(%%ZTMP2)
vinserti64x4 %%ZKEY1, YWORD(%%ZKEY5), 1
vinserti64x4 %%ZKEY2, YWORD(%%ZKEY6), 1
vinserti64x4 %%ZKEY3, YWORD(%%ZKEY7), 1
vinserti64x4 %%ZKEY4, YWORD(%%ZKEY8), 1
vinserti64x4 %%ZIV1, YWORD(%%ZIV5), 1
vinserti64x4 %%ZIV2, YWORD(%%ZIV6), 1
vinserti64x4 %%ZIV3, YWORD(%%ZIV7), 1
vinserti64x4 %%ZIV4, YWORD(%%ZIV8), 1
;; KEY and IV transposition is finished (ZKEY1-ZKEY4 & ZIV1-ZIV4)
;; - initialize LFSR's
vmovdqa64 %%ALL_FS, [rel all_fs]
;; vmovdqa64 LFSR_4, %%ZKEY1 - no needed, already secured through mapping
vmovdqa64 LFSR_12, %%ZKEY1
vpxord LFSR_0, %%ALL_FS, %%ZKEY1
vpxord LFSR_8, %%ALL_FS, %%ZKEY1
;; vmovdqa64 LFSR_5, %%ZKEY2 - no needed, already secured through mapping
vmovdqa64 LFSR_13, %%ZKEY2
vpxord LFSR_1, %%ALL_FS, %%ZKEY2
vpxord LFSR_9, %%ALL_FS, %%ZKEY2
;; vmovdqa64 LFSR_6, %%ZKEY3 - no needed, already secured through mapping
vmovdqa64 LFSR_14, %%ZKEY3
vpxord LFSR_2, %%ALL_FS, %%ZKEY3
vpxord LFSR_10, %%ALL_FS, %%ZKEY3
;; vmovdqa64 LFSR_7, %%ZKEY4 - no needed, already secured through mapping
vmovdqa64 LFSR_15, %%ZKEY4
vpxord LFSR_3, %%ALL_FS, %%ZKEY4
vpxord LFSR_11, %%ALL_FS, %%ZKEY4
;; continue with LFSR init (apply IV)
vpshufb %%ZIV1, %%ZIV1, [rel const_byte_shuff_mask]
vpshufb %%ZIV2, %%ZIV2, [rel const_byte_shuff_mask]
vpshufb %%ZIV3, %%ZIV3, [rel const_byte_shuff_mask]
vpshufb %%ZIV4, %%ZIV4, [rel const_byte_shuff_mask]
vpxord LFSR_9, LFSR_9, %%ZIV1
vpxord LFSR_10, LFSR_10, %%ZIV2
vpxord LFSR_12, LFSR_12, %%ZIV3
vpxord LFSR_15, LFSR_15, %%ZIV4
;; initialize FSM registers
vpxorq FSM1, FSM1, FSM1
vpxorq FSM2, FSM2, FSM2
vpxorq FSM3, FSM3, FSM3
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MulAlpha/DivAlpha operation
;; Note:
;; arg5, arg6 - addresses for low and high part of maps used to do transpose,
;; maps differ for mul and div operations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro ALPHA_OP_16 11
%xdefine %%IO_LFSR_X %1 ;; [in/out] zmm reg for Mulalpha/Divalpha result
%xdefine %%TEMP_MAP %2 ;; [clobbered] temporary zmm register
%xdefine %%TEMP1 %3 ;; [clobbered] temporary zmm register
%xdefine %%TEMP2 %4 ;; [clobbered] temporary zmm register
%xdefine %%MAP_LO %5 ;; [in] pointer to low part of transpose map
%xdefine %%MAP_HI %6 ;; [in] pointer to high part of transpose map
%xdefine %%KR1 %7 ;; [clobbered] temporary k-register
%xdefine %%KR2 %8 ;; [clobbered] temporary k-register
%xdefine %%KR3 %9 ;; [clobbered] temporary k-register
%xdefine %%KR4 %10 ;; [clobbered] temporary k-register
%xdefine %%KR5 %11 ;; [clobbered] temporary k-register
vpandq %%TEMP1, %%IO_LFSR_X, [rel dw_e0s] ;; 3 MSB on each double word
vpxorq %%TEMP2, %%TEMP2
vpcmpeqd %%KR1, %%TEMP1, %%TEMP2
vpcmpeqd %%KR2, %%TEMP1, [rel dw_20s]
vpcmpeqd %%KR3, %%TEMP1, [rel dw_40s]
vpcmpeqd %%KR4, %%TEMP1, [rel dw_60s]
vpcmpeqd %%KR5, %%TEMP1, [rel dw_80s]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_LO + 64*0]
vpermi2d %%IO_LFSR_X{%%KR1}, %%TEMP_MAP, [rel %%MAP_LO + 64*1]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_LO + 64*2]
vpermi2d %%IO_LFSR_X{%%KR2}, %%TEMP_MAP, [rel %%MAP_LO + 64*3]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_LO + 64*4]
vpermi2d %%IO_LFSR_X{%%KR3}, %%TEMP_MAP, [rel %%MAP_LO + 64*5]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_LO + 64*6]
vpermi2d %%IO_LFSR_X{%%KR4}, %%TEMP_MAP, [rel %%MAP_LO + 64*7]
vpcmpeqd %%KR1, %%TEMP1, [rel dw_e0s]
vpcmpeqd %%KR2, %%TEMP1, [rel dw_c0s]
vpcmpeqd %%KR3, %%TEMP1, [rel dw_a0s]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_HI + 64*0]
vpermi2d %%IO_LFSR_X{%%KR5}, %%TEMP_MAP, [rel %%MAP_HI + 64*1]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_HI + 64*2]
vpermi2d %%IO_LFSR_X{%%KR3}, %%TEMP_MAP, [rel %%MAP_HI + 64*3]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_HI + 64*4]
vpermi2d %%IO_LFSR_X{%%KR2}, %%TEMP_MAP, [rel %%MAP_HI + 64*5]
vmovdqa64 %%TEMP_MAP, [rel %%MAP_HI + 64*6]
vpermi2d %%IO_LFSR_X{%%KR1}, %%TEMP_MAP, [rel %%MAP_HI + 64*7]
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; LFSR_CLOCK
;; updates LFSR registers0-15
;; The same macro is used for initialization and working phase
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro LFSR_CLOCK 10
%xdefine %%TEMP %1 ;; [clobbered] temporary zmm register
%xdefine %%TEMP1 %2 ;; [clobbered] temporary zmm register
%xdefine %%TEMP2 %3 ;; [clobbered] temporary zmm register
%xdefine %%TEMP3 %4 ;; [clobbered] temporary zmm register
%xdefine %%TEMP4 %5 ;; [clobbered] temporary zmm register
%xdefine %%KR1 %6 ;; [clobbered] temporary k-register
%xdefine %%KR2 %7 ;; [clobbered] temporary k-register
%xdefine %%KR3 %8 ;; [clobbered] temporary k-register
%xdefine %%KR4 %9 ;; [clobbered] temporary k-register
%xdefine %%KR5 %10 ;; [clobbered] temporary k-register
vpslld %%TEMP, LFSR_0, 8
vpxord %%TEMP, %%TEMP, LFSR_2
vpsrld %%TEMP4, LFSR_0, 24
;; LFSR_0 = Mulalpha(LFSR[0]>>24 & 0xff)
ALPHA_OP_16 %%TEMP4, %%TEMP1, %%TEMP2, %%TEMP3, \
const_mulalpha_map_00_0f, \
const_mulalpha_map_80_8f, \
%%KR1, %%KR2, %%KR3, %%KR4, %%KR5
vpxord %%TEMP, %%TEMP, %%TEMP4
vmovdqa32 LFSR_0, LFSR_1
vmovdqa32 LFSR_1, LFSR_2
vmovdqa32 LFSR_2, LFSR_3
vmovdqa32 LFSR_3, LFSR_4
vmovdqa32 LFSR_4, LFSR_5
vmovdqa32 LFSR_5, LFSR_6
vmovdqa32 LFSR_6, LFSR_7
vmovdqa32 LFSR_7, LFSR_8
vmovdqa32 LFSR_8, LFSR_9
vmovdqa32 LFSR_9, LFSR_10
vmovdqa32 LFSR_10, LFSR_11
;; LFSR[11] >> 8 & 0x00ffffff
vpsrld %%TEMP4, LFSR_11, 8
vpxord %%TEMP, %%TEMP, %%TEMP4
vmovdqa32 %%TEMP1, LFSR_11
;; LFSR_11 = DIValpha(LFSR[11] & 0xff)
ALPHA_OP_16 %%TEMP1, %%TEMP2, %%TEMP3, %%TEMP4, \
const_divalpha_map_00_0f, \
const_divalpha_map_80_8f, \
%%KR1, %%KR2, %%KR3, %%KR4, %%KR5
vmovdqa32 %%TEMP4, LFSR_12
vmovdqa32 LFSR_12, LFSR_13
vmovdqa32 LFSR_13, LFSR_14
vmovdqa32 LFSR_13, LFSR_14
vmovdqa32 LFSR_14, LFSR_15
vpxord LFSR_15, %%TEMP, %%TEMP1
vmovdqa32 LFSR_11, %%TEMP4
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initializes global registers with constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro INIT_CONSTANTS 1
%xdefine %%GEN %1 ;; [in] avx512_gen1/avx512_gen2
%ifidn %%GEN, avx512_gen2
vmovdqa64 FIXED_MAP_TAB_0, [rel const_transf_map + 64 * 0]
vmovdqa64 FIXED_MAP_TAB_1, [rel const_transf_map + 64 * 1]
vmovdqa64 FIXED_MAP_TAB_2, [rel const_transf_map + 64 * 2]
vmovdqa64 FIXED_MAP_TAB_3, [rel const_transf_map + 64 * 3]
%endif
vmovdqa64 FIXED_ROTATE_MASK, [rel const_fixed_rotate_mask]
vmovdqa64 FIXED_PATTERN_SHUF, [rel const_fixup]
vmovdqa64 FIXED_M_MASK, [rel const_fixup_mask]
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Stores to/loads from memory from/to vector registers key stream state registers
;; - uses global register mapping for load/store operation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro LFSR_FSM_STATE 2
%define %%PTR %1 ;; [in] pointer to state structure
%define %%TYPE %2 ;; [in] "STORE" or "LOAD" selector
%ifidn %%TYPE, STORE
%assign i 0
%rep 16
vmovdqu64 [%%PTR + _snow3g_args_LFSR_ %+ i], LFSR_ %+ i
%assign i (i + 1)
%endrep
vmovdqu64 [%%PTR + _snow3g_args_FSM_1], FSM1
vmovdqu64 [%%PTR + _snow3g_args_FSM_2], FSM2
vmovdqu64 [%%PTR + _snow3g_args_FSM_3], FSM3
%else ;; LOAD
%assign i 0
%rep 16
vmovdqu64 LFSR_ %+ i, [%%PTR + _snow3g_args_LFSR_ %+ i]
%assign i (i + 1)
%endrep
vmovdqu64 FSM1, [%%PTR + _snow3g_args_FSM_1]
vmovdqu64 FSM2, [%%PTR + _snow3g_args_FSM_2]
vmovdqu64 FSM3, [%%PTR + _snow3g_args_FSM_3]
%endif
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes 64 byte of key stream, loads plain text,
;; xor's key stream against the plain text, stores the result.
;;
;; Note: if lane is in initialization mode loads and stores
;; don't really happen (mask) and key stream is simply discarded
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro STORE_KEYSTREAM_ZMM 9
%xdefine %%SRC_PTRS %1 ;; [in] address of array of pointers to 16 src buffs or "NULL"
%xdefine %%DST_PTRS %2 ;; [in] address of array of pointers to 16 dst buffs
%xdefine %%STATE_PTR %3 ;; [in] pointer to state structure
%xdefine %%OFFSET %4 ;; [in] current offset to src/dst
%xdefine %%LANEID %5 ;; [in] imm value used as lane index
%xdefine %%TGP0 %6 ;; [clobbered] temporary 64bit register
%xdefine %%TZMM1 %7 ;; [clobbered] temporary zmm register
%xdefine %%TZMM2 %8 ;; [clobbered] temporary zmm register
%xdefine %%KREG %9 ;; [clobbered] k register
kmovq %%KREG, [%%STATE_PTR + _snow3g_args_LD_ST_MASK + (%%LANEID * 8)]
vpshufb %%TZMM1, LFSR_ %+ %%LANEID, [rel const_byte_shuff_mask]
%ifnidn %%SRC_PTRS, NULL
mov %%TGP0, [%%SRC_PTRS + (%%LANEID * 8)]
vmovdqu8 %%TZMM2{%%KREG}{z}, [%%TGP0 + %%OFFSET]
vpxord %%TZMM1, %%TZMM1, %%TZMM2
%endif
mov %%TGP0, [%%DST_PTRS + (%%LANEID * 8)]
vmovdqu8 [%%TGP0 + %%OFFSET]{%%KREG}, %%TZMM1
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes 64 byte of key stream, loads plain text,
;; xor's key stream against the plain text, stores the result.
;; - here it takes into account partial cases
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro STORE_KEYSTREAM_ZMM_LAST 10
%xdefine %%SRC_PTRS %1 ;; [in] array of pointers to 16 src buffs or "NULL"
%xdefine %%DST_PTRS %2 ;; [in] array of pointers to 16 dst buffs
%xdefine %%STATE_PTR %3 ;; [in] pointer to state structure
%xdefine %%OFFSET %4 ;; [in] current offset to src/dst
%xdefine %%LANEID %5 ;; [in] imm value used as lane index
%xdefine %%TGP0 %6 ;; [clobbered] temporary 64bit register
%xdefine %%TZMM1 %7 ;; [clobbered] temporary zmm register
%xdefine %%TZMM2 %8 ;; [clobbered] temporary zmm register
%xdefine %%KMASK_DB %9 ;; [in] k register with byte mask limiting input/output
%xdefine %%KTMP %10;; [clobbered] temporary k register
kmovq %%KTMP, [%%STATE_PTR + _snow3g_args_LD_ST_MASK + (%%LANEID * 8)]
kandq %%KTMP, %%KMASK_DB, %%KTMP
%ifnidn %%SRC_PTRS, NULL
vpshufb %%TZMM1, LFSR_ %+ %%LANEID, [rel const_byte_shuff_mask]
mov %%TGP0, [%%SRC_PTRS + (%%LANEID * 8)]
vmovdqu8 %%TZMM2{%%KTMP}{z}, [%%TGP0 + %%OFFSET]
vpxord %%TZMM1, %%TZMM1, %%TZMM2
mov %%TGP0, [%%DST_PTRS + (%%LANEID * 8)]
vmovdqu8 [%%TGP0 + %%OFFSET]{%%KTMP}, %%TZMM1
%else
mov %%TGP0, [%%DST_PTRS + (%%LANEID * 8)]
vmovdqu8 [%%TGP0 + %%OFFSET]{%%KTMP}, LFSR_ %+ %%LANEID
%endif
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key streams are kept in stack in following way:
;; rsp + _keystream + 64*0 KEYSTREAM 0 : [buff15_0, buff_14_0, ..., buff0_0]
;; ...
;; rsp + _keystream + 64*14 KEYSTREAM 14 : [buff15_14, buff_14_14, ..., buff0_14]
;; rsp + _keystream + 64*15 KEYSTREAM 15 : [buff15_15, buff_14_15, ..., buff0_15]
;; @note Uses LFSR registers for the transposition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro TRANSPOSE_FROM_STACK 4
%xdefine %%TEMP1 %1 ;; [clobbered] temporary zmm register
%xdefine %%TEMP2 %2 ;; [clobbered] temporary zmm register
%xdefine %%TEMP3 %3 ;; [clobbered] temporary zmm register
%xdefine %%TEMP4 %4 ;; [clobbered] temporary zmm register
TRANSPOSE16_U32_LOAD_FIRST8 \
LFSR_0, LFSR_1, LFSR_2, LFSR_3, LFSR_4, LFSR_5, LFSR_6, LFSR_7, \
LFSR_8, LFSR_9, LFSR_10, LFSR_11, LFSR_12, LFSR_13, LFSR_14, LFSR_15, \
{rsp + _keystream + (64 * 0)}, {rsp + _keystream + (64 * 1)}, \
{rsp + _keystream + (64 * 2)}, {rsp + _keystream + (64 * 3)}, \
{rsp + _keystream + (64 * 4)}, {rsp + _keystream + (64 * 5)}, \
{rsp + _keystream + (64 * 6)}, {rsp + _keystream + (64 * 7)}, 0
TRANSPOSE16_U32_LOAD_LAST8 \
LFSR_0, LFSR_1, LFSR_2, LFSR_3, LFSR_4, LFSR_5, LFSR_6, LFSR_7, \
LFSR_8, LFSR_9, LFSR_10, LFSR_11, LFSR_12, LFSR_13, LFSR_14, LFSR_15, \
{rsp + _keystream + (64 * 8)}, {rsp + _keystream + (64 * 9)}, \
{rsp + _keystream + (64 * 10)}, {rsp + _keystream + (64 * 11)}, \
{rsp + _keystream + (64 * 12)}, {rsp + _keystream + (64 * 13)}, \
{rsp + _keystream + (64 * 14)}, {rsp + _keystream + (64 * 15)}, 0
TRANSPOSE16_U32_PRELOADED \
LFSR_0, LFSR_1, LFSR_2, LFSR_3, LFSR_4, LFSR_5, LFSR_6, LFSR_7, \
LFSR_8, LFSR_9, LFSR_10, LFSR_11, LFSR_12, LFSR_13, LFSR_14, LFSR_15, \
%%TEMP1, %%TEMP2, %%TEMP3, %%TEMP4
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SNOW3G cipher code generating required number key stream double words
;; - it is multi-buffer implementation (16 buffers)
;; - buffers can be in initialization or working mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro SNOW_3G_KEYSTREAM 15
%xdefine %%STATE_PTR %1 ;; [in] FSM_LFSR state structure pointer
%xdefine %%COUNT %2 ;; [in/clobbered] number of dwords to be processed
%xdefine %%SRC_PTRS %3 ;; [in] address of array of pointers to 16 src buff
%xdefine %%DST_PTRS %4 ;; [in] address of array of pointers to 16 dst buff
%xdefine %%OFFSET %5 ;; [clobbered] temporary 64bit register
%xdefine %%TGP0 %6 ;; [clobbered] temporary 64bit register
%xdefine %%TGP1 %7 ;; [clobbered] temporary 64bit register
%xdefine %%TGP2 %8 ;; [clobbered] temporary 64bit register
%xdefine %%KR1 %9 ;; [clobbered] temporary k-register
%xdefine %%KR2 %10 ;; [clobbered] temporary k-register
%xdefine %%KR3 %11 ;; [clobbered] temporary k-register
%xdefine %%KR4 %12 ;; [clobbered] temporary k-register
%xdefine %%KR5 %13 ;; [clobbered] temporary k-register
%xdefine %%KR6 %14 ;; [clobbered] temporary k-register
%xdefine %%GEN %15 ;; [in] avx512_gen1/avx512_gen2
xor %%OFFSET, %%OFFSET
;; Number of DWORD's MOD 16
mov %%TGP1, %%COUNT
and DWORD(%%TGP1), 15
kmovw %%KR6, [%%STATE_PTR + _snow3g_INIT_MASK]
INIT_CONSTANTS %%GEN
LFSR_FSM_STATE %%STATE_PTR, LOAD
;; used as offset for storing key stream on the stack frame
xor %%TGP0, %%TGP0
%%next_keyword:
%ifidn %%GEN, avx512_gen2
FSM_CLOCK FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%else
FSM_CLOCK_NO_VAES FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%endif
;; this xor happens only in key stream gen mode (working mode)
knotw %%KR6, %%KR6 ;; bits are set if lane is initialized
vpxord KEYSTREAM{%%KR6}, LFSR_0, KEYSTREAM
;; put key stream on the stack frame
vmovdqa32 [rsp + _keystream + %%TGP0], KEYSTREAM
add DWORD(%%TGP0), 64
LFSR_CLOCK TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
%%KR1, %%KR2, %%KR3, %%KR4, %%KR5
;; this xor happens only in initialization gen mode (initialization mode)
knotw %%KR6, %%KR6 ;; bits are zero if lane is initialized
vpxord LFSR_15{%%KR6}, LFSR_15, KEYSTREAM
cmp DWORD(%%TGP0), (16 * 64)
jnz %%no_write_yet
;; clear the offset to start again
xor %%TGP0, %%TGP0
;; temporarily free LFSR and FSM registers for the transpose
LFSR_FSM_STATE %%STATE_PTR, STORE
TRANSPOSE_FROM_STACK \
TEMP_27, TEMP_28, TEMP_29, TEMP_30
%assign i 0
%rep 16
STORE_KEYSTREAM_ZMM \
%%SRC_PTRS, %%DST_PTRS, %%STATE_PTR, %%OFFSET, i, \
%%TGP2, TEMP_27, TEMP_28, %%KR2
%assign i (i + 1)
%endrep
;; restore LFSR and FSM state
LFSR_FSM_STATE %%STATE_PTR, LOAD
add %%OFFSET, 64
%%no_write_yet:
dec %%COUNT
jnz %%next_keyword
;; save LFSR & FSM registers
LFSR_FSM_STATE %%STATE_PTR, STORE
or %%TGP0, %%TGP0
jz %%fin
TRANSPOSE_FROM_STACK \
TEMP_27, TEMP_28, TEMP_29, TEMP_30
lea %%TGP2, [rel dw_len_to_db_mask]
kmovq %%KR1, [%%TGP2 + %%TGP1 * 8]
%assign i 0
%rep 16
STORE_KEYSTREAM_ZMM_LAST \
%%SRC_PTRS, %%DST_PTRS, %%STATE_PTR, %%OFFSET, i, \
%%TGP2, TEMP_27, TEMP_29, %%KR1, %%KR2
%assign i (i + 1)
%endrep
lea %%OFFSET, [%%OFFSET + %%TGP1 * 4]
%%fin:
%endmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generate 5 double words of key stream for SNOW3G authentication
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro SNOW3G_AUTH_INIT_5 12
%xdefine %%KEY %1 ;; [in] array of pointers to 16 keys
%xdefine %%IV %2 ;; [in] array of pointers to 16 IV's
%xdefine %%DST_PTR %3 ;; [in] destination buffer to put 5DW of keystream into (32 bytes per lane)
%xdefine %%COUNT %4 ;; [clobbered] 64b register
%xdefine %%TGP0 %5 ;; [clobbered] 64b register
%xdefine %%KR1 %6 ;; [clobbered] temporary k-register
%xdefine %%KR2 %7 ;; [clobbered] temporary k-register
%xdefine %%KR3 %8 ;; [clobbered] temporary k-register
%xdefine %%KR4 %9 ;; [clobbered] temporary k-register
%xdefine %%KR5 %10 ;; [clobbered] temporary k-register
%xdefine %%KR6 %11 ;; [clobbered] temporary k-register
%xdefine %%GEN %12 ;; [in] avx512_gen1/avx512_gen2
INIT_CONSTANTS %%GEN
LFSR_FSM_INIT_AUTH %%KEY, %%IV, %%TGP0, %%COUNT
;; initialization mode
;; 32 + 1 iterations of FSM and LFSR clock
kxorw %%KR6, %%KR6, %%KR6
knotw %%KR6, %%KR6 ;; 0xffff -> do LFSR_15 xor
mov DWORD(%%COUNT), 32
%%_auth_keystream_init_mode:
%ifidn %%GEN, avx512_gen2
FSM_CLOCK FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%else
FSM_CLOCK_NO_VAES FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%endif
LFSR_CLOCK TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
%%KR1, %%KR2, %%KR3, %%KR4, %%KR5
;; this xor happens only in initialization mode (init1)
vpxord LFSR_15{%%KR6}, LFSR_15, KEYSTREAM
dec DWORD(%%COUNT)
jnz %%_auth_keystream_init_mode
kortestw %%KR6, %%KR6
jz %%_auth_keystream_init_mode_exit
;; 2nd phase of initialization
mov DWORD(%%COUNT), 1
kxorw %%KR6, %%KR6, %%KR6 ;; no LFSR_15 xor in init2
jmp %%_auth_keystream_init_mode
%%_auth_keystream_init_mode_exit:
;; working mode - 5 double words
mov DWORD(%%COUNT), 5
xor %%TGP0, %%TGP0
%%_auth_keystream_work_mode:
%ifidn %%GEN, avx512_gen2
FSM_CLOCK FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%else
FSM_CLOCK_NO_VAES FSM1, FSM2, FSM3, LFSR_5, LFSR_15, KEYSTREAM, \
TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
FIXED_MAP_TAB_0, FIXED_MAP_TAB_1, \
FIXED_MAP_TAB_2, FIXED_MAP_TAB_3, \
%%KR1, %%KR2, %%KR3, %%KR4
%endif
vpxord KEYSTREAM, LFSR_0, KEYSTREAM ;; only in working mode
;; put key stream on the stack frame
vmovdqa32 [rsp + _keystream + %%TGP0], KEYSTREAM
add DWORD(%%TGP0), 64
LFSR_CLOCK TEMP_27, TEMP_28, TEMP_29, TEMP_30, TEMP_31, \
%%KR1, %%KR2, %%KR3, %%KR4, %%KR5
dec DWORD(%%COUNT)
jnz %%_auth_keystream_work_mode
;; transpose the keystream and store in the destination
TRANSPOSE_FROM_STACK \
TEMP_27, TEMP_28, TEMP_29, TEMP_30
%assign i 0
%rep 16
%xdefine %%KS_ZMM LFSR_ %+ i
vmovdqu32 [%%DST_PTR + (i * 32)], YWORD(%%KS_ZMM)
%assign i (i + 1)
%endrep
%ifdef SAFE_DATA
;; clear the keystream
;; - LFSR and FSM registers not stored in the state
vpxorq TEMP_31, TEMP_31
vmovdqa32 [rsp + _keystream + (0 * 64)], TEMP_31
vmovdqa32 [rsp + _keystream + (1 * 64)], TEMP_31
vmovdqa32 [rsp + _keystream + (2 * 64)], TEMP_31
vmovdqa32 [rsp + _keystream + (3 * 64)], TEMP_31
vmovdqa32 [rsp + _keystream + (4 * 64)], TEMP_31
%endif
%endmacro
|
#include "Particle.hpp"
#include "Scenes/Scenes.hpp"
namespace acid {
constexpr static float FADE_TIME = 1.0f;
Particle::Particle(std::shared_ptr<ParticleType> particleType, const Vector3f &position, const Vector3f &velocity, float lifeLength, float stageCycles,
float rotation, float scale, float gravityEffect) :
particleType(std::move(particleType)),
position(position),
velocity(velocity),
lifeLength(lifeLength),
stageCycles(stageCycles),
rotation(rotation),
scale(scale),
gravityEffect(gravityEffect) {
}
void Particle::Update() {
auto delta = Engine::Get()->GetDelta().AsSeconds();
velocity.y += -10.0f * gravityEffect * delta;
change = velocity;
change *= delta;
position += change;
elapsedTime += delta;
if (elapsedTime > lifeLength - FADE_TIME)
transparency -= delta / FADE_TIME;
if (!IsAlive() || !Scenes::Get()->GetScene()->GetCamera())
return;
auto cameraToParticle = Scenes::Get()->GetScene()->GetCamera()->GetPosition() - position;
distanceToCamera = cameraToParticle.LengthSquared();
auto lifeFactor = stageCycles * elapsedTime / lifeLength;
if (!particleType->GetImage())
return;
auto stageCount = static_cast<int32_t>(std::pow(particleType->GetNumberOfRows(), 2));
auto atlasProgression = lifeFactor * stageCount;
auto index1 = static_cast<int32_t>(std::floor(atlasProgression));
auto index2 = index1 < stageCount - 1 ? index1 + 1 : index1;
imageBlendFactor = std::fmod(atlasProgression, 1.0f);
imageOffset1 = CalculateImageOffset(index1);
imageOffset2 = CalculateImageOffset(index2);
}
bool Particle::operator<(const Particle &rhs) const {
return distanceToCamera > rhs.distanceToCamera;
}
Vector2f Particle::CalculateImageOffset(int32_t index) const {
auto column = index % particleType->GetNumberOfRows();
auto row = index / particleType->GetNumberOfRows();
return Vector2f(static_cast<float>(column), static_cast<float>(row)) / particleType->GetNumberOfRows();
}
}
|
; A056106: Second spoke of a hexagonal spiral.
; 1,3,11,25,45,71,103,141,185,235,291,353,421,495,575,661,753,851,955,1065,1181,1303,1431,1565,1705,1851,2003,2161,2325,2495,2671,2853,3041,3235,3435,3641,3853,4071,4295,4525,4761,5003,5251,5505,5765,6031,6303,6581,6865,7155,7451,7753,8061,8375,8695,9021,9353,9691,10035,10385,10741,11103,11471,11845,12225,12611,13003,13401,13805,14215,14631,15053,15481,15915,16355,16801,17253,17711,18175,18645,19121,19603,20091,20585,21085,21591,22103,22621,23145,23675,24211,24753,25301,25855,26415,26981,27553,28131,28715,29305
mov $1,$0
mul $1,3
sub $1,1
mul $0,$1
add $0,1
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/window_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace xla {
namespace {
namespace op = ::xla::testing::opcode_matchers;
using absl::string_view;
struct TestData {
string test_name;
string module_string;
};
string TestDataToString(const ::testing::TestParamInfo<TestData>& data) {
return data.param.test_name;
}
// For each string below, we check that:
// - we parse it to an HloModule successfully, and
// - the stringification of the resulting HloModule is equal to our original
// string.
std::vector<TestData> CreateTestCases() {
// clang-format off
return std::vector<TestData>({
// ax + y
{
"AxpyParam",
R"(HloModule axpy_module
ENTRY %axpy.v5 (alpha: f32[], x: f32[2,4], y: f32[2,4]) -> f32[2,4] {
%alpha = f32[] parameter(0)
%broadcast = f32[2,4]{1,0} broadcast(f32[] %alpha), dimensions={}
%x = f32[2,4]{1,0} parameter(1)
%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)
%y = f32[2,4]{1,0} parameter(2)
ROOT %add = f32[2,4]{1,0} add(f32[2,4]{1,0} %multiply, f32[2,4]{1,0} %y)
}
)"
},
// parameter replication
{
"ParamReplication",
R"(HloModule param_replication_module
ENTRY %param_replication (a: f32[], b: (f32[2,4], (f32[2,4]))) -> (f32[], (f32[2,4], (f32[2,4]))) {
%a = f32[] parameter(0), parameter_replication={true}
%b = (f32[2,4]{1,0}, (f32[2,4]{1,0})) parameter(1), parameter_replication={false,true}
ROOT %tuple = (f32[], (f32[2,4]{1,0}, (f32[2,4]{1,0}))) tuple(f32[] %a, (f32[2,4]{1,0}, (f32[2,4]{1,0})) %b)
}
)"
},
// pred constant
{
"ConstantPred",
R"(HloModule constant_pred_module
ENTRY %constant_pred () -> pred[] {
ROOT %constant = pred[] constant(true), metadata={op_type="const" op_name="\"it\'s not a problem\n" source_file="path/to/test.cc" source_line=68}, backend_config="foo\" bar"
}
)"
},
// pred array constant
{
"ConstantPredArray",
R"(HloModule module
ENTRY %constant_pred_array () -> pred[2,3] {
ROOT %constant = pred[2,3]{1,0} constant({ { 0, 1, 0 }, { 1, 0, 1 } })
}
)"
},
// s32 constant
{
"ConstantS32",
R"(HloModule constant_s32_module
ENTRY %constant_s32 () -> s32[] {
ROOT %constant = s32[] constant(-42)
}
)"
},
// f32 constant, but the value is not a decimal and there is a backend
// configuration
{
"ConstantF32",
R"(HloModule ConstantF32_module
ENTRY %ConstantF32.v4 () -> f32[] {
ROOT %constant = f32[] constant(42), backend_config="this is a configuration"
}
)"
},
// f32 constant, rank 1 empty array.
{
"ConstantF32R1Empty",
R"(HloModule ConstantF32Empty_module
ENTRY %ConstantF32Empty.v4 () -> f32[0] {
ROOT %constant = f32[0]{0} constant({})
}
)"
},
// f32 constant, rank 4 empty array.
{
"ConstantF32R4Empty",
R"(HloModule ConstantF32R4Empty_module
ENTRY %ConstantF32R4Empty.v4 () -> f32[2,0,4,3] {
ROOT %constant = f32[2,0,4,3]{3,2,1,0} constant({ { /*i0=0*/ }, { /*i0=1*/ } })
}
)"
},
// constant 4D
{
"Constant4D",
R"(HloModule Small_3x2x1x1_module
ENTRY %Small_3x2x1x1.v1 () -> f32[3,2,1,1] {
ROOT %constant = f32[3,2,1,1]{3,2,1,0} constant({ { /*i0=0*/ { /*i1=0*/ {-1} }, { /*i1=1*/ {4.1} } }, { /*i0=1*/ { /*i1=0*/ {2} }, { /*i1=1*/ {4.1} } }, { /*i0=2*/ { /*i1=0*/ {5} }, { /*i1=1*/ {4.4} } } })
}
)"
},
// non-finite constants: nan, inf, -inf
{
"ConstantNonFinite",
R"(HloModule IsFiniteR1F32s_module
ENTRY %IsFiniteR1F32s.v2 () -> pred[6] {
%constant = f32[6]{0} constant({nan, 7, nan, -1, inf, -inf})
ROOT %is-finite = pred[6]{0} is-finite(f32[6]{0} %constant)
}
)"
},
// constant f16
{
"ConstantF16",
R"(HloModule ConstantF16_module
ENTRY %ConstantF16.v4 () -> f16[] {
ROOT %constant = f16[] constant(500)
}
)"
},
// bf16
{
"BF16",
R"(HloModule BF16
ENTRY %BF16.v4 () -> bf16[] {
ROOT %constant = bf16[] constant(500)
}
)"
},
// constant + constant
{
"AddConstants",
R"(HloModule add_constants_module
ENTRY %add_constants () -> f32[] {
%constant = f32[] constant(3.14)
ROOT %add = f32[] add(f32[] %constant, f32[] %constant)
}
)"
},
// tuple constant
{
"TupleConstant",
R"(HloModule TupleConstant_module
ENTRY %TupleConstant.v1 () -> (f32[2,1], f32[2]) {
ROOT %constant = (f32[2,1]{1,0}, f32[2]{0}) constant(( { {1}, {2} }, {2, 42} ))
}
)"
},
// v1 > v2 ? v1 : v2
{
"SelectR1F32",
R"(HloModule SelectR1F32WithCmpR1F32sFromParamsSmall_module
ENTRY %SelectR1F32WithCmpR1F32sFromParamsSmall.v4 (v1: f32[4], v2: f32[4]) -> f32[4] {
%v1 = f32[4]{0} parameter(0), sharding={maximal device=1}
%v2 = f32[4]{0} parameter(1), sharding={maximal device=1}
%greater-than = pred[4]{0} compare(f32[4]{0} %v1, f32[4]{0} %v2), direction=GT, sharding={replicated}
ROOT %select = f32[4]{0} select(pred[4]{0} %greater-than, f32[4]{0} %v1, f32[4]{0} %v2), sharding={}
}
)"
},
// empty tuple
{
"EmptyTupleCreate",
R"(HloModule EmptyTupleCreate_module
ENTRY %EmptyTupleCreate.v1 () -> () {
ROOT %tuple = () tuple()
}
)"
},
// tuple
{
"TupleCreate",
R"(HloModule TupleCreate_module
ENTRY %TupleCreate.v4 (v1: f32[], v2: f32[3], v3: f32[2,3]) -> (f32[], f32[3], f32[2,3]) {
%v1 = f32[] parameter(0)
%v2 = f32[3]{0} parameter(1)
%v3 = f32[2,3]{1,0} parameter(2)
ROOT %tuple = (f32[], f32[3]{0}, f32[2,3]{1,0}) tuple(f32[] %v1, f32[3]{0} %v2, f32[2,3]{1,0} %v3)
}
)"
},
{
"ShardedTupleCreate",
R"(HloModule ShardedTupleCreate_module
ENTRY %ShardedTupleCreate.v4 (v1: f32[], v2: f32[3], v3: f32[2,3]) -> (f32[], f32[3], f32[2,3]) {
%v1 = f32[] parameter(0)
%v2 = f32[3]{0} parameter(1)
%v3 = f32[2,3]{1,0} parameter(2)
ROOT %tuple = (f32[], f32[3]{0}, f32[2,3]{1,0}) tuple(f32[] %v1, f32[3]{0} %v2, f32[2,3]{1,0} %v3), sharding={{replicated}, {maximal device=0}, {replicated}}
}
)"
},
{
"DomainParsing",
R"(HloModule DomainParsing_module
ENTRY %DomainParsing (v1: f32[]) -> f32[] {
%v1 = f32[] parameter(0)
ROOT %dom = f32[] domain(f32[] %v1), domain={kind="sharding", entry={maximal device=0}, exit={maximal device=1}}
}
)"
},
// int32 result = 0;
// while (result < 5) { result = result + 1; }
{
"WhileWithScalarS32Result",
R"(HloModule WhileWithScalarS32Result_module
%body.v3 (prev.1: s32[]) -> s32[] {
%constant = s32[] constant(1)
%prev.1 = s32[] parameter(0)
ROOT %add = s32[] add(s32[] %constant, s32[] %prev.1)
}
%condition.v3 (prev.2: s32[]) -> pred[] {
%constant.1 = s32[] constant(5)
%prev.2 = s32[] parameter(0)
ROOT %greater-than = pred[] compare(s32[] %constant.1, s32[] %prev.2), direction=GT
}
ENTRY %WhileWithScalarS32Result.v2 () -> s32[] {
%constant.2 = s32[] constant(0)
ROOT %while = s32[] while(s32[] %constant.2), condition=%condition.v3, body=%body.v3
}
)"
},
// send and recv
{
"SendRecv",
R"(HloModule TwoSendRecvBothWayRecvFist_module
ENTRY %TwoSendRecvBothWayRecvFist.v3 () -> (f32[], token[]) {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15, sharding={maximal device=1}
ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15, sharding={maximal device=1}
%constant = f32[] constant(2.1), sharding={maximal device=0}
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, sharding={maximal device=0}, control-predecessors={%recv}
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16, sharding={maximal device=0}
}
)"
},
{
"SendRecvWithHostTransfer",
R"(HloModule HostTransferSendRecv_module
ENTRY %TwoSendRecvBothWayRecvFist.v3 () -> (f32[], token[]) {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15, is_host_transfer=true
ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15, is_host_transfer=true
%constant = f32[] constant(2.1), sharding={maximal device=0}
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, is_host_transfer=true
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16, is_host_transfer=true
}
)"
},
// get-tuple-element
{
"GetTupleElement",
R"(HloModule GetTupleElement_module
ENTRY %GetTupleElement.v4 () -> s32[2,3] {
%constant = f32[3]{0} constant({1, 2, 3})
%constant.1 = s32[2,3]{1,0} constant({ { 1, 2, 3 }, { 4, 5, 6 } })
%tuple = (f32[3]{0}, s32[2,3]{1,0}) tuple(f32[3]{0} %constant, s32[2,3]{1,0} %constant.1)
ROOT %get-tuple-element = s32[2,3]{1,0} get-tuple-element((f32[3]{0}, s32[2,3]{1,0}) %tuple), index=1, sharding={maximal device=0}
}
)"
},
// call
{
"Call",
R"(HloModule CallR0F32IdentityScalar_module
%Identity.v1 (x: f32[]) -> f32[] {
ROOT %x = f32[] parameter(0)
}
ENTRY %CallR0F32IdentityScalar.v2 () -> f32[] {
%constant = f32[] constant(42)
ROOT %call = f32[] call(f32[] %constant), to_apply=%Identity.v1
}
)"
},
// reduce window
{
"ReduceWindow",
R"(HloModule R4UnitWindow_module
%add_F32.v3 (lhs: f32[], rhs: f32[]) -> f32[] {
%lhs = f32[] parameter(0)
%rhs = f32[] parameter(1)
ROOT %add = f32[] add(f32[] %lhs, f32[] %rhs)
}
ENTRY %R4UnitWindow.v3 (operand: f32[13,12,8,15]) -> f32[13,3,8,15] {
%operand = f32[13,12,8,15]{0,3,2,1} parameter(0)
%constant = f32[] constant(0)
ROOT %reduce-window = f32[13,3,8,15]{0,3,2,1} reduce-window(f32[13,12,8,15]{0,3,2,1} %operand, f32[] %constant), window={size=1x1x7x1 stride=1x4x1x1 pad=0_0x0_0x3_3x0_0}, to_apply=%add_F32.v3
}
)"
},
// reduce window on scalar
{
"ReduceWindowScalar",
R"(HloModule reduce_window_scalar
%add_F32.v3 (lhs: f32[], rhs: f32[]) -> f32[] {
%lhs = f32[] parameter(0)
%rhs = f32[] parameter(1)
ROOT %add = f32[] add(f32[] %lhs, f32[] %rhs)
}
ENTRY %R4UnitWindowScalar () -> f32[] {
%constant = f32[] constant(42)
%constant.1 = f32[] constant(1)
ROOT %reduce-window = f32[] reduce-window(f32[] %constant, f32[] %constant.1), to_apply=%add_F32.v3
}
)"
},
// convolution
{
"Convolution",
R"(HloModule Convolve1D1Window_0_module
ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2,1] {
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f, operand_precision={high,default}
}
)"
},
// convolution rank 2
{
"ConvolutionR2",
R"(HloModule ConvolveR2_module
ENTRY %ConvolveR2.v3 (input: f32[1,2], filter: f32[1,1]) -> f32[1,2] {
%input = f32[1,2]{1,0} parameter(0)
%filter = f32[1,1]{1,0} parameter(1)
ROOT %convolution = f32[1,2]{0,1} convolution(f32[1,2]{1,0} %input, f32[1,1]{1,0} %filter), dim_labels=bf_io->bf
}
)"
},
// convolution backward
{
"ConvolutionBackward",
R"(HloModule ConvolveBackward_module
ENTRY %ConvolveBackward (input: f32[128,7,7,512], filter: f32[3,3,512,512]) -> f32[128,14,14,512] {
%input = f32[128,7,7,512]{0,3,2,1} parameter(0)
%filter = f32[3,3,512,512]{3,2,1,0} parameter(1)
ROOT %convolution-base-dilated = f32[128,14,14,512]{0,3,2,1} convolution(f32[128,7,7,512]{0,3,2,1} %input, f32[3,3,512,512]{3,2,1,0} %filter), window={size=3x3 pad=1_2x1_2 lhs_dilate=2x2 rhs_reversal=1x1}, dim_labels=b01f_01oi->b01f
}
)"
},
// reverse(constant)
{
"Reverse4D",
R"(HloModule Reverse4DFloatArrayOnDim01_module
ENTRY %Reverse4DFloatArrayOnDim01.v2 () -> f32[4,3,2,1] {
%constant = f32[4,3,2,1]{0,1,2,3} constant({ { /*i0=0*/ { /*i1=0*/ {1}, {2} }, { /*i1=1*/ {3}, {4} }, { /*i1=2*/ {5}, {6} } }, { /*i0=1*/ { /*i1=0*/ {7}, {8} }, { /*i1=1*/ {9}, {10} }, { /*i1=2*/ {11}, {12} } }, { /*i0=2*/ { /*i1=0*/ {13}, {14} }, { /*i1=1*/ {15}, {16} }, { /*i1=2*/ {17}, {18} } }, { /*i0=3*/ { /*i1=0*/ {19}, {20} }, { /*i1=1*/ {21}, {22} }, { /*i1=2*/ {23}, {24} } } })
ROOT %reverse = f32[4,3,2,1]{0,1,2,3} reverse(f32[4,3,2,1]{0,1,2,3} %constant), dimensions={0,1}
}
)"
},
// concat
{
"Concat",
R"(HloModule Concat2x3With2x5_module
ENTRY %Concat2x3With2x5.v3 () -> f32[2,8] {
%constant = f32[2,3]{1,0} constant({ { 0, 1, 2 }, { 1000, 1001, 1002 } })
%constant.1 = f32[2,5]{1,0} constant({ { 64, 65, 66, 67, 68 }, { 1064, 1065, 1066, 1067, 1068 } })
ROOT %concatenate = f32[2,8]{1,0} concatenate(f32[2,3]{1,0} %constant, f32[2,5]{1,0} %constant.1), dimensions={1}
}
)"
},
// select and scatter
{
"SelectAndScatter",
R"(HloModule R4F32OverlapSmall_module
%ge_F32.v3 (lhs: f32[], rhs: f32[]) -> pred[] {
%lhs = f32[] parameter(0)
%rhs = f32[] parameter(1)
ROOT %greater-than-or-equal-to = pred[] compare(f32[] %lhs, f32[] %rhs), direction=GE
}
%add_F32.v3 (lhs.1: f32[], rhs.1: f32[]) -> f32[] {
%lhs.1 = f32[] parameter(0)
%rhs.1 = f32[] parameter(1)
ROOT %add = f32[] add(f32[] %lhs.1, f32[] %rhs.1)
}
ENTRY %R4F32OverlapSmall.v4 () -> f32[4,5,1,1] {
%constant = f32[4,5,1,1]{3,2,1,0} constant({ { /*i0=0*/ { /*i1=0*/ {7} }, { /*i1=1*/ {2} }, { /*i1=2*/ {5} }, { /*i1=3*/ {3} }, { /*i1=4*/ {8} } }, { /*i0=1*/ { /*i1=0*/ {3} }, { /*i1=1*/ {8} }, { /*i1=2*/ {9} }, { /*i1=3*/ {3} }, { /*i1=4*/ {4} } }, { /*i0=2*/ { /*i1=0*/ {1} }, { /*i1=1*/ {5} }, { /*i1=2*/ {7} }, { /*i1=3*/ {5} }, { /*i1=4*/ {6} } }, { /*i0=3*/ { /*i1=0*/ {0} }, { /*i1=1*/ {6} }, { /*i1=2*/ {2} }, { /*i1=3*/ {10} }, { /*i1=4*/ {2} } } })
%constant.1 = f32[2,2,1,1]{3,2,1,0} constant({ { /*i0=0*/ { /*i1=0*/ {2} }, { /*i1=1*/ {6} } }, { /*i0=1*/ { /*i1=0*/ {3} }, { /*i1=1*/ {1} } } })
%constant.2 = f32[] constant(0)
ROOT %select-and-scatter = f32[4,5,1,1]{3,2,1,0} select-and-scatter(f32[4,5,1,1]{3,2,1,0} %constant, f32[2,2,1,1]{3,2,1,0} %constant.1, f32[] %constant.2), window={size=2x3x1x1 stride=2x2x1x1}, select=%ge_F32.v3, scatter=%add_F32.v3
}
)"
},
// select and scatter on scalar
{
"SelectAndScatterScalar",
R"(HloModule select_and_scatter_scalar
%ge_F32.v3 (lhs: f32[], rhs: f32[]) -> pred[] {
%lhs = f32[] parameter(0)
%rhs = f32[] parameter(1)
ROOT %greater-than-or-equal-to = pred[] compare(f32[] %lhs, f32[] %rhs), direction=GE
}
%add_F32.v3 (lhs.1: f32[], rhs.1: f32[]) -> f32[] {
%lhs.1 = f32[] parameter(0)
%rhs.1 = f32[] parameter(1)
ROOT %add = f32[] add(f32[] %lhs.1, f32[] %rhs.1)
}
ENTRY %SelectAndScatterScalar () -> f32[] {
%constant = f32[] constant(42)
%constant.1 = f32[] constant(1)
%constant.2 = f32[] constant(2)
ROOT %select-and-scatter = f32[] select-and-scatter(f32[] %constant, f32[] %constant.1, f32[] %constant.2), select=%ge_F32.v3, scatter=%add_F32.v3
}
)"
},
// slice
{
"Slice",
R"(HloModule slice_module
ENTRY %slice.v2 (p0: f32[3,3,4,4]) -> f32[3,3,2,4] {
%p0 = f32[3,3,4,4]{3,2,1,0} parameter(0)
ROOT %slice = f32[3,3,2,4]{3,2,1,0} slice(f32[3,3,4,4]{3,2,1,0} %p0), slice={[0:3:1], [0:3:1], [0:4:2], [0:4:1]}
}
)"
},
// slice, no stride
{
"SliceNoStride",
R"(HloModule Slice3x3x3_To_1x3x3_F32_module
ENTRY %Slice3x3x3_To_1x3x3_F32.v2 () -> f32[1,3,3] {
%constant = f32[3,3,3]{2,1,0} constant({ { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }, { { 9, 10, 11 }, { 12, 13, 14 }, { 15, 16, 17 } }, { { 18, 19, 20 }, { 21, 22, 23 }, { 24, 25, 26 } } })
ROOT %slice = f32[1,3,3]{2,1,0} slice(f32[3,3,3]{2,1,0} %constant), slice={[0:1], [0:3], [0:3]}
}
)"
},
// slice R0
{
"SliceR0",
R"(HloModule SliceR0_module
ENTRY %SliceR0.v2 () -> s32[] {
%constant = s32[] constant(1)
ROOT %slice = s32[] slice(s32[] %constant), slice={}
}
)"
},
// transpose
{
"Transpose",
R"(HloModule Transpose_module
ENTRY %Transpose.v2 () -> s32[1,2,3] {
%constant = s32[1,2,3]{2,1,0} constant({ { { 1, 2, 3 }, { 4, 5, 6 } } })
ROOT %transpose = s32[1,2,3]{2,1,0} transpose(s32[1,2,3]{2,1,0} %constant), dimensions={0,1,2}
}
)"
},
{
"TransposeC128",
R"(HloModule TransposeC128_module
ENTRY %Transpose.v3 (input: c128[1,2,3]) -> c128[1,2,3] {
%input = c128[1,2,3]{2,1,0} parameter(0)
ROOT %transpose = c128[1,2,3]{2,1,0} transpose(c128[1,2,3]{2,1,0} %input), dimensions={0,1,2}
}
)"
},
// Triangular solve
{
"TriangularSolve",
R"(HloModule TriangularSolve_module
ENTRY %SimpleRightLowerNotranspose.4 (a.1: f32[4,4], b.2: f32[3,4]) -> f32[3,4] {
%a.1 = f32[4,4]{1,0} parameter(0)
%b.2 = f32[3,4]{1,0} parameter(1)
ROOT %triangular-solve.3 = f32[3,4]{1,0} triangular-solve(f32[4,4]{1,0} %a.1, f32[3,4]{1,0} %b.2), lower=true, transpose_a=NO_TRANSPOSE
}
)"
},
// Dynamic slice
{
"DynamicSlice",
R"(HloModule DynamicSlice_module
ENTRY %DynamicSlice.v5 (original_parameter: s32[2,2,258], start_index: s32[1]) -> s32[2,2,258] {
%original_parameter = s32[2,2,258]{2,1,0} parameter(0)
%constant = s32[1]{0} constant({0})
%start_index = s32[1]{0} parameter(1)
%concatenate = s32[3]{0} concatenate(s32[1]{0} %constant, s32[1]{0} %constant, s32[1]{0} %start_index), dimensions={0}
ROOT %dynamic-slice = s32[2,2,258]{2,1,0} dynamic-slice(s32[2,2,258]{2,1,0} %original_parameter, s32[3]{0} %concatenate), dynamic_slice_sizes={2,2,258}
}
)"
},
// Dynamic slice with scalar indices
{
"DynamicSliceScalarIndices",
R"(HloModule DynamicSlice_module
ENTRY %DynamicSlice.v5 (original_parameter: s32[2,2,258], start_index: s32[]) -> s32[2,2,258] {
%original_parameter = s32[2,2,258]{2,1,0} parameter(0)
%constant = s32[] constant(0)
%start_index = s32[] parameter(1)
ROOT %dynamic-slice = s32[2,2,258]{2,1,0} dynamic-slice(s32[2,2,258]{2,1,0} %original_parameter, s32[] %constant, s32[] %constant, s32[] %start_index), dynamic_slice_sizes={2,2,258}
}
)"
},
// Dynamic update slice
{
"DynamicUpdateSlice",
R"(HloModule DynamicSlice_module
ENTRY %DynamicUpdateSlice.v4 (input: s32[1,1,25,1], update: s32[1,1,2,1], start_indices: s32[4]) -> s32[1,1,25,1] {
%input = s32[1,1,25,1]{3,2,1,0} parameter(0)
%update = s32[1,1,2,1]{3,2,1,0} parameter(1)
%start_indices = s32[4]{0} parameter(2)
ROOT %dynamic-update-slice = s32[1,1,25,1]{3,2,1,0} dynamic-update-slice(s32[1,1,25,1]{3,2,1,0} %input, s32[1,1,2,1]{3,2,1,0} %update, s32[4]{0} %start_indices)
}
)"
},
// Dynamic update slice with scalar indices
{
"DynamicUpdateSliceScalarIndex",
R"(HloModule DynamicUpdateSlice_module
ENTRY %DynamicUpdateSlice.v4 (input: s32[1,1,25,1], update: s32[1,1,2,1], start_index.0: s32[], start_index.1: s32[], start_index.2: s32[], start_index.3: s32[]) -> s32[1,1,25,1] {
%input = s32[1,1,25,1]{3,2,1,0} parameter(0)
%update = s32[1,1,2,1]{3,2,1,0} parameter(1)
%start_index.0 = s32[] parameter(2)
%start_index.1 = s32[] parameter(3)
%start_index.2 = s32[] parameter(4)
%start_index.3 = s32[] parameter(5)
ROOT %dynamic-update-slice = s32[1,1,25,1]{3,2,1,0} dynamic-update-slice(s32[1,1,25,1]{3,2,1,0} %input, s32[1,1,2,1]{3,2,1,0} %update, s32[] %start_index.0, s32[] %start_index.1, s32[] %start_index.2, s32[] %start_index.3)
}
)"
},
// batch norm training
{
"BatchNormTraining",
R"(HloModule BasicTraining_module
ENTRY %BasicTraining.v4 () -> (f32[2,2,1,2], f32[2], f32[2]) {
%constant = f32[2,2,1,2]{3,2,1,0} constant({ { /*i0=0*/ { /*i1=0*/ { 1, 2 } }, { /*i1=1*/ { 3, 4 } } }, { /*i0=1*/ { /*i1=0*/ { 5, 6 } }, { /*i1=1*/ { 7, 8 } } } })
%constant.1 = f32[2]{0} constant({2, 3})
%constant.2 = f32[2]{0} constant({1, 2})
ROOT %batch-norm-training = (f32[2,2,1,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training(f32[2,2,1,2]{3,2,1,0} %constant, f32[2]{0} %constant.1, f32[2]{0} %constant.2), epsilon=0.001, feature_index=3
}
)"
},
// batch norm inference
{
"BatchNormInference",
R"(HloModule BatchNormInference_module
ENTRY %BatchNormInference.v6 (input: f32[2,2,2,2], offset: f32[2], scale: f32[2], mean: f32[2], variance: f32[2]) -> f32[2,2,2,2] {
%input = f32[2,2,2,2]{3,2,1,0} parameter(0)
%offset = f32[2]{0} parameter(1)
%scale = f32[2]{0} parameter(2)
%mean = f32[2]{0} parameter(3)
%variance = f32[2]{0} parameter(4)
ROOT %batch-norm-inference = f32[2,2,2,2]{3,2,1,0} batch-norm-inference(f32[2,2,2,2]{3,2,1,0} %input, f32[2]{0} %offset, f32[2]{0} %scale, f32[2]{0} %mean, f32[2]{0} %variance), epsilon=0.001, feature_index=0
}
)"
},
// batch norm grad
{
"BatchNormGrad",
R"(HloModule BatchNormGrad_module
ENTRY %BatchNormGrad.v4 (input: f32[2,2,2,2], scale: f32[2], mean: f32[2], variance: f32[2], grad_output: f32[2,2,2,2]) -> (f32[2,2,2,2], f32[2], f32[2]) {
%input = f32[2,2,2,2]{3,2,1,0} parameter(0)
%scale = f32[2]{0} parameter(1)
%mean = f32[2]{0} parameter(2)
%variance = f32[2]{0} parameter(3)
%grad_output = f32[2,2,2,2]{3,2,1,0} parameter(4)
ROOT %batch-norm-grad = (f32[2,2,2,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad(f32[2,2,2,2]{3,2,1,0} %input, f32[2]{0} %scale, f32[2]{0} %mean, f32[2]{0} %variance, f32[2,2,2,2]{3,2,1,0} %grad_output), epsilon=0.001, feature_index=0
}
)"
},
// fft
{
"Fft",
R"(HloModule Fft_module
ENTRY %Fft (input: c64[8,32]) -> c64[8,32] {
%input = c64[8,32]{1,0} parameter(0)
ROOT %fft = c64[8,32]{1,0} fft(c64[8,32]{1,0} %input), fft_type=FFT, fft_length={32}
}
)"
},
// ifft
{
"Ifft2d",
R"(HloModule Ifft2d_module
ENTRY %Ifft2d (input: c64[5,8,32]) -> c64[5,8,32] {
%input = c64[5,8,32]{2,1,0} parameter(0)
ROOT %fft = c64[5,8,32]{2,1,0} fft(c64[5,8,32]{2,1,0} %input), fft_type=IFFT, fft_length={8,32}
}
)"
},
// rfft2d
{
"Rfft2d",
R"(HloModule Rfft2d_module
ENTRY %Rfft2d (input: f32[5,64,32]) -> c64[5,64,17] {
%input = f32[5,64,32]{2,1,0} parameter(0)
ROOT %fft = c64[5,64,17]{2,1,0} fft(f32[5,64,32]{2,1,0} %input), fft_type=RFFT, fft_length={64,32}
}
)"
},
// irfft3d
{
"Irfft3d",
R"(HloModule Irfft3d_module
ENTRY %Irfft3d (input: c64[5,64,128,33]) -> f32[5,64,128,64] {
%input = c64[5,64,128,33]{3,2,1,0} parameter(0)
ROOT %fft = f32[5,64,128,64]{3,2,1,0} fft(c64[5,64,128,33]{3,2,1,0} %input), fft_type=IRFFT, fft_length={64,128,64}
}
)"
},
// pad
{
"Pad",
R"(HloModule Pad1DS3Array_module
ENTRY %Pad1DS3Array.v3 () -> f32[8] {
%constant = f32[3]{0} constant({1, 2, 3})
%constant.1 = f32[] constant(0.1)
ROOT %pad = f32[8]{0} pad(f32[3]{0} %constant, f32[] %constant.1), padding=3_1
}
)"
},
// pad has interior
{
"PadHasInterior",
R"(HloModule PadHasInterior_module
ENTRY %PadHasInterior.v3 (input: f32[1,25,7,7]) -> f32[1,25,17,11] {
%input = f32[1,25,7,7]{3,2,1,0} parameter(0)
%constant = f32[] constant(-5.123)
ROOT %pad = f32[1,25,17,11]{3,2,1,0} pad(f32[1,25,7,7]{3,2,1,0} %input, f32[] %constant), padding=0_0_0x0_0_0x2_2_1x2_2_0
}
)"
},
// Negative padding
{
"PadHasNegativePadding",
R"(HloModule PadHasNegativePadding_module
ENTRY %PadHasNegativePadding (input: f32[1,25,7,7,10]) -> f32[1,15,6,3,29] {
%input = f32[1,25,7,7,10]{4,3,2,1,0} parameter(0)
%constant = f32[] constant(-5.123)
ROOT %pad = f32[1,15,6,3,29]{4,3,2,1,0} pad(f32[1,25,7,7,10]{4,3,2,1,0} %input, f32[] %constant), padding=0_0_0x0_-10_0x0_-1_0x-2_-2_0x-1_-1_3
}
)"
},
// fusion
{
"Fusion",
R"(HloModule fusion_module
%fused_computation (constant.param_0: f32[3,2,1,1], constant.1.param_1: f32[2]) -> f32[3,2,1,1] {
%constant.param_0 = f32[3,2,1,1]{3,2,1,0} parameter(0)
%constant.1.param_1 = f32[2]{0} parameter(1)
%broadcast = f32[3,2,1,1]{3,2,1,0} broadcast(f32[2]{0} %constant.1.param_1), dimensions={1}
ROOT %subtract = f32[3,2,1,1]{3,2,1,0} subtract(f32[3,2,1,1]{3,2,1,0} %constant.param_0, f32[3,2,1,1]{3,2,1,0} %broadcast)
}
ENTRY %fusion.v3 () -> f32[3,2,1,1] {
%constant = f32[3,2,1,1]{3,2,1,0} constant({ { /*i0=0*/ { /*i1=0*/ {-1} }, { /*i1=1*/ {4.1} } }, { /*i0=1*/ { /*i1=0*/ {2} }, { /*i1=1*/ {4.1} } }, { /*i0=2*/ { /*i1=0*/ {5} }, { /*i1=1*/ {4.4} } } })
%constant.1 = f32[2]{0} constant({3.14, 4.25})
ROOT %fusion = f32[3,2,1,1]{3,2,1,0} fusion(f32[3,2,1,1]{3,2,1,0} %constant, f32[2]{0} %constant.1), kind=kLoop, calls=%fused_computation
}
)"
},
{
"Sparse",
R"(HloModule sparse_f32
ENTRY %sparse () -> f32[2,3,4] {
ROOT %foo = f32[2,3,4]sparse{10} constant({[0, 1, 2]: 1, [1, 2, 2]: 2, [1, 2, 3]: 3})
}
)"
},
{
"SparseC128",
R"(HloModule sparse_c128
ENTRY %sparse () -> c128[2,3,4] {
ROOT %foo = c128[2,3,4]sparse{10} constant({[0, 1, 2]: (1, 0), [1, 2, 2]: (2, 5), [1, 2, 3]: (3, 10)})
}
)"
},
{
"SparseEmpty",
R"(HloModule sparse_f32_empty
ENTRY %sparse_f32_empty () -> f32[2,3,4] {
ROOT %foo = f32[2,3,4]sparse{10} constant({})
}
)"
},
{
"SparseR1",
R"(HloModule sparse_f32_r1
ENTRY %sparse_f32_r1 () -> f32[9] {
ROOT %foo = f32[9]sparse{10} constant({1: 2, 3: 4, 5: 6})
}
)"
},
{
"gather",
R"(HloModule StringifyGather
ENTRY %Gather (input_tensor: f32[50,49,48,47,46], start_indices: s64[10,9,8,7,5]) -> f32[10,9,8,7,30,29,28,27,26] {
%input_tensor = f32[50,49,48,47,46]{4,3,2,1,0} parameter(0)
%start_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
ROOT %gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, s64[10,9,8,7,5]{4,3,2,1,0} %start_indices), offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, start_index_map={0,1,2,3,4}, index_vector_dim=4, slice_sizes={30,29,28,27,26}
}
)"
},
{
"scatter",
R"(HloModule StringifyScatter
%add_F32.v3 (lhs: f32[], rhs: f32[]) -> f32[] {
%lhs = f32[] parameter(0)
%rhs = f32[] parameter(1)
ROOT %add = f32[] add(f32[] %lhs, f32[] %rhs)
}
ENTRY %Scatter (input_tensor: f32[50,49,48,47,46], scatter_indices: s64[10,9,8,7,5], updates: f32[10,9,8,7,30,29,28,27,26]) -> f32[50,49,48,47,46] {
%input_tensor = f32[50,49,48,47,46]{4,3,2,1,0} parameter(0)
%scatter_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
%updates = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} parameter(2)
ROOT %scatter = f32[50,49,48,47,46]{4,3,2,1,0} scatter(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, s64[10,9,8,7,5]{4,3,2,1,0} %scatter_indices, f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} %updates), update_window_dims={4,5,6,7,8}, inserted_window_dims={}, scatter_dims_to_operand_dims={0,1,2,3,4}, index_vector_dim=4, to_apply=%add_F32.v3
}
)"
},
{
"ConstantUnsignedNoUnderflow",
R"(HloModule ConstantUnsignedNoUnderflow_module
ENTRY %ConstantUnsignedNoUnderflow () -> u64[] {
ROOT %constant = u64[] constant(1)
}
)"
},
{
"ConstantUnsignedNoOverflow",
R"(HloModule ConstantUnsignedNoOverflow_module
ENTRY %ConstantUnsignedNoOverflow () -> u64[] {
ROOT %constant = u64[] constant(9223372036854775807)
}
)"
},
// CustomCallWithLayoutConstraints
{
"CustomCallWithLayoutConstraints",
R"(HloModule CustomCallWithLayoutConstraints
ENTRY %CustomCallWithLayoutConstraints (p0: f32[42,2,3], p1: f32[123,4]) -> f32[1,2,3] {
%p0 = f32[42,2,3]{0,1,2} parameter(0)
%p1 = f32[123,4]{0,1} parameter(1)
ROOT %custom-call = f32[1,2,3]{0,2,1} custom-call(f32[42,2,3]{0,1,2} %p0, f32[123,4]{0,1} %p1), custom_call_target="baz", operand_layout_constraints={f32[42,2,3]{0,1,2}, f32[123,4]{1,0}}
}
)"
},
// CustomCallWithLayoutConstraintsNoOperands
{
"CustomCallWithLayoutConstraintsNoOperands",
R"(HloModule CustomCallWithLayoutConstraintsNoOperands
ENTRY %CustomCallWithLayoutConstraints () -> f32[1,2,3] {
ROOT %custom-call = f32[1,2,3]{0,2,1} custom-call(), custom_call_target="baz", operand_layout_constraints={}
}
)"
},
// CustomCallWithLayoutConstraintsTupleShapes
{
"CustomCallWithLayoutConstraintsTupleShapes",
R"(HloModule CustomCallWithLayoutConstraintsTupleShapes
ENTRY %CustomCallWithLayoutConstraints (p0: (f32[2,2], f32[42,2,3]), p1: f32[123,4]) -> (f32[1,2,3], f32[1,2,3]) {
%p0 = (f32[2,2]{0,1}, f32[42,2,3]{0,1,2}) parameter(0)
%p1 = f32[123,4]{0,1} parameter(1)
ROOT %custom-call = (f32[1,2,3]{0,2,1}, f32[1,2,3]{1,2,0}) custom-call((f32[2,2]{0,1}, f32[42,2,3]{0,1,2}) %p0, f32[123,4]{0,1} %p1), custom_call_target="baz", operand_layout_constraints={(f32[2,2]{1,0}, f32[42,2,3]{2,0,1}), f32[123,4]{1,0}}
}
)"
},
// Parse c64 literal
{
"ParseC64Literal",
R"(HloModule ParseC64Literal
ENTRY %ParseC64Literal () -> c64[2] {
ROOT %c = c64[2]{0} constant({(1, 2), (-inf, nan)})
}
)"
},
// Parse c128 literal
{
"ParseC128Literal",
R"(HloModule ParseC128Literal
ENTRY %ParseC128Literal () -> c128[2] {
ROOT %c = c128[2]{0} constant({(1, 2), (-inf, nan)})
}
)"
},
// Indexed Conditional
{
"IndexedConditional",
R"(HloModule indexed_conditional
%Negate (x: f32[]) -> f32[] {
%x = f32[] parameter(0)
ROOT %negate = f32[] negate(f32[] %x)
}
%Identity (y: f32[]) -> f32[] {
%y = f32[] parameter(0)
ROOT %copy = f32[] copy(f32[] %y)
}
%Floor (z: f32[]) -> f32[] {
%z = f32[] parameter(0)
ROOT %floor = f32[] floor(f32[] %z)
}
ENTRY %Parameters1.v4 () -> f32[] {
%constant = s32[] constant(1)
%constant.1 = f32[] constant(56)
%constant.2 = f32[] constant(12)
%constant.3 = f32[] constant(13)
ROOT %conditional = f32[] conditional(s32[] %constant, f32[] %constant.1, f32[] %constant.2, f32[] %constant.3), branch_computations={%Negate, %Identity, %Floor}
}
)"
},
});
// clang-format on
}
std::vector<TestData> CreateShortTestCases() {
// clang-format off
return std::vector<TestData>({
// map
{
"Map",
R"(HloModule MapBinaryAdder_module
add_F32.v3 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY MapBinaryAdder.v3 {
param0 = f32[4]{0} parameter(0)
param1 = f32[4]{0} parameter(1)
ROOT map = f32[4]{0} map(param0, param1), dimensions={0}, to_apply=add_F32.v3
}
)"
},
// reduce
{
"Reduce",
R"(HloModule ReduceR3ToR2_module
add_F32.v3 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY ReduceR3ToR2.v3 {
input = f32[8,16,256]{2,1,0} parameter(0)
constant = f32[] constant(0)
ROOT reduce = f32[8,16]{1,0} reduce(input, constant), dimensions={2}, to_apply=add_F32.v3
}
)"
},
// tuple reduce
{
"TupleReduce",
R"(HloModule TupleReduce
max_argmax {
value = f32[] parameter(2)
prev_max = f32[] parameter(0)
is_next_larger = pred[] compare(value, prev_max), direction=GE
max = f32[] select(is_next_larger, value, prev_max)
index = s32[] parameter(3)
prev_argmax = s32[] parameter(1)
argmax = s32[] select(is_next_larger, index, prev_argmax)
ROOT pair = (f32[], s32[]) tuple(max, argmax)
}
ENTRY reduce_entry {
values = f32[1024]{0} parameter(0)
indices = f32[1024]{0} parameter(1)
init_value = f32[] constant(-inf)
init_index = s32[] constant(-1)
ROOT result = (f32[], s32[]) reduce(values, indices, init_value, init_index), dimensions={0}, to_apply=max_argmax
}
)"
},
// infeed/outfeed
{
"InfeedOutfeed",
R"(HloModule outfeed_module
ENTRY InfeedToOutfeed {
token0 = token[] after-all()
infeed = ((u32[3]{0}, pred[]), token[]) infeed(token0)
infeed.data = (u32[3]{0}, pred[]) get-tuple-element(infeed), index=0
outfeed = token[] outfeed(infeed.data, token0)
ROOT infeed.1 = ((u32[3]{0}, pred[]), token[]) infeed(token0)
infeed.1.data = (u32[3]{0}, pred[]) get-tuple-element(infeed.1), index=0
infeed.1.token = token[] get-tuple-element(infeed.1), index=1
outfeed.1 = token[] outfeed(infeed.1.data, infeed.1.token)
}
)"
},
// Rng
{
"Rng",
R"(HloModule rng_module
ENTRY Rng {
constant = f32[] constant(0)
constant.1 = f32[] constant(1)
ROOT rng = f32[8]{0} rng(constant, constant.1), distribution=rng_uniform
}
)"
},
// Reduce precision
{
"ReducePrevison",
R"(HloModule reduce_precision
ENTRY ReducePrecision {
constant = f32[1]{0} constant({3.14159})
ROOT reduce-precision = f32[1]{0} reduce-precision(constant), exponent_bits=8, mantissa_bits=10
}
)"
},
// Sort (Key)
{
"SortKey",
R"(HloModule sort
compare {
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
x = f32[1024]{0} parameter(0)
ROOT sorted = f32[1024]{0} sort(x), dimensions={0}, to_apply=compare
}
)"
},
// Sort (Key, Value)
{
"SortKeyValue",
R"(HloModule sort
compare {
p.1.lhs = s32[] parameter(2)
p.1.rhs = s32[] parameter(3)
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
keys = f32[1024]{0} parameter(0)
values = s32[1024]{0} parameter(1)
ROOT sorted = (f32[1024]{0}, s32[1024]{0}) sort(keys, values), dimensions={0}, to_apply=compare
}
)"
},
// R2 Sort (Key)
{
"SortKeyR2",
R"(HloModule sort
compare {
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
x = f32[1024,16]{0,1} parameter(0)
ROOT sorted = f32[1024,16]{0,1} sort(x), dimensions={0}, to_apply=compare
}
)"
},
// R2 Sort (Key, Value)
{
"SortKeyValueR2",
R"(HloModule sort
compare {
p.1.lhs = s32[] parameter(2)
p.1.rhs = s32[] parameter(3)
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
keys = f32[1024,16]{0,1} parameter(0)
values = s32[1024,16]{0,1} parameter(1)
ROOT sorted = (f32[1024,16]{0,1}, s32[1024,16]{0,1}) sort(keys, values), dimensions={0}, to_apply=compare
}
)"
},
// Sort (Key, Value, Value, Value)
{
"SortManyValues",
R"(HloModule sort
compare {
p.1.lhs = s32[] parameter(2)
p.1.rhs = s32[] parameter(3)
p.2.lhs = u32[] parameter(4)
p.2.rhs = u32[] parameter(5)
p.3.lhs = f32[] parameter(6)
p.3.rhs = f32[] parameter(7)
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
keys = f32[1024,16]{0,1} parameter(0)
values.0 = s32[1024,16]{0,1} parameter(1)
values.1 = u32[1024,16]{0,1} parameter(2)
values.2 = f32[1024,16]{0,1} parameter(3)
ROOT sorted = (f32[1024,16]{0,1}, s32[1024,16]{0,1}, u32[1024,16]{0,1}, f32[1024,16]{0,1}) sort(keys, values.0, values.1, values.2), dimensions={0}, to_apply=compare
}
)"
},
// Sort (Key) is_stable=true
{
"SortKeyStable",
R"(HloModule sort
compare {
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lt = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
x = f32[1024]{0} parameter(0)
ROOT sorted = f32[1024]{0} sort(x), dimensions={0}, is_stable=true, to_apply=compare
}
)"
},
// Indexed Conditional
{
"IndexedConditional",
R"(HloModule indexed_conditional
Negate {
x = f32[] parameter(0)
ROOT negate = f32[] negate(x)
}
Identity {
y = f32[] parameter(0)
ROOT copy = f32[] copy(y)
}
Floor {
z = f32[] parameter(0)
ROOT floor = f32[] floor(z)
}
ENTRY Parameters1.v4 {
constant = s32[] constant(1)
constant.1 = f32[] constant(56)
constant.2 = f32[] constant(12)
constant.3 = f32[] constant(13)
ROOT conditional = f32[] conditional(constant, constant.1, constant.2, constant.3), branch_computations={Negate, Identity, Floor}
}
)"
},
// Predicated Conditional
{
"PredicatedConditional",
R"(HloModule pred_conditional
Negate {
x = f32[] parameter(0)
ROOT negate = f32[] negate(x)
}
Identity {
y = f32[] parameter(0)
ROOT copy = f32[] copy(y)
}
ENTRY Parameters1.v4 {
constant = pred[] constant(true)
constant.1 = f32[] constant(56)
constant.2 = f32[] constant(12)
ROOT conditional = f32[] conditional(constant, constant.1, constant.2), true_computation=Negate, false_computation=Identity
}
)"
},
// CustomCall
{
"CustomCall",
R"(HloModule custom_call
ENTRY CustomCall {
constant = f32[1]{0} constant({12345})
ROOT custom-call = f32[1,2,3]{0,2,1} custom-call(constant), custom_call_target="foo\"bar"
}
)"
},
// CustomCall with opaque value.
{
"CustomCallWithOpaque",
R"(HloModule custom_call
ENTRY CustomCall {
constant = f32[1]{0} constant({12345})
ROOT custom-call = f32[1,2,3]{0,2,1} custom-call(constant), custom_call_target="foo\"bar", opaque="this string is opaque"
}
)"
},
// Variables with non-default names
{
"NonDefaultNames",
R"(HloModule add_constants_module
ENTRY add_constants {
foo = f32[] constant(3.14)
ROOT bar = f32[] add(foo, foo)
}
)"
},
{
"Dot",
R"(HloModule dot
ENTRY dot {
a = f32[2,10]{1,0} parameter(0)
b = f32[10,3]{1,0} parameter(1)
ROOT dot = f32[2,3]{1,0} dot(a, b), lhs_batch_dims={0}, lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)"
},
{
"gather",
R"(HloModule gather
ENTRY Gather {
input_tensor = f32[50,49,48,47,46]{4,3,2,1,0} parameter(0)
start_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
ROOT gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(input_tensor, start_indices), offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, start_index_map={0,1,2,3,4}, index_vector_dim=4, slice_sizes={30,29,28,27,26}
}
)"
},
// all-reduce
{
"AllReduce",
R"(HloModule CRS
add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY CRS {
input = f32[8]{0} parameter(0)
ROOT crs = f32[8]{0} all-reduce(input), replica_groups={}, to_apply=add
}
)"
},
// all-reduce with subgroups
{
"AllReduceWithSubgroups",
R"(HloModule CRS_Subgroups
add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY AllReduceWithSubgroups {
input = f32[128,32]{0,1} parameter(0)
ROOT all-reduce = f32[128,32]{0,1} all-reduce(input), replica_groups={{0,1},{2,3}}, barrier="abc", to_apply=add
}
)"
},
// all-reduce with all-reduce-id
{
"AllReduceAllReduce",
R"(HloModule CRS
add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY CRS {
input = f32[8]{0} parameter(0)
crs.1 = f32[8]{0} all-reduce(input), replica_groups={{0}}, all_reduce_id=1, to_apply=add
ROOT crs.0 = f32[8]{0} all-reduce(input), replica_groups={{0}}, all_reduce_id=1, to_apply=add
}
)"
},
// all-to-all
{
"AllToAll",
R"(HloModule AllToAll
ENTRY AllToAll {
input = f32[128,32]{0,1} parameter(0)
ROOT a2a = f32[128,32]{0,1} all-to-all(input), replica_groups={}
}
)"
},
// all-to-all with subgroups
{
"AllToAllWithSubgroups",
R"(HloModule AllToAllWithSubgroups
ENTRY AllToAllWithSubgroups {
input = f32[128,32]{0,1} parameter(0)
ROOT a2a = f32[128,32]{0,1} all-to-all(input), replica_groups={{1,2},{3,0}}
}
)"
},
// collective-permute
{
"CollectivePermute",
R"(HloModule CollectivePermute
ENTRY CollectivePermute {
input = f32[128,32]{0,1} parameter(0)
ROOT root = f32[128,32]{0,1} collective-permute(input), source_target_pairs={{0,1},{1,2},{2,3}}
}
)"
},
// replica-id
{
"ReplicaId",
R"(HloModule replica-id
ENTRY Replica-id {
ROOT replica-id = u32[] replica-id()
}
)"
},
// Iota
{
"Iota",
R"(HloModule iota
ENTRY Iota {
ROOT iota = f32[100]{0} iota(), iota_dimension=0
}
)"
},
// custom-call with window, dim_labels and feature_group_count
{
"CustomCallWithWindowAndDimLabelsAndFeatureGroupCount",
R"(HloModule CustomCallWithWindowAndDimLabelsAndFeatureGroupCount
ENTRY Computation {
ROOT r = f32[100]{0} custom-call(), window={size=2x2}, dim_labels=b01f_01io->b01f, feature_group_count=2, custom_call_target="target"
}
)"
},
// is_scheduled=true attribute
{
"ScheduledModule",
R"(HloModule scheduled_module, is_scheduled=true
compare {
p.1.lhs = s32[] parameter(2)
p.1.rhs = s32[] parameter(3)
p.0.lhs = f32[] parameter(0)
p.0.rhs = f32[] parameter(1)
ROOT lhs = pred[] compare(p.0.lhs, p.0.rhs), direction=LT
}
ENTRY Sort {
keys = f32[1024]{0} parameter(0)
values = s32[1024]{0} parameter(1)
ROOT sorted = (f32[1024]{0}, s32[1024]{0}) sort(keys, values), dimensions={0}, to_apply=compare
}
)"
},
// AfterAll with multiple operands
{
"AfterAllWithMultipleOperands",
R"(HloModule AfterAllWithMultipleOperands
ENTRY AfterAllWithMultipleOperands {
p0 = f32[] parameter(0)
token0 = token[] after-all()
token1 = token[] after-all()
ROOT after-all = token[] after-all(p0, token0, token1)
}
)"
},
// AddDependency
// A dependency chain is created from 'neg' to 'exp' using tokens.
{
"AddDependency",
R"(HloModule AddDependency
ENTRY AddDependency {
p = f32[] parameter(0)
neg = f32[] negate(p)
token0 = token[] after-all(neg)
p_after_token = f32[] add-dependency(p, token0)
exp = f32[] exponential(p_after_token)
ROOT sum = f32[] add(neg, exp)
}
)"
},
// A module containing constants equal to the min/max values of various data
// types.
{
"MinMaxValues",
R"(HloModule MinMaxValues
ENTRY MinMaxValues {
x.s8 = s8[2]{0} constant({-128, 127})
x.s16 = s16[2]{0} constant({-32768, 32767})
x.s32 = s32[2]{0} constant({-2147483648, 2147483647})
x.u8 = u8[2]{0} constant({0, 255})
x.u16 = u16[2]{0} constant({0, 65535})
x.u32 = u32[2]{0} constant({0, 4294967295})
x.f16 = f16[2]{0} constant({-65504, 65504})
x.bf16 = bf16[2]{0} constant({-3.38953e+38, 3.38953e+38})
x.f32 = f32[2]{0} constant({-3.40282e+38, 3.40282e+38})
x.f64 = f64[2]{0} constant({-1.79769e+308, 1.79769e+308})
x.c64 = c64[2]{0} constant({(-3.40282e+38, 3.40282e+38), (3.40282e+38, -3.40282e+38)})
ROOT c.c128 = c128[2]{0} constant({(-1.79769e+308, 1.79769e+308), (1.79769e+308, -1.79769e+308)})
}
)"
},
});
// clang-format on
}
// The test class for those tests defined above which round-trip through the
// parser and ToString is templatized on two bool parameters:
//
// short_form : used for the "short" test cases which use the ShortParsable
// output form.
// proto_round_trip : whether the module should also be round-tripped through
// HloProto form. This provides much better coverage for the proto
// serialization/deserialization.
//
// The proto_round_trip=true case also technically covers the Parser->ToString
// roundtrip as well, but separating out the Parser->ToString roundtrip as its
// own test provides better isolation and could conceivably catch weirdo bugs
// which are hidden by interaction between the textual and proto roundtripping.
template <bool short_form, bool proto_round_trip>
class HloParameterizedParserTest
: public ::testing::Test,
public ::testing::WithParamInterface<TestData> {
protected:
// Expects "ToString(ParseHloString(string)) == string", that is, parses the
// string, asserts that it succeeded, stringifies the parsed module, and
// checks that it equals the original string.
void ExpectEqual() {
const string& original = GetParam().module_string;
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(original));
if (proto_round_trip) {
TF_ASSERT_OK_AND_ASSIGN(module, HloModule::CreateFromProto(
module->ToProto(), module->config()));
}
if (short_form) {
EXPECT_EQ(original, module->ToString(HloPrintOptions::ShortParsable()));
} else {
EXPECT_EQ(
original,
module->ToString(HloPrintOptions().set_print_large_constants(true)));
}
}
};
// These using shenanigans are required because the TEST_P macro doesn't like
// template instantiations which contain commas.
using HloParserTestLong = HloParameterizedParserTest<false, false>;
using HloParserTestLongProto = HloParameterizedParserTest<false, true>;
using HloParserTestShort = HloParameterizedParserTest<true, false>;
using HloParserTestShortProto = HloParameterizedParserTest<true, true>;
TEST_P(HloParserTestLong, Run) { ExpectEqual(); }
TEST_P(HloParserTestLongProto, Run) { ExpectEqual(); }
TEST_P(HloParserTestShort, Run) { ExpectEqual(); }
TEST_P(HloParserTestShortProto, Run) { ExpectEqual(); }
INSTANTIATE_TEST_SUITE_P(HloParserTestSuccessInstantiation, HloParserTestLong,
::testing::ValuesIn(CreateTestCases()),
TestDataToString);
INSTANTIATE_TEST_SUITE_P(HloParserTestSuccessInstantiation,
HloParserTestLongProto,
::testing::ValuesIn(CreateTestCases()),
TestDataToString);
INSTANTIATE_TEST_SUITE_P(HloParserTestSuccessInstantiation, HloParserTestShort,
::testing::ValuesIn(CreateShortTestCases()),
TestDataToString);
INSTANTIATE_TEST_SUITE_P(HloParserTestSuccessInstantiation,
HloParserTestShortProto,
::testing::ValuesIn(CreateShortTestCases()),
TestDataToString);
class HloParserTest : public ::testing::Test {
protected:
static void ExpectHasSubstr(string_view s, string_view expected) {
EXPECT_TRUE(absl::StrContains(s, expected))
<< "'" << s << "' does not contain '" << expected << "'";
}
};
TEST_F(HloParserTest, Empty) {
const string original = "";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, Garbage) {
const string original = "HloModule thi$ str1ng makes# N0 sen$e @all!*&^%$";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, WrongOpcode) {
const string original = R"(HloModule wrong_opcode:
ENTRY %blabla (x: f32[], y: f32[]) -> f32[] {
%x = f32[]{} parameter(0)
%y = f32[]{} parameter(1)
%le = pred[]{} le(f32[]{} %x, f32[]{} %y)
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, WrongShape) {
const string original = R"(HloModule wrong_opcode:
ENTRY %blabla (x: g32[]) -> g32[] {
%x = g32[]{} parameter(0)
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, WrongOperandsSize) {
const string original = R"(HloModule wrong_opcode:
ENTRY %blabla (x: f32[]) -> pred[] {
%x = f32[]{} parameter(0)
%eq = pred[]{} compare(f32[]{} %x), direction=EQ
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, OperandNotFound) {
const string original = R"(HloModule operand_not_found:
ENTRY %blabla (x: f32[]) -> pred[] {
%x = f32[]{} parameter(0)
%eq = pred[]{} compare(f32[]{} %x, f32[]{} %y), direction=EQ
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, MoreConstants) {
const string original = R"(HloModule SelectScalarS32True_module
ENTRY %SelectScalarS32True.v4 () -> s32[] {
%constant.2 = pred[] constant(true)
%constant.1 = s32[] constant(-42), sharding={devices=[2,2]1,2,3,4}
%constant = s32[] constant(42)
%select = s32[] select(pred[] %constant.2, s32[] %constant.1, s32[] %constant)
}
)";
auto result = ParseHloString(original);
TF_EXPECT_OK(result.status());
// Constant instructions have no name. The string will be parsed successfully
// but the constant names will not be exactly the same.
}
TEST_F(HloParserTest, ConfigurationField) {
const string original = R"(HloModule AModule
ENTRY %configuration_test() -> s32[] {
%constant = s32[] constant(42), backend_config="foo bar"
})";
auto result = ParseHloString(original);
TF_ASSERT_OK(result.status());
EXPECT_EQ("foo bar", result.ValueOrDie()
->entry_computation()
->root_instruction()
->raw_backend_config_string());
}
TEST_F(HloParserTest, LiteralDimensionsMismatch_1) {
const string original = R"(HloModule some_2_module
ENTRY %some_2 () -> f32[2] {
ROOT %constant = f32[2]{0} constant({1,{2}})
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"expects nested array in rank 1, but sees larger");
}
TEST_F(HloParserTest, LiteralDimensionsMismatch_2) {
const string original = R"(HloModule some_2x3_module
ENTRY %some_2x3 () -> f32[2,3] {
ROOT %constant = f32[2,3]{1,0} constant({1, 2, 3, 4, 5, 6})
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"expects nested array in rank 2, but sees 1");
}
TEST_F(HloParserTest, LiteralDimensionsMismatch_3) {
const string original = R"(HloModule some_2x3x2_module
ENTRY %some_2x3x2 () -> f32[2,3,2] {
ROOT %constant = f32[2,3,2]{2,1,0} constant({{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}}})
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"expects 3 elements in the [0]th element");
}
TEST_F(HloParserTest, ConstantF16Overflow) {
const string original =
R"(HloModule ConstantF16Overflow_module
ENTRY %ConstantF16Overflow.v4 () -> f16[] {
ROOT %constant = f16[] constant(-65505)
}
)";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"is out of range for literal's primitive type F16");
}
TEST_F(HloParserTest, ConstantBf16NoOverflow) {
// 65505 is in range for bf16.
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = bf16[] constant(-65505)
})";
EXPECT_EQ(Status::OK(), ParseHloString(original).status());
}
TEST_F(HloParserTest, ConstantBf16Overflow) {
// 1e100 is out of range for bf16.
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = bf16[] constant(1e100)
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"out of range");
}
TEST_F(HloParserTest, ConstantF16OverflowInSparseArray) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f16[5]sparse{10} constant({[0]: 0, [1]: -65505})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"is out of range for literal's primitive type F16");
}
TEST_F(HloParserTest, ConstantUnsignedUnderflow) {
const string original = R"(
HloModule ConstantUnsignedUnderflow_module
ENTRY %ConstantUnsignedUnderflow () -> u64[] {
ROOT %constant = u64[] constant(-1)
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"is out of range for literal's primitive type U64");
}
TEST_F(HloParserTest, ConstantUnsignedOverflow) {
const string original = R"(
HloModule ConstantUnsignedOverflow_module
ENTRY %ConstantUnsignedOverflow () -> u32[] {
ROOT %constant = u32[] constant(4294967296)
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
ExpectHasSubstr(result.status().error_message(),
"is out of range for literal's primitive type U32");
}
TEST_F(HloParserTest, ConstantUnsignedInt64Overflow) {
const string original = R"(
HloModule ConstantUnsignedOverflow_module
ENTRY %ConstantUnsignedOverflow () -> u64[] {
ROOT %constant = u64[] constant(9223372036854775808)
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, ConstantC64Overflow) {
const string original = R"(
HloModule test_module
ENTRY test () -> c64[] {
ROOT c = c64[] constant((1e100, 0))
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, ConstantC64Underflow) {
const string original = R"(
HloModule test_module
ENTRY test () -> c64[] {
ROOT c = c64[] constant((0, -1e100))
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, ConstantF64Overflow) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f64[] constant(1.8e308)
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, ConstantF64Underflow) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f64[] constant(-1.8e308)
})";
auto result = ParseHloString(original);
EXPECT_NE(Status::OK(), result.status());
}
TEST_F(HloParserTest, ConstantWithExp) {
const string original = R"(HloModule ConstantWithExp_module
ENTRY %ConstantWithExp.v4 () -> f32[] {
%constant.1 = f32[] constant(3e+2)
}
)";
auto result = ParseHloString(original);
TF_EXPECT_OK(result.status());
// The string will be parsed successfully but the output strings are not
// exactly the same, because "3e2" is parsed into value 300 and will be
// printed as "300".
}
TEST_F(HloParserTest, ShortConstant) {
const string original = R"(HloModule ShortCOnstant_module
ENTRY %ShortConstant.v4 () -> f32[67,89] {
ROOT %constant.1 = f32[67,89]{1,0} constant({...})
}
)";
auto result = ParseHloString(original);
TF_EXPECT_OK(result.status());
EXPECT_EQ(result.ValueOrDie()->ToString(HloPrintOptions()), original);
}
TEST_F(HloParserTest, AttibutesAnyOrder) {
const string original = R"(HloModule any_order_module
ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2,1] {
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), feature_group_count=1, sharding={maximal device=1}, backend_config="foo", dim_labels=b0f_0io->b0f, window={pad=1_1 size=2}
}
)";
TF_EXPECT_OK(ParseHloString(original).status());
}
TEST_F(HloParserTest, InvalidDimLabels) {
string prefix = R"(HloModule invalid_dim_labels_module
ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2,1] {
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), window={size=1} )";
string suffix = R"(
}
)";
ExpectHasSubstr(
ParseHloString(absl::StrCat(prefix, ",dim_labels=00_01_10", suffix))
.status()
.error_message(),
"expects dim labels pattern");
ExpectHasSubstr(
ParseHloString(absl::StrCat(prefix, ",dim_labels=010_1100->010", suffix))
.status()
.error_message(),
"must have the same rank");
}
TEST_F(HloParserTest, UnexpectedAttribute) {
const string original = R"(HloModule unexpected_attr_module
ENTRY %TwoSendRecvBothWayRecvFist.v3 () -> f32[] {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
%recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
ROOT %constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, calls=%recv
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"unexpected attribute \"calls\"");
}
TEST_F(HloParserTest, MissingAttribute) {
const string original = R"(HloModule missing_attr_module
ENTRY %TwoSendRecvBothWayRecvFist.v3 () -> f32[] {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
%recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
ROOT %constant = f32[] constant(-2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0)
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"attribute channel_id is expected but not seen");
}
TEST_F(HloParserTest, PredecessorUndefined) {
const string original = R"(HloModule pre_not_found_module
ENTRY %TwoSendRecvBothWayRecvFist.v3 () -> f32[] {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
%recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
ROOT %constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%done}
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"'done' is not defined");
}
TEST_F(HloParserTest, SliceAllowOmitStride1) {
const string original = R"(HloModule slice_module
ENTRY %slice.v2 (p0: f32[3,3,4,4]) -> f32[3,3,2,4] {
%p0 = f32[3,3,4,4]{3,2,1,0} parameter(0)
ROOT %slice = f32[3,3,2,4]{3,2,1,0} slice(f32[3,3,4,4]{3,2,1,0} %p0), slice={[0:3], [0:3], [0:4:2], [0:4]}
}
)";
TF_EXPECT_OK(ParseHloString(original).status());
}
TEST_F(HloParserTest, PaddingConfigIsNotWindowPad) {
const string original = R"(HloModule window_pad_module
ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2,1] {
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), dim_labels=b0f_0io->b0f, window={pad=1_1_0 size=1}
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"expects padding_low and padding_high separated by '_'");
}
TEST_F(HloParserTest, CommaBetweenSubAttributes) {
const string original = R"(HloModule test_comma_module
ENTRY %test_comma.v4 () -> f32[] {
ROOT %constant = f32[] constant(-4.2), metadata={source_line=5, op_type="::const"}
}
)";
TF_EXPECT_OK(ParseHloString(original).status());
}
TEST_F(HloParserTest, ComputationShapeDoesNotMatchRootShape) {
const string original = R"(HloModule custom_call:
ENTRY %CustomCall () -> f32[1] {
%constant = f32[1]{0} constant({12345})
ROOT %foo = f32[1,2,3]{0,2,1} custom-call(f32[1]{0} %constant), custom_call_target="foo\"bar"
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Shape of computation CustomCall, f32[1], is not compatible "
"with that of its root instruction foo, f32[1,2,3]");
}
TEST_F(HloParserTest, EntryComputationWithLayout) {
const string original = R"(HloModule layout:
add_F32.v3 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %Reduce (input: f32[8,16,256]) -> f32[8,16] {
input = f32[8,16,256]{0,1,2} parameter(0)
constant = f32[] constant(0)
ROOT reduce = f32[8,16]{0,1} reduce(input, constant), dimensions={2}, to_apply=add_F32.v3
})";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
auto program_layout = module.ValueOrDie()->entry_computation_layout();
ASSERT_EQ(program_layout.parameter_count(), 1);
auto param_layout = program_layout.parameter_layout(0).layout();
auto result_layout = program_layout.result_layout().layout();
EXPECT_TRUE(
LayoutUtil::Equal(LayoutUtil::MakeLayout({0, 1, 2}), param_layout))
<< "actual layout of parameter(0) is "
<< LayoutUtil::HumanString(param_layout);
EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({0, 1}), result_layout))
<< "actual layout of result is "
<< LayoutUtil::HumanString(result_layout);
}
TEST_F(HloParserTest, NoEntry) {
const string original = R"(HloModule no_entry:
c1 {
const1 = f32[1]{0} constant({12345})
}
c2 {
const2 = f32[1]{0} constant({67890})
})";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
EXPECT_EQ(module.ValueOrDie()->entry_computation()->name(), "c2");
}
TEST_F(HloParserTest, NoRoot) {
const string original = R"(HloModule no_root:
ENTRY consts {
first = f32[1]{0} constant({12345})
last = f32[1]{0} constant({67890})
})";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
EXPECT_EQ(
module.ValueOrDie()->entry_computation()->root_instruction()->name(),
"last");
}
TEST_F(HloParserTest, Comments) {
const string original = R"(/* module description. */
HloModule comments:
ENTRY /*comment*/ c1 {
/* blah */
ROOT const1 = /*foo*/f32[1]{0} constant({12345 /*bar*/})
/* comment */
}
/* something else */
)";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
}
TEST_F(HloParserTest, MultilineComments) {
const string original = R"(HloModule multiline_comment:
ENTRY c1 {
/*
ROOT foo = f32[1]{0} constant({12345})
*/
ROOT const1 = f32[1]{0} constant({12345})
/*
a
b
c
d
*/
})";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
}
TEST_F(HloParserTest, UnterminatedComment) {
const string original = R"(HloModule unterminated_comment:
ENTRY c1 {
/* unterminated
ROOT const1 = f32[1]{0} constant({12345})
})";
// Verify that the error message points to the beginning of the unterminated
// comment.
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"/* unterminated\n^");
}
TEST_F(HloParserTest, SlashSlashComments) {
const string original = R"(HloModule slash_slash_comment:
// Garbage
ENTRY c1 {
// Foo bar
ROOT const1 = f32[1]{0} constant({12345}) // Something else
})";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
}
TEST_F(HloParserTest, SlashSlashCommentMsDosEolFormat) {
const string original =
"HloModule slash_slash_comment:\r\n// Garbage\r\nENTRY c1 {\r\n// Foo "
"bar\r\nROOT const1 = f32[1]{0} constant({12345}) // Something else\r\n}";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
}
TEST_F(HloParserTest, SlashSlashCommentMacEolFormat) {
const string original =
"HloModule slash_slash_comment:\r// Garbage\rENTRY c1 {\r// Foo "
"bar\rROOT const1 = f32[1]{0} constant({12345}) // Something else\r}";
auto module = ParseHloString(original);
TF_ASSERT_OK(module.status());
}
TEST_F(HloParserTest, MultipleEntries) {
const string original = R"(HloModule multiple_entries:
ENTRY c1 {
const1 = f32[1]{0} constant({12345})
}
ENTRY c2 {
const2 = f32[1]{0} constant({67890})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"expects only one ENTRY");
}
TEST_F(HloParserTest, MultipleRoots) {
const string original = R"(HloModule multiple_roots:
ENTRY consts {
ROOT const1 = f32[1]{0} constant({12345})
ROOT const2 = f32[1]{0} constant({12345})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"one computation should have only one ROOT");
}
TEST_F(HloParserTest, ComputationExists) {
const string original = R"(HloModule comp_exists
comp {
const1 = f32[1]{0} constant({12345})
}
comp {
const2 = f32[1]{0} constant({67890})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
R"(was parsing 2:1: error: computation previously defined here
comp {
^)");
}
TEST_F(HloParserTest, CrossComputationLookup) {
const string original = R"(HloModule cross_computation_lookup:
tcalla (a: (s32[], s32[])) -> (s32[], s32[]) {
ROOT aparam = (s32[], s32[]) parameter(0)
}
tcallb (b: (s32[], s32[])) -> s32[] {
rparam = (s32[], s32[]) parameter(0)
ROOT gte0 = s32[] get-tuple-element(aparam), index=0
}
ENTRY entry {
param = (s32[], s32[]) parameter(0)
call0 = (s32[], s32[]) call(param), to_apply=tcalla
ROOT call1 = s32[] call(param), to_apply=tcallb
})";
ExpectHasSubstr(
ParseHloString(original).status().error_message(),
"was parsing 8:39: error: instruction does not exist: aparam");
}
TEST_F(HloParserTest, SameNameDiffComputations) {
const string original = R"(HloModule same_names:
add {
p0 = f32[] parameter(0)
p1 = f32[] parameter(1)
ROOT result = f32[] add(p0, p1)
}
ENTRY ReduceR3ToR2 {
p0 = f32[8,16,256]{2,1,0} parameter(0)
p1 = f32[] constant(0)
ROOT result = f32[8,16]{1,0} reduce(p0, p1), dimensions={2}, to_apply=add
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(original));
ASSERT_NE(module->entry_computation(), nullptr);
EXPECT_THAT(module->entry_computation()->root_instruction(), op::Reduce());
}
TEST_F(HloParserTest, ParseSharding) {
const string original = "{maximal device=42}";
TF_ASSERT_OK_AND_ASSIGN(HloSharding sharding, ParseSharding(original));
EXPECT_EQ(sharding.ToString(), original);
}
TEST_F(HloParserTest, ParseWindow) {
Window original = window_util::MakeWindow({1, 2, 3});
TF_ASSERT_OK_AND_ASSIGN(Window parsed,
ParseWindow(window_util::ToString(original)))
EXPECT_EQ(window_util::ToString(original), window_util::ToString(parsed));
}
TEST_F(HloParserTest, ParseConvolutionDimensionNumbers) {
const string original = "b0f_0io->b0f";
TF_ASSERT_OK_AND_ASSIGN(ConvolutionDimensionNumbers dnums,
ParseConvolutionDimensionNumbers(original));
EXPECT_EQ(original, ConvolutionDimensionNumbersToString(dnums));
}
TEST_F(HloParserTest, ParseReplicaGroups) {
const string original = "{{0,1},{2,3}}";
TF_ASSERT_OK_AND_ASSIGN(std::vector<ReplicaGroup> replica_groups,
ParseReplicaGroupsOnly(original));
EXPECT_EQ(original, ReplicaGroupsToString(replica_groups));
}
TEST_F(HloParserTest, ParsePaddingConfigNoInteriorPadding) {
const string original = "0_1x2_3";
TF_ASSERT_OK_AND_ASSIGN(PaddingConfig dnums, ParsePaddingConfig(original));
EXPECT_EQ(original, PaddingConfigToString(dnums));
}
TEST_F(HloParserTest, ParsePaddingConfigInteriorPadding) {
const string original = "0_1_0x2_3_4";
TF_ASSERT_OK_AND_ASSIGN(PaddingConfig dnums, ParsePaddingConfig(original));
EXPECT_EQ(original, PaddingConfigToString(dnums));
}
TEST_F(HloParserTest, ParsePaddingConfigInteriorPaddingImplicitZeroDim) {
TF_ASSERT_OK_AND_ASSIGN(PaddingConfig dnums, ParsePaddingConfig("0_1x2_3_4"));
// The extra "_0" gets added to the canonical string because the other dim has
// interior padding.
EXPECT_EQ("0_1_0x2_3_4", PaddingConfigToString(dnums));
}
TEST_F(HloParserTest, NontupleInfeed) {
const string original = R"(HloModule nontuple_infeed:
ENTRY nontuple_infeed {
token0 = token[] after-all()
ROOT infeed = pred[] infeed(token0)
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"infeed must have a non-empty tuple shape");
}
TEST(HloParserSingleOpTest, SingleOp) {
const string text =
"%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, "
"f32[2,4]{1,0} %x)";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_THAT(computation->root_instruction(),
op::Multiply(op::Parameter(0), op::Parameter(1)));
}
TEST(HloParserSingleOpTest, SingleOpNoShapeProducesError) {
const string text = "multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)";
StatusOr<std::unique_ptr<HloModule>> module = ParseHloString(text);
ASSERT_TRUE(!module.status().ok());
LOG(INFO) << "Status: " << module.status();
EXPECT_THAT(module.status().ToString(),
::testing::HasSubstr("expects '=' in instruction"));
}
TEST(HloParserSingleOpTest, SingleOpNoOperandShapesProducesError) {
const string text = "%multiply = f32[2,4]{1,0} multiply(%broadcast, %x)";
StatusOr<std::unique_ptr<HloModule>> module = ParseHloString(text);
ASSERT_TRUE(!module.status().ok());
LOG(INFO) << "Status: " << module.status();
EXPECT_THAT(module.status().ToString(),
::testing::HasSubstr("Operand had no shape in HLO text"));
}
TEST(HloParserSingleOpTest, SingleOpNoNames) {
const string text =
"%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0}, f32[2,4]{1,0})";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_THAT(computation->root_instruction(),
op::Multiply(op::Parameter(0), op::Parameter(1)));
}
TEST(HloParserSingleOpTest, CanonicalOp) {
const string text = "f32[2,4]{1,0} multiply(f32[2,4]{1,0}, f32[2,4]{1,0})";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_THAT(computation->root_instruction(),
op::Multiply(op::Parameter(0), op::Parameter(1)));
EXPECT_EQ(
computation->root_instruction()->ToString(HloPrintOptions::Canonical()),
text);
}
TEST(HloParserSingleOpTest, CanonicalOpWithNested) {
const string text =
R"(f32[5,20]{1,0} while(f32[5,10]{1,0}), condition=
{
tmp_0 = f32[5,10]{1,0} parameter(0)
tmp_1 = f32[20,10]{1,0} parameter(1)
ROOT tmp_2 = f32[5,20]{1,0} fusion(f32[5,10]{1,0} tmp_0, f32[20,10]{1,0} tmp_1), kind=kLoop, calls=
{
tmp_0 = f32[5,10]{1,0} parameter(0)
tmp_1 = f32[20,10]{1,0} parameter(1)
tmp_2 = f32[10,20]{1,0} transpose(f32[20,10]{1,0} tmp_1), dimensions={1,0}
ROOT tmp_3 = f32[5,20]{1,0} dot(f32[5,10]{1,0} tmp_0, f32[10,20]{1,0} tmp_2), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
}, body=
{
tmp_0 = f32[5,10]{1,0} parameter(0)
tmp_1 = f32[20,10]{1,0} parameter(1)
ROOT tmp_2 = f32[5,20]{1,0} fusion(f32[5,10]{1,0} tmp_0, f32[20,10]{1,0} tmp_1), kind=kLoop, calls=
{
tmp_0 = f32[5,10]{1,0} parameter(0)
tmp_1 = f32[20,10]{1,0} parameter(1)
tmp_2 = f32[10,20]{1,0} transpose(f32[20,10]{1,0} tmp_1), dimensions={1,0}
ROOT tmp_3 = f32[5,20]{1,0} dot(f32[5,10]{1,0} tmp_0, f32[10,20]{1,0} tmp_2), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_EQ(
computation->root_instruction()->ToString(HloPrintOptions::Canonical()),
text);
}
TEST(HloParserSingleOpTest, CanonicalOpIndexedConditionalInlinedBranches) {
const string text =
R"(f32[5,10]{1,0} conditional(s32[], f32[5,10]{1,0}, f32[5,10]{1,0}, f32[5,10]{1,0}), branch_computations={
{
tmp_0 = f32[5,10]{1,0} parameter(0)
ROOT tmp_1 = f32[5,10]{1,0} ceil(f32[5,10]{1,0} tmp_0)
},
{
tmp_0 = f32[5,10]{1,0} parameter(0)
ROOT tmp_1 = f32[5,10]{1,0} floor(f32[5,10]{1,0} tmp_0)
},
{
tmp_0 = f32[5,10]{1,0} parameter(0)
ROOT tmp_1 = f32[5,10]{1,0} copy(f32[5,10]{1,0} tmp_0)
}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_EQ(
computation->root_instruction()->ToString(HloPrintOptions::Canonical()),
text);
}
TEST(HloParserSingleOpTest, SingleOpWithNested) {
const string text =
R"(%fusion = f32[3,2,1,1]{3,2,1,0} fusion(f32[3,2,1,1]{3,2,1,0} %p0, f32[2]{0} %p1), kind=kLoop, calls=
{
%param_0 = f32[3,2,1,1]{3,2,1,0} parameter(0)
%param_1 = f32[2]{0} parameter(1)
%broadcast = f32[3,2,1,1]{3,2,1,0} broadcast(f32[2]{0} %param_1), dimensions={1}
ROOT %subtract = f32[3,2,1,1]{3,2,1,0} subtract(f32[3,2,1,1]{3,2,1,0} %param_0, f32[3,2,1,1]{3,2,1,0} %broadcast)
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_THAT(computation->root_instruction(),
op::Fusion(op::Parameter(0), op::Parameter(1)));
}
TEST(HloParserSingleOpTest, SingleOpWithNested_DoesNotExist) {
const string text =
R"(reduce = f32[] reduce(f32[10], f32[]), dimensions={1}, to_apply=
{
result = f32[] add(f32[] x, f32[] y)
})";
auto status = ParseHloString(text).status();
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.error_message(),
::testing::HasSubstr("does not exist: x"));
}
TEST(HloParserSingleOpTest, SingleOpWithNested_NoLhs) {
const string text =
R"(reduce = f32[] reduce(f32[10], f32[]), dimensions={1}, to_apply=
{
f32[] add(f32[] x, f32[] y)
})";
auto status = ParseHloString(text).status();
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.error_message(), ::testing::HasSubstr("expects name"));
}
TEST(HloParserSingleOpTest, SingleOpWithNested_NoOperandName) {
const string text =
R"(reduce = f32[] reduce(f32[10], f32[]), dimensions={1}, to_apply=
{
result = f32[] add(f32[], f32[])
})";
auto status = ParseHloString(text).status();
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.error_message(), ::testing::HasSubstr("expects name"));
}
TEST(HloParserSingleOpTest, ConvolutionTrivialFeatureGroupCount) {
const string text =
R"(%convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f)";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(text));
const HloComputation* computation = module->entry_computation();
ASSERT_NE(computation, nullptr);
EXPECT_THAT(computation->root_instruction(),
op::Convolution(op::Parameter(0), op::Parameter(1)));
auto* convolution =
Cast<HloConvolutionInstruction>(computation->root_instruction());
EXPECT_EQ(convolution->feature_group_count(), 1);
}
TEST_F(HloParserTest, IsScheduledIsFalse) {
const string text = R"(
HloModule axpy_module, is_scheduled=false
ENTRY %axpy.v5 (alpha: f32[], x: f32[2,4], y: f32[2,4]) -> f32[2,4] {
%alpha = f32[] parameter(0)
%broadcast = f32[2,4]{1,0} broadcast(f32[] %alpha), dimensions={}
%x = f32[2,4]{1,0} parameter(1)
%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)
%y = f32[2,4]{1,0} parameter(2)
ROOT %add = f32[2,4]{1,0} add(f32[2,4]{1,0} %multiply, f32[2,4]{1,0} %y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(text));
ASSERT_FALSE(module->has_schedule());
}
TEST_F(HloParserTest, IsScheduledNotPresent) {
const string text = R"(
HloModule axpy_module
ENTRY %axpy.v5 (alpha: f32[], x: f32[2,4], y: f32[2,4]) -> f32[2,4] {
%alpha = f32[] parameter(0)
%broadcast = f32[2,4]{1,0} broadcast(f32[] %alpha), dimensions={}
%x = f32[2,4]{1,0} parameter(1)
%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)
%y = f32[2,4]{1,0} parameter(2)
ROOT %add = f32[2,4]{1,0} add(f32[2,4]{1,0} %multiply, f32[2,4]{1,0} %y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(text));
ASSERT_FALSE(module->has_schedule());
}
TEST_F(HloParserTest, IsScheduledIsTrue) {
const string text = R"(
HloModule axpy_module, is_scheduled=true
ENTRY %axpy.v5 (alpha: f32[], x: f32[2,4], y: f32[2,4]) -> f32[2,4] {
%alpha = f32[] parameter(0)
%broadcast = f32[2,4]{1,0} broadcast(f32[] %alpha), dimensions={}
%x = f32[2,4]{1,0} parameter(1)
%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)
%y = f32[2,4]{1,0} parameter(2)
ROOT %add = f32[2,4]{1,0} add(f32[2,4]{1,0} %multiply, f32[2,4]{1,0} %y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(text));
ASSERT_TRUE(module->has_schedule());
TF_ASSERT_OK(module->schedule().Verify());
EXPECT_EQ(module->schedule().sequences().size(), 1);
ASSERT_TRUE(
module->schedule().is_computation_scheduled(module->entry_computation()));
EXPECT_THAT(
module->schedule().sequence(module->entry_computation()).instructions(),
::testing::ElementsAre(op::Parameter(), op::Broadcast(), op::Parameter(),
op::Multiply(), op::Parameter(), op::Add()));
}
TEST_F(HloParserTest, IsScheduledIsTrueDifferentOrder) {
// As above but in with a different schedule order.
const string text = R"(
HloModule axpy_module, is_scheduled=true
ENTRY %axpy.v5 (alpha: f32[], x: f32[2,4], y: f32[2,4]) -> f32[2,4] {
%alpha = f32[] parameter(0)
%x = f32[2,4]{1,0} parameter(1)
%y = f32[2,4]{1,0} parameter(2)
%broadcast = f32[2,4]{1,0} broadcast(f32[] %alpha), dimensions={}
%multiply = f32[2,4]{1,0} multiply(f32[2,4]{1,0} %broadcast, f32[2,4]{1,0} %x)
ROOT %add = f32[2,4]{1,0} add(f32[2,4]{1,0} %multiply, f32[2,4]{1,0} %y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(text));
ASSERT_TRUE(module->has_schedule());
TF_ASSERT_OK(module->schedule().Verify());
EXPECT_EQ(module->schedule().sequences().size(), 1);
ASSERT_TRUE(
module->schedule().is_computation_scheduled(module->entry_computation()));
EXPECT_THAT(
module->schedule().sequence(module->entry_computation()).instructions(),
::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Parameter(),
op::Broadcast(), op::Multiply(), op::Add()));
}
TEST_F(HloParserTest, CustomCallWrongNumberofOperandConstraints) {
const string original = R"(HloModule CustomCallWrongNumberofOperandConstraints
ENTRY %CustomCallWrongNumberofOperandConstraints (p0: f32[42,2,3], p1: f32[123,4]) -> f32[1,2,3] {
%p0 = f32[42,2,3]{0,1,2} parameter(0)
%p1 = f32[123,4]{0,1} parameter(1)
ROOT %custom-call = f32[1,2,3]{0,1,2} custom-call(f32[42,2,3]{0,1,2} %p0, f32[123,4]{0,1} %p1), custom_call_target="baz", operand_layout_constraints={f32[42,2,3]{0,1,2}}
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Expected 2 operand layout constraints, 1 given");
}
TEST_F(HloParserTest, CustomCallIncompatibleOperandConstraints) {
const string original = R"(HloModule CustomCallIncompatibleOperandConstraints
ENTRY %CustomCallIncompatibleOperandConstraints (p0: f32[42,2,3], p1: f32[123,4]) -> f32[1,2,3] {
%p0 = f32[42,2,3]{0,1,2} parameter(0)
%p1 = f32[123,4]{0,1} parameter(1)
ROOT %custom-call = f32[1,2,3]{0,1,2} custom-call(f32[42,2,3]{0,1,2} %p0, f32[123,4]{0,1} %p1), custom_call_target="baz", operand_layout_constraints={f32[42,2,3]{0,1,2}, f32[555,5]{1,0}}
}
)";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"operand 1 is not compatible with operand shape");
}
TEST_F(HloParserTest, AllowShapeWhitespace) {
const string text = R"(
HloModule module
ENTRY entry {
ROOT root = f32[ 1, 2,3, 4, 5]{0, 1, 2,3, 4 } parameter(0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseHloString(text));
}
TEST_F(HloParserTest, ShapeMismatchInOperand) {
const string text = R"(
HloModule foobar
ENTRY %entrycomp (p: f32[2,2]) -> f32[2,2] {
%p = f32[2,2] parameter(0)
%constant.1 = f32[2,2] constant({{1, 2}, {3, 4}})
ROOT %add.1 = f32[2,2] add(f32[2,2] %p, f32[2,5] %constant.1)
}
)";
ExpectHasSubstr(ParseHloString(text).status().error_message(),
"The declared operand shape f32[2,5]{1,0} is not compatible"
" with the shape of the operand instruction f32[2,2]{1,0}.");
}
TEST_F(HloParserTest, OutOfRangeSparseIndex) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f16[5]sparse{10} constant({[100]: 0})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Invalid sparse index");
}
TEST_F(HloParserTest, NegativeSparseIndex) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f16[5]sparse{10} constant({-1: 0})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Invalid sparse index");
}
TEST_F(HloParserTest, SparseIndexWithRankTooLarge) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f16[5]sparse{10} constant({[0, 0]: 0})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Invalid sparse index");
}
TEST_F(HloParserTest, SparseIndexWithRankTooSmall) {
const string original = R"(
HloModule test_module
ENTRY test {
ROOT c = f16[5, 5]sparse{10} constant({[0]: 0})
})";
ExpectHasSubstr(ParseHloString(original).status().error_message(),
"Invalid sparse index");
}
TEST_F(HloParserTest, ParseShapeStringR2F32) {
string shape_string = "f32[123,456]";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeShape(F32, {123, 456});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseShapeStringTupleOfArrays) {
string shape_string = "(f32[1572864],s8[5120,1024])";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected =
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {1572864}),
ShapeUtil::MakeShape(S8, {5120, 1024})});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseShapeStringNestedTuple) {
string shape_string = "(f32[1],(f32[2], token[]), opaque[], f32[3])";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeTupleShape({
ShapeUtil::MakeShape(F32, {1}),
ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {2}), ShapeUtil::MakeTokenShape()}),
ShapeUtil::MakeOpaqueShape(),
ShapeUtil::MakeShape(F32, {3}),
});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseShapeStringWithLayout) {
string shape_string = "f32[123,456]{0,1}";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeShapeWithLayout(F32, {123, 456}, {0, 1});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseShapeStringWithTilingLayout) {
// One tile.
string shape_string = "f32[123,456]{0,1:T(2,128)}";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected =
ShapeUtil::MakeShapeWithLayout(F32, {123, 456}, {0, 1}, {Tile({2, 128})});
EXPECT_EQ(expected, actual)
<< "expected: " << ShapeUtil::HumanStringWithLayout(expected)
<< "actual: " << ShapeUtil::HumanStringWithLayout(actual);
// Tile with negative dimension size for combining dimensions.
shape_string = "f32[123,456,789]{0,1,2:T(2, * , 128)}";
TF_ASSERT_OK_AND_ASSIGN(actual, ParseShape(shape_string));
expected =
ShapeUtil::MakeShapeWithLayout(F32, {123, 456, 789}, {0, 1, 2},
{Tile({2, Tile::kCombineDimension, 128})});
EXPECT_EQ(expected, actual)
<< "expected: " << ShapeUtil::HumanStringWithLayout(expected)
<< "actual: " << ShapeUtil::HumanStringWithLayout(actual);
// Two tiles.
shape_string = "bf16[123,456,789]{2,1,0:T(2,*,128)(2,1)}";
TF_ASSERT_OK_AND_ASSIGN(actual, ParseShape(shape_string));
expected = ShapeUtil::MakeShapeWithLayout(
BF16, {123, 456, 789}, {2, 1, 0},
{Tile({2, Tile::kCombineDimension, 128}), Tile({2, 1})});
EXPECT_EQ(expected, actual)
<< "expected: " << ShapeUtil::HumanStringWithLayout(expected)
<< "actual: " << ShapeUtil::HumanStringWithLayout(actual);
// Tile with element size in bits.
shape_string = "pred[123,456]{1,0:T(2,128)E(1)}";
TF_ASSERT_OK_AND_ASSIGN(actual, ParseShape(shape_string));
expected = ShapeUtil::MakeShapeWithLayout(PRED, {123, 456}, {1, 0},
{Tile({2, 128})}, 1);
EXPECT_EQ(expected, actual)
<< "expected: " << ShapeUtil::HumanStringWithLayout(expected)
<< "actual: " << ShapeUtil::HumanStringWithLayout(actual);
// Element size in bits without tile.
shape_string = "pred[123,456]{1,0:E(1)}";
TF_ASSERT_OK_AND_ASSIGN(actual, ParseShape(shape_string));
expected = ShapeUtil::MakeShapeWithLayout(PRED, {123, 456}, {1, 0}, {}, 1);
EXPECT_EQ(expected, actual)
<< "expected: " << ShapeUtil::HumanStringWithLayout(expected)
<< "actual: " << ShapeUtil::HumanStringWithLayout(actual);
// Wrong minor_to_major.
shape_string = "f32[123,456,789]{1:T(2, * , 128)}";
auto result = ParseShape(shape_string);
ExpectHasSubstr(result.status().error_message(),
"Dimensions size is 3, but minor to major size is 1.");
}
TEST_F(HloParserTest, ParseShapeStringWithSparseLayout) {
string shape_string = "f32[123,456]sparse{10}";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeShapeWithSparseLayout(F32, {123, 456}, 10);
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseOpaqueType) {
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape("opaque[]"));
Shape expected = ShapeUtil::MakeOpaqueShape();
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseTokenType) {
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape("token[]"));
Shape expected = ShapeUtil::MakeTokenShape();
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseInvalidShapeString) {
string shape_strings[] = {
"f32[123,456]foobar{0,1}", "f32[123,456]sparse{0,1}", "f32[123,456]{foo}",
"f32[123,456]dense{foo}", "f32[123,456]sparse{foo}",
};
for (const string& shape_string : shape_strings) {
StatusOr<Shape> result = ParseShape(shape_string);
ASSERT_FALSE(result.ok()) << "shape: " << shape_string;
}
}
TEST_F(HloParserTest, ParseDynamicArray) {
string shape_string = "f32[123,<=456]";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeShape(F32, {123, 456}, {false, true});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, ParseDynamicTuple) {
string shape_string = "(f32[42], u32[<=123,<=456])";
TF_ASSERT_OK_AND_ASSIGN(Shape actual, ParseShape(shape_string));
Shape expected = ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {42}),
ShapeUtil::MakeShape(U32, {123, 456}, {true, true})});
ASSERT_TRUE(ShapeUtil::Equal(expected, actual))
<< "expected: " << ShapeUtil::HumanString(expected)
<< "actual: " << ShapeUtil::HumanString(actual);
}
TEST_F(HloParserTest, NegativeParameterNumber) {
const string hlo_string = "par0 = f32[3,5] parameter(-1)";
auto result = ParseHloString(hlo_string);
ASSERT_FALSE(result.status().ok());
EXPECT_THAT(result.status().error_message(),
::testing::HasSubstr("parameter number must be >= 0"));
}
TEST_F(HloParserTest, WrongNumberOfParameterLeafBuffersInReplication) {
const string hlo_string =
"par0 = (f32[3,5], f32[]) parameter(0), "
"parameter_replication={true,false,true}";
auto result = ParseHloString(hlo_string);
ASSERT_FALSE(result.status().ok());
EXPECT_THAT(result.status().error_message(),
::testing::HasSubstr("parameter has 2 leaf buffers, but "
"parameter_replication has 3 elements"));
}
} // namespace
} // namespace xla
|
; A129296: Number of divisors of n^2 - 1 that are not greater than n.
; 1,1,2,2,4,2,5,3,5,3,8,2,8,4,6,4,9,2,12,4,8,4,10,3,10,6,8,4,16,2,14,4,7,8,12,4,12,4,10,4,20,2,16,6,8,6,12,3,18,6,12,4,16,4,20,8,10,4,16,2,16,6,8,12,16,4,16,4,16,4,30,2,15,6,8,12,16,4,24,5,12,5,16,4,16,8,10,4,30,4,24,8,8,8,14,4,21,6,18,6
add $0,1
pow $0,2
trn $0,3
mov $1,$0
add $0,1
seq $0,94820 ; Partial sums of A038548.
seq $1,94820 ; Partial sums of A038548.
sub $0,$1
|
; A152891: a(1) = b(1) = 0; for n > 1, b(n) = b(n-1) + n-1 + a(n-1) and a(n) = a(n-1) + n-1 + b(n).
; 0,2,9,29,83,226,602,1588,4171,10935,28645,75012,196404,514214,1346253,3524561,9227447,24157798,63245966,165580120,433494415,1134903147,2971215049,7778742024,20365011048,53316291146,139583862417,365435296133,956722026011,2504730781930,6557470319810,17167680177532,44945570212819,117669030460959,308061521170093,806515533049356,2111485077978012,5527939700884718
lpb $0,1
sub $0,1
add $3,1
add $2,$3
add $3,$2
add $1,$3
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r8
push %r9
push %rax
push %rdi
lea addresses_UC_ht+0x10ffb, %r13
clflush (%r13)
nop
nop
nop
nop
nop
add $14873, %r8
vmovups (%r13), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %rdi
and $4730, %rdi
lea addresses_normal_ht+0x1764b, %rax
nop
nop
nop
nop
nop
sub $28894, %r9
movb (%rax), %r15b
xor $17447, %rax
pop %rdi
pop %rax
pop %r9
pop %r8
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %r8
push %rbx
push %rdi
push %rdx
// Faulty Load
lea addresses_RW+0x33fb, %rdx
nop
sub $2377, %r14
movb (%rdx), %r8b
lea oracles, %rdi
and $0xff, %r8
shlq $12, %r8
mov (%rdi,%r8,1), %r8
pop %rdx
pop %rdi
pop %rbx
pop %r8
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}}
{'32': 12372}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
ld, F1, 0(R10)
mult.d, F2, F1, F5
sd, F2, 8(R0)
ld, F3, 8(R0)
ld, F4, 4(R10)
ld, F5, 8(R0)
|
xor r0,r0,r0
ldl $8000
and r7,r7,r1
ldl $8002
and r7,r7,r2
ldl $72
store r0,r2,r7
ldl $1
store r0,r1,r4
ldl $101
store r0,r2,r7
ldl $2
store r0,r1,r4
ldl $108
store r0,r2,r7
ldl $3
store r0,r1,r4
ldl $108
store r0,r2,r7
ldl $4
store r0,r1,r4
ldl $111
store r0,r2,r7
ldl $5
store r0,r1,r4
ldl $44
store r0,r2,r7
ldl $6
store r0,r1,r4
ldl $32
store r0,r2,r7
ldl $7
store r0,r1,r4
ldl $119
store r0,r2,r7
ldl $8
store r0,r1,r4
ldl $111
store r0,r2,r7
ldl $9
store r0,r1,r4
hlt
|
.code
ClearBreakpoints proc
invoke RtlZeroMemory,offset breakpoint,sizeof breakpoint
invoke RtlZeroMemory,offset szBPSourceName,sizeof szBPSourceName
ret
ClearBreakpoints endp
AddBreakpoint proc uses ebx esi,nLine:DWORD,lpFileName:DWORD
mov esi,offset szBPSourceName
mov ebx,0
.while byte ptr [esi]
invoke strcmpi,esi,lpFileName
.break .if !eax
inc ebx
lea esi,[esi+MAX_PATH]
.endw
.if !byte ptr [esi]
invoke strcpy,esi,lpFileName
.endif
mov esi,offset breakpoint
.while [esi].BREAKPOINT.LineNumber
lea esi,[esi+sizeof BREAKPOINT]
.endw
mov [esi].BREAKPOINT.FileID,ebx
mov eax,nLine
mov [esi].BREAKPOINT.LineNumber,eax
ret
AddBreakpoint endp
MapBreakPoints proc uses ebx esi edi
LOCAL CountBP:DWORD
LOCAL CountSource:DWORD
LOCAL Unhandled:DWORD
mov esi,dbg.hMemLine
xor ecx,ecx
.while ecx<dbg.inxline
mov [esi].DEBUGLINE.BreakPoint,FALSE
inc ecx
add esi,sizeof DEBUGLINE
.endw
mov Unhandled,0
mov CountBP,512
mov esi,offset breakpoint
.while CountBP
mov eax,[esi].BREAKPOINT.LineNumber
.if eax
push esi
call MatchIt
pop esi
.endif
dec CountBP
add esi,sizeof BREAKPOINT
.endw
mov eax,Unhandled
ret
MatchIt:
mov eax,[esi].BREAKPOINT.FileID
mov edx,MAX_PATH
mul edx
mov edi,offset szBPSourceName
lea edi,[edi+eax]
mov eax,dbg.inxsource
mov CountSource,eax
mov ebx,dbg.hMemSource
.while CountSource
invoke strcmpi,edi,addr [ebx].DEBUGSOURCE.FileName
.if !eax
mov edx,[ebx].DEBUGSOURCE.FileID
mov eax,[esi].BREAKPOINT.LineNumber
mov esi,dbg.hMemLine
inc Unhandled
xor ecx,ecx
.while ecx<dbg.inxline
.if eax==[esi].DEBUGLINE.LineNumber
.if dx==[esi].DEBUGLINE.FileID
mov [esi].DEBUGLINE.BreakPoint,TRUE
mov [esi].DEBUGLINE.NoDebug,0
dec Unhandled
.break
.endif
.endif
inc ecx
add esi,sizeof DEBUGLINE
.endw
.break
.endif
dec CountSource
add ebx,sizeof DEBUGSOURCE
.endw
retn
MapBreakPoints endp
SetBreakPointsAll proc
mov edx,dbg.minadr
mov ecx,dbg.maxadr
sub ecx,edx
invoke WriteProcessMemory,dbg.hdbghand,edx,dbg.hMemBP,ecx,0
ret
SetBreakPointsAll endp
SetBreakPoints proc uses ebx edi
mov edi,dbg.hMemLine
mov ebx,dbg.inxline
.while ebx
.if [edi].DEBUGLINE.BreakPoint && ![edi].DEBUGLINE.NoDebug
invoke WriteProcessMemory,dbg.hdbghand,[edi].DEBUGLINE.Address,addr szBP,1,0
.endif
lea edi,[edi+sizeof DEBUGLINE]
dec ebx
.endw
ret
SetBreakPoints endp
IsLineCode proc uses ebx esi edi,nLine:DWORD,lpFileName:DWORD
mov edi,dbg.inxsource
mov ebx,dbg.hMemSource
.while edi
invoke strcmpi,lpFileName,addr [ebx].DEBUGSOURCE.FileName
.if !eax
mov edx,[ebx].DEBUGSOURCE.FileID
mov eax,nLine
mov esi,dbg.hMemLine
xor ecx,ecx
.while ecx<dbg.inxline
.if eax==[esi].DEBUGLINE.LineNumber
.if dx==[esi].DEBUGLINE.FileID
mov eax,TRUE
jmp Ex
.endif
.endif
inc ecx
add esi,sizeof DEBUGLINE
.endw
.break
.endif
dec edi
lea ebx,[ebx+sizeof DEBUGSOURCE]
.endw
xor eax,eax
Ex:
ret
IsLineCode endp
SetBreakpointAtCurrentLine proc uses ebx esi edi,nLine:DWORD,lpFileName:DWORD
mov edi,dbg.inxsource
mov ebx,dbg.hMemSource
.while edi
invoke strcmpi,lpFileName,addr [ebx].DEBUGSOURCE.FileName
.if !eax
mov edx,[ebx].DEBUGSOURCE.FileID
mov eax,nLine
mov esi,dbg.hMemLine
xor ecx,ecx
.while ecx<dbg.inxline
.if eax==[esi].DEBUGLINE.LineNumber
.if dx==[esi].DEBUGLINE.FileID
invoke WriteProcessMemory,dbg.hdbghand,[esi].DEBUGLINE.Address,addr szBP,1,0
jmp Ex
.endif
.endif
inc ecx
add esi,sizeof DEBUGLINE
.endw
.break
.endif
dec edi
lea ebx,[ebx+sizeof DEBUGSOURCE]
.endw
Ex:
ret
SetBreakpointAtCurrentLine endp
ClearBreakPointsAll proc
mov edx,dbg.minadr
mov ecx,dbg.maxadr
sub ecx,edx
invoke WriteProcessMemory,dbg.hdbghand,edx,dbg.hMemNoBP,ecx,0
ret
ClearBreakPointsAll endp
MapNoDebug proc uses ebx esi edi
LOCAL buffer[256]:BYTE
LOCAL buffer1[8]:BYTE
LOCAL nInx:DWORD
mov edi,dbg.hMemSymbol
mov ebx,dbg.inxsymbol
xor eax,eax
.while ebx
mov [edi].DEBUGSYMBOL.NoDebug,ax
dec ebx
add edi,sizeof DEBUGSYMBOL
.endw
mov ecx,dbg.inxline
mov esi,dbg.hMemLine
.while ecx
mov [esi].DEBUGLINE.NoDebug,al
dec ecx
lea esi,[esi+sizeof DEBUGLINE]
.endw
; Do not debug the proc line
mov esi,dbg.hMemSymbol
mov ecx,dbg.inxsymbol
.while ecx
.if [esi].DEBUGSYMBOL.nType=='p'
push ecx
invoke FindWord,addr [esi].DEBUGSYMBOL.szName,addr szPrpp
.if eax
mov edi,eax
; Point to parameters
invoke strlen,edi
lea edi,[edi+eax+1]
movzx eax,byte ptr [edi]
.if !eax
; Point to return type
invoke strlen,edi
lea edi,[edi+eax+1]
; Point to locals
invoke strlen,edi
lea edi,[edi+eax+1]
movzx eax,byte ptr [edi]
.endif
.if eax
mov eax,[esi].DEBUGSYMBOL.Address
mov ebx,dbg.inxline
mov edi,dbg.hMemLine
.while ebx
.if eax==[edi].DEBUGLINE.Address
mov [edi].DEBUGLINE.NoDebug,TRUE
.break
.endif
dec ebx
lea edi,[edi+sizeof DEBUGLINE]
.endw
.endif
.endif
pop ecx
.endif
dec ecx
lea esi,[esi+sizeof DEBUGSYMBOL]
.endw
; Map procs that sould not be debugged
mov esi,lpNoDebug
.while TRUE
.break .if !byte ptr [esi]
mov edi,dbg.hMemSymbol
mov ebx,dbg.inxsymbol
.while ebx
invoke strcmp,esi,addr [edi].DEBUGSYMBOL.szName
.if !eax
mov [edi].DEBUGSYMBOL.NoDebug,1
mov edx,[edi].DEBUGSYMBOL.Address
mov eax,edx
add edx,[edi].DEBUGSYMBOL.nSize
mov ecx,dbg.inxline
push esi
mov esi,dbg.hMemLine
.while ecx
.if [esi].DEBUGLINE.Address>=eax
.if [esi].DEBUGLINE.Address<edx
mov [esi].DEBUGLINE.NoDebug,1
.endif
.endif
dec ecx
lea esi,[esi+sizeof DEBUGLINE]
.endw
pop esi
.endif
dec ebx
lea edi,[edi+sizeof DEBUGSYMBOL]
.endw
invoke strlen,esi
lea esi,[esi+eax+1]
.endw
ret
MapNoDebug endp
|
// File implement/oglplus/enums/tess_gen_primitive_type_def.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/tess_gen_primitive_type.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
#if defined GL_QUADS
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined Quads
# pragma push_macro("Quads")
# undef Quads
OGLPLUS_ENUM_CLASS_VALUE(Quads, GL_QUADS)
# pragma pop_macro("Quads")
# else
OGLPLUS_ENUM_CLASS_VALUE(Quads, GL_QUADS)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_TRIANGLES
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined Triangles
# pragma push_macro("Triangles")
# undef Triangles
OGLPLUS_ENUM_CLASS_VALUE(Triangles, GL_TRIANGLES)
# pragma pop_macro("Triangles")
# else
OGLPLUS_ENUM_CLASS_VALUE(Triangles, GL_TRIANGLES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_ISOLINES
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined Isolines
# pragma push_macro("Isolines")
# undef Isolines
OGLPLUS_ENUM_CLASS_VALUE(Isolines, GL_ISOLINES)
# pragma pop_macro("Isolines")
# else
OGLPLUS_ENUM_CLASS_VALUE(Isolines, GL_ISOLINES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
|
#include <gtest/gtest.h>
#include <iostream>
#include <leetcode/anyorder.hpp>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
/**
* This file is generated by leetcode_add.py v1.0
*
* 187.
* Repeated DNA Sequences
*
* ––––––––––––––––––––––––––––– Description –––––––––––––––––––––––––––––
*
* The “DNA sequence” is composed of a series of nucleotides abbreviated
* as ‘'A'’ , ‘'C'’ , ‘'G'’ , and ‘'T'’
* - For example, ‘'ACGAATTCCG'’ is a “DNA sequence”
* When studying “DNA” , it is useful to identify repeated sequences
* within the
* Given a string ‘s’ that represents a “DNA sequence” , return all the “
* ‘10’ -letter-long” sequences (substrings) that occur more than once in
* a DNA molecule. You may return the answer in “any order” .
*
* ––––––––––––––––––––––––––––– Constraints –––––––––––––––––––––––––––––
*
* • ‘1 ≤ s.length ≤ 10⁵’
* • ‘s[i]’ is either ‘'A'’ , ‘'C'’ , ‘'G'’ , or ‘'T'’ .
*
*/
struct q187 : public ::testing::Test {
// Leetcode answer here
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
unordered_map<string, int> keep;
vector<string> res;
for (int i = 0; i < (int)s.size() - 10 + 1; ++i) {
++keep[s.substr(i, 10)];
}
for (auto it = keep.begin(); it != keep.end(); ++it) {
if (it->second > 1) res.push_back(it->first);
}
return res;
}
};
class Solution *solution;
};
TEST_F(q187, sample_input01) {
solution = new Solution();
string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT";
vector<string> exp = {"AAAAACCCCC", "CCCCCAAAAA"};
// Try EXPECT_EQ_ANY_ORDER_RECURSIVE
// if the element is also matched in any order.
EXPECT_EQ_ANY_ORDER(solution->findRepeatedDnaSequences(s), exp);
delete solution;
}
TEST_F(q187, sample_input02) {
solution = new Solution();
string s = "AAAAAAAAAAAAA";
vector<string> exp = {"AAAAAAAAAA"};
// Try EXPECT_EQ_ANY_ORDER_RECURSIVE
// if the element is also matched in any order.
EXPECT_EQ_ANY_ORDER(solution->findRepeatedDnaSequences(s), exp);
delete solution;
}
|
;
;
; Copyright (c) 2018 by blindtiger. All rights reserved.
;
; The contents of this file are subject to the Mozilla Public License Version
; 2.0 (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; http://www.mozilla.org/MPL/
;
; Software distributed under the License is distributed on an "AS IS" basis,
; WITHOUT WARRANTY OF ANY KIND, either express or implied. SEe the License
; for the specific language governing rights and limitations under the
; License.
;
; The Initial Developer of the Original e is blindtiger.
;
;
.386p
.model flat, stdcall
.xlist
include callconv.inc
.list
_TEXT$00 SEGMENT PAGE 'CODE'
_TEXT$00 ends
end
|
object_const_def ; object_event constants
CanalaveEastGate_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
CanalaveEastGate_MapEvents:
db 0, 0 ; filler
db 2 ; warp events
warp_event 9, 4, ROUTE_218, 3
warp_event 9, 5, ROUTE_218, 4
db 0 ; coord events
db 0 ; bg events
db 0 ; object events
|
// Test a procedure with calling convention stack - and enough parameters to use fast ASM for cleaning stack
// Commodore 64 PRG executable file
.file [name="procedure-callingconvention-stack-2.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.const STACK_BASE = $103
.label SCREEN = $400
.segment Code
// __zp(2) unsigned int plus(__zp(2) unsigned int a, __zp(4) unsigned int b)
plus: {
.const OFFSET_STACK_A = 2
.const OFFSET_STACK_B = 0
.const OFFSET_STACK_RETURN_2 = 2
.label a = 2
.label b = 4
.label return = 2
tsx
lda STACK_BASE+OFFSET_STACK_A,x
sta.z a
lda STACK_BASE+OFFSET_STACK_A+1,x
sta.z a+1
tsx
lda STACK_BASE+OFFSET_STACK_B,x
sta.z b
lda STACK_BASE+OFFSET_STACK_B+1,x
sta.z b+1
// return a+b;
clc
lda.z return
adc.z b
sta.z return
lda.z return+1
adc.z b+1
sta.z return+1
// }
tsx
lda.z return
sta STACK_BASE+OFFSET_STACK_RETURN_2,x
lda.z return+1
sta STACK_BASE+OFFSET_STACK_RETURN_2+1,x
rts
}
main: {
.label __0 = 2
// plus(0x1234, 0x2345)
lda #>$1234
pha
lda #<$1234
pha
lda #>$2345
pha
lda #<$2345
pha
jsr plus
pla
pla
pla
sta.z __0
pla
sta.z __0+1
// SCREEN[0] = plus(0x1234, 0x2345)
lda.z __0
sta SCREEN
lda.z __0+1
sta SCREEN+1
// }
rts
}
|
; A125518: a(n) = tau(n) * prime(n).
; 2,6,10,21,22,52,34,76,69,116,62,222,82,172,188,265,118,366,134,426,292,316,166,712,291,404,412,642,218,904,254,786,548,556,596,1359,314,652,668,1384,358,1448,382,1158,1182,796,422,2230,681,1374,932,1434,482,2008,1028,2104,1076,1084,554,3372,566,1172,1842,2177,1252,2536,662,2022,1388,2792,706,4308,734,1492,2274,2298,1556,3176,802,4090,2095,1684,862,5196,1756,1772,1796,3656,922,5556,1868,2874,1948,1964,1996,6036,1018,3126,3138,4869
mov $1,$0
seq $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n.
seq $1,40 ; The prime numbers.
mul $0,$1
|
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int add;
while (add != 0)
{
cout << "int: ";
cin >> add;
sum += add;
}
cout << sum;
cout << "\n\n\nhelp my mechanical mind.";
return 0;
}
|
// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "util.h"
#include "test/test_youlike.h"
#include "test/test_random.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#define SKIPLIST_LENGTH 300000
BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(skiplist_test)
{
std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH);
for (int i=0; i<SKIPLIST_LENGTH; i++) {
vIndex[i].nHeight = i;
vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1];
vIndex[i].BuildSkip();
}
for (int i=0; i<SKIPLIST_LENGTH; i++) {
if (i > 0) {
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
BOOST_CHECK(vIndex[i].pskip->nHeight < i);
} else {
BOOST_CHECK(vIndex[i].pskip == NULL);
}
}
for (int i=0; i < 1000; i++) {
int from = insecure_rand() % (SKIPLIST_LENGTH - 1);
int to = insecure_rand() % (from + 1);
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]);
}
}
BOOST_AUTO_TEST_CASE(getlocator_test)
{
// Build a main chain 100000 blocks long.
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances.
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight);
BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1);
}
// Build a branch that splits off at block 49999, 50000 blocks long.
std::vector<uint256> vHashSide(50000);
std::vector<CBlockIndex> vBlocksSide(50000);
for (unsigned int i=0; i<vBlocksSide.size(); i++) {
vHashSide[i] = ArithToUint256(i + 50000 + (arith_uint256(1) << 128)); // Add 1<<128 to the hashes, so GetLow64() still returns the height.
vBlocksSide[i].nHeight = i + 50000;
vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[49999];
vBlocksSide[i].phashBlock = &vHashSide[i];
vBlocksSide[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight);
BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Test 100 random starting points for locators.
for (int n=0; n<100; n++) {
int r = insecure_rand() % 150000;
CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000];
CBlockLocator locator = chain.GetLocator(tip);
// The first result must be the block itself, the last one must be genesis.
BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash());
BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash());
// Entries 1 through 11 (inclusive) go back one step each.
for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->nHeight - i);
}
// The further ones (excluding the last one) go back with exponential steps.
unsigned int dist = 2;
for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i - 1]).GetLow64() - UintToArith256(locator.vHave[i]).GetLow64(), dist);
dist *= 2;
}
}
}
BOOST_AUTO_TEST_CASE(findearliestatleast_test)
{
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
if (i < 10) {
vBlocksMain[i].nTime = i;
vBlocksMain[i].nTimeMax = i;
} else {
// randomly choose something in the range [MTP, MTP*2]
int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast();
int r = insecure_rand() % medianTimePast;
vBlocksMain[i].nTime = r + medianTimePast;
vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax);
}
}
// Check that we set nTimeMax up correctly.
unsigned int curTimeMax = 0;
for (unsigned int i=0; i<vBlocksMain.size(); ++i) {
curTimeMax = std::max(curTimeMax, vBlocksMain[i].nTime);
BOOST_CHECK(curTimeMax == vBlocksMain[i].nTimeMax);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Verify that FindEarliestAtLeast is correct.
for (unsigned int i=0; i<10000; ++i) {
// Pick a random element in vBlocksMain.
int r = insecure_rand() % vBlocksMain.size();
int64_t test_time = vBlocksMain[r].nTime;
CBlockIndex *ret = chain.FindEarliestAtLeast(test_time);
BOOST_CHECK(ret->nTimeMax >= test_time);
BOOST_CHECK((ret->pprev==NULL) || ret->pprev->nTimeMax < test_time);
BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
; A002535: a(n) = 2*a(n-1) + 9*a(n-2), with a(0)=a(1)=1.
; Submitted by Jon Maiga
; 1,1,11,31,161,601,2651,10711,45281,186961,781451,3245551,13524161,56258281,234234011,974792551,4057691201,16888515361,70296251531,292589141311,1217844546401,5068991364601,21098583646811,87818089575031,365523431971361,1521409670118001,6332530227978251,26357747487018511,109708267025841281,456636261434849161,1900646926102269851,7911020205118182151,32927862745156792961,137054907336377225281,570460579379165587211,2374415324785726201951,9882975863983942688801,41135689651039421195161
mov $3,1
lpb $0
sub $0,1
mov $2,$3
mul $2,10
add $3,$1
add $1,$2
lpe
mov $0,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r15
push %r8
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x4bab, %rsi
lea addresses_A_ht+0x13f4d, %rdi
clflush (%rdi)
nop
nop
nop
nop
cmp %r15, %r15
mov $25, %rcx
rep movsb
nop
nop
nop
add %r8, %r8
lea addresses_A_ht+0xe80b, %rsi
lea addresses_A_ht+0x7f0b, %rdi
clflush (%rsi)
nop
nop
nop
nop
and $32967, %r12
mov $98, %rcx
rep movsl
nop
nop
nop
nop
nop
xor $18565, %rdi
lea addresses_WC_ht+0x840b, %r8
nop
nop
nop
nop
xor $25167, %r15
movb (%r8), %cl
nop
nop
nop
dec %r15
lea addresses_normal_ht+0xab, %rsi
lea addresses_D_ht+0x1c48b, %rdi
clflush (%rdi)
nop
nop
nop
nop
add %r10, %r10
mov $110, %rcx
rep movsw
nop
xor %r8, %r8
lea addresses_WC_ht+0x162c7, %r15
nop
nop
inc %rcx
mov $0x6162636465666768, %r10
movq %r10, %xmm3
vmovups %ymm3, (%r15)
nop
nop
nop
nop
nop
sub $52279, %rsi
lea addresses_normal_ht+0xd70b, %rsi
lea addresses_normal_ht+0x1480b, %rdi
nop
nop
add $37779, %r11
mov $111, %rcx
rep movsl
nop
nop
inc %rdi
lea addresses_D_ht+0x1a00b, %r15
nop
xor $39679, %r12
mov $0x6162636465666768, %rcx
movq %rcx, %xmm6
vmovups %ymm6, (%r15)
xor $59781, %rsi
lea addresses_WT_ht+0xc2ad, %rsi
lea addresses_WT_ht+0x1a43f, %rdi
nop
nop
cmp %r8, %r8
mov $127, %rcx
rep movsb
xor %r10, %r10
pop %rsi
pop %rdi
pop %rcx
pop %r8
pop %r15
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r14
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
// Store
lea addresses_WC+0xe333, %r10
nop
nop
nop
nop
xor %rbp, %rbp
movl $0x51525354, (%r10)
nop
nop
nop
add $44148, %rax
// Store
lea addresses_WC+0x2057, %rax
clflush (%rax)
nop
sub %r8, %r8
mov $0x5152535455565758, %rsi
movq %rsi, %xmm4
vmovups %ymm4, (%rax)
nop
nop
and $40300, %rsi
// REPMOV
mov $0x40b, %rsi
lea addresses_normal+0x16b0b, %rdi
nop
nop
nop
nop
and $14071, %r8
mov $18, %rcx
rep movsb
nop
nop
nop
xor $46665, %rsi
// Store
lea addresses_A+0x1f40b, %r8
nop
nop
inc %r14
movl $0x51525354, (%r8)
nop
nop
add %r8, %r8
// Faulty Load
lea addresses_PSE+0x1600b, %rbp
dec %r14
vmovups (%rbp), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %r11
lea oracles, %r8
and $0xff, %r11
shlq $12, %r11
mov (%r8,%r11,1), %r11
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r14
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_P'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_normal'}, 'OP': 'REPM'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 10, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 10, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 5, 'same': True, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A110328: Row sums of a number triangle related to the Pell numbers.
; Submitted by Christian Krause
; 1,3,15,109,1053,12711,184123,3111585,60096249,1305766603,31523994471,837162204693,24253060182805,761176868685039,25727009276451603,931657420717406281,35987519689305385713,1476986487871517622675
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
sub $3,$1
mul $1,$0
mul $1,2
mov $5,$0
mul $5,$3
mov $3,0
sub $3,$5
div $3,2
add $3,1
add $1,$3
lpe
mov $0,$1
|
; A304974: Number of achiral color patterns (set partitions) for a row or loop of length n using exactly 4 colors (sets).
; 0,0,0,0,1,2,9,16,53,90,265,440,1221,2002,5369,8736,22933,37130,96105,155080,397541,640002,1629529,2619056,6636213,10653370,26899145,43144920,108659461,174174002,437826489,701478976,1760871893,2820264810,7072185385,11324105960,28374834981,45425564002,113757620249,182089676496,455805321973,729520967450,1825545810825,2921570654200,7309156812101,11696742970002,29257547954809,46818352939616,117092953938453,187367554937290,468560102111465,749752649285640,1874805267518821,2999857885752002
mov $2,$0
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
mov $5,$0
mov $10,$0
mov $11,0
lpb $5
mov $0,$10
sub $5,2
sub $0,$5
mov $6,$0
mov $7,0
mov $8,2
lpb $8
mov $0,$6
sub $8,1
add $0,$8
sub $0,1
div $0,2
trn $0,1
seq $0,145544 ; 4*(4^n-3^n).
mov $3,$0
mov $9,$8
mul $9,$0
add $7,$9
lpe
min $6,1
mul $6,$3
mov $3,$7
sub $3,$6
div $3,4
add $11,$3
lpe
add $1,$11
lpe
mov $0,$1
|
// Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/args_vector.hpp>
#include <fcppt/text.hpp>
#include <fcppt/catch/begin.hpp>
#include <fcppt/catch/either.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/catch/record.hpp>
#include <fcppt/catch/strong_typedef.hpp>
#include <fcppt/either/comparison.hpp>
#include <fcppt/options/apply.hpp>
#include <fcppt/options/argument.hpp>
#include <fcppt/options/duplicate_names.hpp>
#include <fcppt/options/flag.hpp>
#include <fcppt/options/long_name.hpp>
#include <fcppt/options/make_active_value.hpp>
#include <fcppt/options/make_inactive_value.hpp>
#include <fcppt/options/make_success.hpp>
#include <fcppt/options/optional_help_text.hpp>
#include <fcppt/options/optional_short_name.hpp>
#include <fcppt/options/parse.hpp>
#include <fcppt/options/short_name.hpp>
#include <fcppt/record/comparison.hpp>
#include <fcppt/record/make_label.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <fcppt/config/external_end.hpp>
FCPPT_CATCH_BEGIN
TEST_CASE("options::apply", "[options]")
{
FCPPT_RECORD_MAKE_LABEL(arg_label);
using int_arg_type = fcppt::options::argument<arg_label, int>;
FCPPT_RECORD_MAKE_LABEL(flag_label);
using int_flag_type = fcppt::options::flag<flag_label, int>;
auto const mult_parser(fcppt::options::apply(
int_arg_type{
fcppt::options::long_name{FCPPT_TEXT("arg1")}, fcppt::options::optional_help_text{}},
int_flag_type{
fcppt::options::optional_short_name{fcppt::options::short_name{FCPPT_TEXT("f")}},
fcppt::options::long_name{FCPPT_TEXT("flag")},
fcppt::options::make_active_value(42),
fcppt::options::make_inactive_value(10),
fcppt::options::optional_help_text{}}));
CHECK(
fcppt::options::parse(
mult_parser, fcppt::args_vector{FCPPT_TEXT("--flag"), FCPPT_TEXT("123")}) ==
fcppt::options::make_success(
decltype(mult_parser)::result_type{arg_label{} = 123, flag_label{} = 42}));
}
TEST_CASE("options::apply duplicate names", "[options]")
{
FCPPT_RECORD_MAKE_LABEL(flag_label1);
FCPPT_RECORD_MAKE_LABEL(flag_label2);
using flag1_type = fcppt::options::flag<flag_label1, int>;
using flag2_type = fcppt::options::flag<flag_label2, int>;
CHECK_THROWS_AS(
fcppt::options::apply(
flag1_type{
fcppt::options::optional_short_name{},
fcppt::options::long_name{FCPPT_TEXT("flag")},
fcppt::options::make_active_value(0),
fcppt::options::make_inactive_value(1),
fcppt::options::optional_help_text{}},
flag2_type{
fcppt::options::optional_short_name{},
fcppt::options::long_name{FCPPT_TEXT("flag")},
fcppt::options::make_active_value(0),
fcppt::options::make_inactive_value(1),
fcppt::options::optional_help_text{}}),
fcppt::options::duplicate_names);
}
FCPPT_CATCH_END
|
#include<stdio.h>
#include<windows.h>
#include <tchar.h>
// 头文件不可以空格
int main(void)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (!CreateProcess(NULL,
/* "const char *" 类型的实参与 "LPWSTR" 类型的形参不兼容C/C++(167)
* 报错原因代码是vc6.0写的,采用ANSII编码方式,而vscode采用unicode编码
* 解决方法:引入头文件tchar.h
* "c:\\WINDOWS\\system32\\mspaint.exe" --->_T("c:\\WINDOWS\\system32\\mspaint.exe")
*/
_T("c:\\WINDOWS\\system32\\mspaint.exe"),
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si, &pi))
/* LPSTR被定义成是一个指向以NULL(‘\0’)结尾的32位ANSI字符数组指针
* 而LPWSTR是一个指向以NULL结尾的64位双字节字符数组指针。*/
{
fprintf(stderr, "Creat Process Failed");
return -1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
printf("child Complete");
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x7d4, %rsi
lea addresses_A_ht+0x18824, %rdi
nop
nop
nop
nop
add %rax, %rax
mov $13, %rcx
rep movsq
nop
cmp $27634, %rcx
lea addresses_WT_ht+0x14774, %rsi
lea addresses_UC_ht+0x1c014, %rdi
clflush (%rdi)
nop
nop
nop
cmp %rbp, %rbp
mov $39, %rcx
rep movsq
nop
nop
nop
nop
nop
add $29525, %rbp
lea addresses_UC_ht+0x13394, %rsi
lea addresses_WT_ht+0x2794, %rdi
clflush (%rdi)
nop
nop
nop
cmp $41692, %r11
mov $88, %rcx
rep movsb
nop
nop
nop
sub %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r8
push %r9
push %rax
push %rdi
push %rdx
push %rsi
// Store
lea addresses_PSE+0x1e094, %r11
nop
nop
sub $55741, %rsi
mov $0x5152535455565758, %rdx
movq %rdx, %xmm3
movups %xmm3, (%r11)
nop
nop
nop
nop
cmp $58555, %rdi
// Faulty Load
lea addresses_WT+0x1cf94, %r8
nop
nop
nop
nop
cmp $58126, %rax
movb (%r8), %r11b
lea oracles, %r8
and $0xff, %r11
shlq $12, %r11
mov (%r8,%r11,1), %r11
pop %rsi
pop %rdx
pop %rdi
pop %rax
pop %r9
pop %r8
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
<%
from pwnlib.shellcraft import eval, pretty, okay
from pwnlib.util import lists, packing, fiddling, misc
from pwnlib.log import getLogger
from pwnlib.shellcraft.registers import get_register, is_register, bits_required
log = getLogger('pwnlib.shellcraft.i386.mov')
%>
<%page args="dest, src, stack_allowed = True"/>
<%docstring>
Move src into dest without newlines and null bytes.
If the src is a register smaller than the dest, then it will be
zero-extended to fit inside the larger register.
If the src is a register larger than the dest, then only some of the bits will
be used.
If src is a string that is not a register, then it will locally set
`context.arch` to `'i386'` and use :func:`pwnlib.constants.eval` to evaluate the
string. Note that this means that this shellcode can change behavior depending
on the value of `context.os`.
Args:
dest (str): The destination register.
src (str): Either the input register, or an immediate value.
stack_allowed (bool): Can the stack be used?
Example:
>>> print shellcraft.i386.mov('eax','ebx').rstrip()
mov eax, ebx
>>> print shellcraft.i386.mov('eax', 0).rstrip()
xor eax, eax
>>> print shellcraft.i386.mov('ax', 0).rstrip()
xor ax, ax
>>> print shellcraft.i386.mov('ax', 17).rstrip()
xor ax, ax
mov al, 0x11
>>> print shellcraft.i386.mov('edi', ord('\n')).rstrip()
push 9 /* mov edi, '\n' */
pop edi
inc edi
>>> print shellcraft.i386.mov('al', 'ax').rstrip()
/* moving ax into al, but this is a no-op */
>>> print shellcraft.i386.mov('al','ax').rstrip()
/* moving ax into al, but this is a no-op */
>>> print shellcraft.i386.mov('esp', 'esp').rstrip()
/* moving esp into esp, but this is a no-op */
>>> print shellcraft.i386.mov('ax', 'bl').rstrip()
movzx ax, bl
>>> print shellcraft.i386.mov('eax', 1).rstrip()
push 1
pop eax
>>> print shellcraft.i386.mov('eax', 1, stack_allowed=False).rstrip()
xor eax, eax
mov al, 1
>>> print shellcraft.i386.mov('eax', 0xdead00ff).rstrip()
mov eax, -0xdead00ff
neg eax
>>> print shellcraft.i386.mov('eax', 0xc0).rstrip()
xor eax, eax
mov al, 0xc0
>>> print shellcraft.i386.mov('edi', 0xc0).rstrip()
mov edi, -0xc0
neg edi
>>> print shellcraft.i386.mov('eax', 0xc000).rstrip()
xor eax, eax
mov ah, 0xc000 >> 8
>>> print shellcraft.i386.mov('eax', 0xffc000).rstrip()
mov eax, 0x1010101
xor eax, 0x1010101 ^ 0xffc000
>>> print shellcraft.i386.mov('edi', 0xc000).rstrip()
mov edi, (-1) ^ 0xc000
not edi
>>> print shellcraft.i386.mov('edi', 0xf500).rstrip()
mov edi, 0x1010101
xor edi, 0x1010101 ^ 0xf500
>>> print shellcraft.i386.mov('eax', 0xc0c0).rstrip()
xor eax, eax
mov ax, 0xc0c0
>>> print shellcraft.i386.mov('eax', 'SYS_execve').rstrip()
push (SYS_execve) /* 0xb */
pop eax
>>> with context.local(os='freebsd'):
... print shellcraft.i386.mov('eax', 'SYS_execve').rstrip()
push (SYS_execve) /* 0x3b */
pop eax
>>> print shellcraft.i386.mov('eax', 'PROT_READ | PROT_WRITE | PROT_EXEC').rstrip()
push (PROT_READ | PROT_WRITE | PROT_EXEC) /* 7 */
pop eax
</%docstring>
<%
src_name = src
if not isinstance(src, (str, tuple)):
src_name = pretty(src)
if not get_register(dest):
log.error('%r is not a register' % dest)
dest = get_register(dest)
if dest.size > 32 or dest.is64bit:
log.error("cannot use %s on i386" % dest)
if get_register(src):
src = get_register(src)
if src.is64bit:
log.error("cannot use %s on i386" % src)
if dest.size < src.size and src.name not in dest.bigger:
log.error("cannot mov %s, %s: dddest is smaller than src" % (dest, src))
else:
src = eval(src)
if not dest.fits(src):
log.error("cannot mov %s, %r: dest is smaller than src" % (dest, src))
src_size = bits_required(src)
# Calculate the packed version
mask = ((1<<32)-1)
masked = src & mask
srcp = packing.pack(masked, dest.size)
# Calculate the unsigned and signed versions
srcu = packing.unpack(srcp, dest.size, sign=False)
srcs = packing.unpack(srcp, dest.size, sign=True)
srcp_not = packing.pack(fiddling.bnot(masked))
srcp_neg = packing.pack(fiddling.negate(masked))
srcu_not = packing.unpack(srcp_not)
srcu_neg = packing.unpack(srcp_neg)
%>\
% if is_register(src):
% if src == dest:
/* moving ${src} into ${dest}, but this is a no-op */
% elif src.name in dest.bigger:
/* moving ${src} into ${dest}, but this is a no-op */
% elif dest.size > src.size:
movzx ${dest}, ${src}
% else:
mov ${dest}, ${src}
% endif
% elif isinstance(src, (int, long)):
## Special case for zeroes
% if src == 0:
xor ${dest}, ${dest}
## Special case for *just* a newline
% elif stack_allowed and dest.size == 32 and src == 10:
push 9 /* mov ${dest}, '\n' */
pop ${dest}
inc ${dest}
## Can we push/pop it?
## This is shorter than a `mov` and has a better (more ASCII) encoding.
## Note there are two variants for PUSH IMM32 and PUSH IMM8
% elif stack_allowed and dest.size == 32 and okay(srcp):
push ${pretty(src)}
pop ${dest}
% elif stack_allowed and dest.size == 32 and -127 <= srcs < 128 and okay(srcp[0]):
push ${pretty(src)}
pop ${dest}
## Easy case, everybody is happy
% elif okay(srcp):
mov ${dest}, ${pretty(src)}
## If it's an IMM8, we can use the 8-bit register
% elif 0 <= srcu < 2**8 and okay(srcp[0]) and dest.sizes.get(8, 0):
xor ${dest}, ${dest}
mov ${dest.sizes[8]}, ${pretty(srcu)}
## If it's an IMM16, but there's nothing in the lower 8 bits,
## we can use the high-8-bits register.
## However, we must check that it exists.
% elif srcu == (srcu & 0xff00) and okay(srcp[1]) and dest.ff00:
xor ${dest}, ${dest}
mov ${dest.ff00}, ${pretty(src)} >> 8
## If it's an IMM16, use the 16-bit register
% elif 0 <= srcu < 2**16 and okay(srcp[:2]) and dest.sizes[16]:
xor ${dest}, ${dest}
mov ${dest.sizes[16]}, ${pretty(src)}
## A few more tricks to try...
% elif okay(srcp_neg):
mov ${dest}, -${pretty(src)}
neg ${dest}
%elif okay(srcp_not):
mov ${dest}, (-1) ^ ${pretty(src)}
not ${dest}
## We couldn't find a way to make things work out, so just do
## the XOR trick.
% else:
<%
a,b = fiddling.xor_pair(srcp, avoid = '\x00\n')
a = hex(packing.unpack(a, dest.size))
b = hex(packing.unpack(b, dest.size))
%>\
mov ${dest}, ${a}
xor ${dest}, ${a} ^ ${pretty(src)}
% endif
% endif
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; IsZeroBuffer.nasm
;
; Abstract:
;
; IsZeroBuffer function
;
; Notes:
;
;------------------------------------------------------------------------------
SECTION .text
;------------------------------------------------------------------------------
; BOOLEAN
; EFIAPI
; InternalMemIsZeroBuffer (
; IN CONST VOID *Buffer,
; IN UINTN Length
; );
;------------------------------------------------------------------------------
global ASM_PFX(InternalMemIsZeroBuffer)
ASM_PFX(InternalMemIsZeroBuffer):
push edi
mov edi, [esp + 8] ; edi <- Buffer
mov edx, [esp + 12] ; edx <- Length
xor ecx, ecx ; ecx <- 0
sub ecx, edi
and ecx, 15 ; ecx + edi aligns on 16-byte boundary
jz @Is16BytesZero
cmp ecx, edx
cmova ecx, edx ; bytes before the 16-byte boundary
sub edx, ecx
xor eax, eax ; eax <- 0, also set ZF
repe scasb
jnz @ReturnFalse ; ZF=0 means non-zero element found
@Is16BytesZero:
mov ecx, edx
and edx, 15
shr ecx, 4
jz @IsBytesZero
.0:
pxor xmm0, xmm0 ; xmm0 <- 0
pcmpeqb xmm0, [edi] ; check zero for 16 bytes
pmovmskb eax, xmm0 ; eax <- compare results
cmp eax, 0xffff
jnz @ReturnFalse
add edi, 16
loop .0
@IsBytesZero:
mov ecx, edx
xor eax, eax ; eax <- 0, also set ZF
repe scasb
jnz @ReturnFalse ; ZF=0 means non-zero element found
pop edi
mov eax, 1 ; return TRUE
ret
@ReturnFalse:
pop edi
xor eax, eax
ret ; return FALSE
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 91
call lwaitly_b
ld hl, fe00
ld d, 10
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 0e
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 14
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 2e
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 34
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 4e
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 54
ld(hl++), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 01
ldff(45), a
ld c, 41
ld a, 93
ldff(40), a
ld a, 05
ldff(43), a
.text@1000
lstatint:
nop
.text@109b
ldff a, (c)
and a, 03
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
// fms_sequence_reverse.t.cpp Test reverse sequence
#include <cassert>
#include <vector>
#include "fms_sequence_reverse.h"
#include "fms_sequence_take.h"
using namespace fms::sequence;
template<class X>
int test_reverse()
{
std::vector<X> s = { 1, 2, 3 };
{
auto r = reverse(s.begin(), s.end());
assert(r);
assert(*r == 3);
++r;
assert(r);
assert(*r == 2);
++r;
assert(r);
assert(*r == 1);
++r;
assert(!r);
}
{
auto r = make_reverse(s);
assert(r);
assert(*r == 3);
++r;
assert(r);
assert(*r == 2);
++r;
assert(r);
assert(*r == 1);
++r;
assert(!r);
}
return 0;
}
int test_reverse_double = test_reverse<double>();
|
; A104326: Dual Zeckendorf representation of n or the maximal (binary) Fibonacci representation. Also list of binary vectors not containing 00.
; Submitted by Christian Krause
; 0,1,10,11,101,110,111,1010,1011,1101,1110,1111,10101,10110,10111,11010,11011,11101,11110,11111,101010,101011,101101,101110,101111,110101,110110,110111,111010,111011,111101,111110,111111,1010101,1010110,1010111,1011010,1011011,1011101,1011110,1011111,1101010,1101011,1101101,1101110,1101111,1110101,1110110,1110111,1111010,1111011,1111101,1111110,1111111,10101010,10101011,10101101,10101110,10101111,10110101,10110110,10110111,10111010,10111011,10111101,10111110,10111111,11010101,11010110,11010111
seq $0,3754 ; Numbers with no adjacent 0's in binary expansion.
seq $0,7088 ; The binary numbers (or binary words, or binary vectors, or binary expansion of n): numbers written in base 2.
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r15
push %rbp
push %rbx
push %rdx
// Faulty Load
mov $0x64bc6c00000003bc, %r12
nop
nop
xor $49772, %rdx
movups (%r12), %xmm4
vpextrq $1, %xmm4, %rbx
lea oracles, %rbp
and $0xff, %rbx
shlq $12, %rbx
mov (%rbp,%rbx,1), %rbx
pop %rdx
pop %rbx
pop %rbp
pop %r15
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': True, 'size': 8}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'ff': 1, '79': 26, '5b': 88, '08': 125, '00': 21589}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
module Console
KEY_UP = #19
KEY_DN = #1A
KEY_LT = #8
KEY_RT = #18
newLine:
ld a, CR
call putC
ld a, LF
putC:
ld e, a
ld c, 2
jp BDOS
getC:
peekC:
ld c, 6, e, #ff
jp BDOS
putStringZ:
ld a, (hl)
and a
ret z
push hl
call putC
pop hl
inc hl
jr putStringZ
waitForKeyUp:
ret
endmodule
|
#ifndef DS_GAME_ROOM_GENERATOR_HPP
#define DS_GAME_ROOM_GENERATOR_HPP
#include "../Block/BlockBrick.hpp"
#include "../Block/BlockBackground.hpp"
#include "../Block/BlockTorch.hpp"
#include "../Block/BlockWindow.hpp"
#include "../Block/BlockLadder.hpp"
#include "../Block/BlockColumn.hpp"
#include "../Block/BlockBroken.hpp"
namespace ds {
class Level;
class RoomGenerator {
private:
Level* level;
public:
RoomGenerator();
RoomGenerator(Level* level);
void generateRooms(const sf::Vector2i& startPos,
std::uint8_t rooms,
const bool& startUp);
void generateRoomUpStartTwoExits(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateRoomUpStartOneExit(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateRoomDownStartTwoExits(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateRoomDownStartOneExit(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateCorridorWithColumns(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateCorridor(const sf::Vector2i& position,
const std::uint8_t& rooms);
void generateCorridorWithWindows(const sf::Vector2i& position,
const std::uint8_t& rooms);
};
}
#endif // DS_GAME_ROOM_GENERATOR_HPP
|
; A138252: Beatty sequence of the number t satisfying 1/s + 1/t = 1, where s is the positive root of x^3 - x^2 - 1.
; 3,6,9,12,15,18,22,25,28,31,34,37,40,44,47,50,53,56,59,62,66,69,72,75,78,81,84,88,91,94,97,100,103,107,110,113,116,119,122,125,129,132,135,138,141,144,147,151,154,157,160,163,166,169,173,176,179,182,185,188
mov $1,4
mov $2,$0
add $2,3
mov $3,$0
lpb $2
mov $0,5
lpb $4
add $0,5
add $1,1
trn $4,$2
add $2,4
sub $2,$0
lpe
trn $2,1
add $4,$1
lpe
lpb $3
add $1,3
sub $3,1
lpe
sub $1,2
|
// Tests that identical strings are consolidated
// Commodore 64 PRG executable file
.file [name="string-const-consolidation.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.label screen = 4
.segment Code
main: {
// print(rex1)
lda #<$400
sta.z screen
lda #>$400
sta.z screen+1
jsr print
// print(rex2)
jsr print
// print("rex")
jsr print
// }
rts
}
// void print(__zp(2) char *string)
print: {
.label string = 2
lda #<rex1
sta.z string
lda #>rex1
sta.z string+1
__b1:
// while(*string)
ldy #0
lda (string),y
cmp #0
bne __b2
// }
rts
__b2:
// *screen++ = *string++
ldy #0
lda (string),y
sta (screen),y
// *screen++ = *string++;
inc.z screen
bne !+
inc.z screen+1
!:
inc.z string
bne !+
inc.z string+1
!:
jmp __b1
}
.segment Data
rex1: .text "rex"
.byte 0
|
.cseg
.org 0x00
rcall main_thread
; include components interrupts
;.include "../../../../../src/kernel/drivers/{driver_name}_int.asm"
.include "../../../../../src/kernel/drivers/soc/usart_int.asm"
; include components definitions
.include "../../../../../src/kernel/kernel_def.asm"
;.include "../../../../../src/kernel/drivers/{driver_name}_def.asm"
.include "../../../../../src/kernel/drivers/device_def.asm"
.include "../../../../../src/kernel/drivers/io/device_io_def.asm"
.include "../../../../../src/kernel/drivers/io/in_bit_def.asm"
.include "../../../../../src/kernel/drivers/io/hid/button_def.asm"
.include "../../../../../src/kernel/drivers/io/out_bit_def.asm"
.include "../../../../../src/kernel/drivers/io/hid/led_def.asm"
.include "../../../../../src/kernel/drivers/soc/usart_def.asm"
;.include components data segments
;.include "../../../../../src/kernel/drivers/{driver_name}_dseg.asm"
.include "../../../../../src/kernel/drivers/soc/usart_dseg.asm"
; custom data & descriptors
.dseg
led1: .BYTE SZ_ST_LED
led2: .BYTE SZ_ST_LED
led3: .BYTE SZ_ST_LED
button1: .BYTE SZ_ST_BUTTON
; main thread
.cseg
; skip interrupts vector
.org 0x14
; include components code segments
.include "../../../../../src/kernel/kernel_cseg.asm"
;.include "../../../../../src/kernel/drivers/{driver_name}_cseg.asm"
.include "../../../../../src/kernel/drivers/device_cseg.asm"
.include "../../../../../src/kernel/drivers/io/device_io_cseg.asm"
.include "../../../../../src/kernel/drivers/io/in_bit_cseg.asm"
.include "../../../../../src/kernel/drivers/io/hid/button_cseg.asm"
.include "../../../../../src/kernel/drivers/io/out_bit_cseg.asm"
.include "../../../../../src/kernel/drivers/io/hid/led_cseg.asm"
.include "../../../../../src/kernel/drivers/soc/usart_cseg.asm"
main_thread:
; stack initialization
m_init_stack
; init leds
m_led_init led1, DDRC, PORTC, (1 << BIT3)
m_led_init led2, DDRC, PORTC, (1 << BIT4)
m_led_init led3, DDRC, PORTC, (1 << BIT5)
m_button_init button1, DDRC, PINC, PORTC, (1 << BIT1), button1_on_button_down_handler, button1_on_button_up_handler, button1_on_button_pressed_handler
m_usart_init 1000000, 9600, usart_on_rxc_handler, usart_on_udre_handler, usart_on_txc_handler
m_usart_udre_enable
; init global interrupts
m_init_interrupts
.equ DELAY_TIME = 200000
ldi r16, BUTTON_STATE_DOWN
main_thread_loop:
m_button_handle_io button1
nop
m_led_toggle led1
main_thread_loop_end:
;m_delay DELAY_TIME
rjmp main_thread_loop
ret
button1_on_button_down_handler:
;m_led_off led2
;m_led_off led3
ret
button1_on_button_up_handler:
;m_led_on led2
ret
button1_on_button_pressed_handler:
m_led_off led2
m_led_off led3
m_usart_udre_enable
ret
usart_on_rxc_handler:
;m_led_off led2
m_led_on led3
m_usart_udre_enable
ret
usart_on_udre_handler:
m_usart_udre_disable
; set value to push to UDR
ldi YL, 0xA0
m_led_on led2
;m_led_off led3
ret
usart_on_txc_handler:
ret
|
; A240933: a(n) = n^10 - n^9.
; 0,0,512,39366,786432,7812500,50388480,242121642,939524096,3099363912,9000000000,23579476910,56757583872,127253992476,268593608192,538207031250,1030792151040,1897406023952,3372107936256,5808378560022,9728000000000,15885600931620,25352653573632
mov $1,$0
sub $0,1
pow $1,9
mul $0,$1
|
//////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// [email protected] //
// Created: 2019-12-08 //
// Last edit: 2019-12-08 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "H3Plugins.hpp"
namespace h3
{
}
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld a, ff
ldff(45), a
ld b, 42
call lwaitly_b
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
ld a, 48
ldff(41), a
ldff(45), a
xor a, a
.text@1060
ldff(c), a
ld a, 44
ldff(45), a
nop
nop
ldff a, (c)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
_sh: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
return 0;
}
int
main(void)
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 e4 f0 and $0xfffffff0,%esp
6: 83 ec 10 sub $0x10,%esp
static char buf[100];
int fd;
// Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){
9: eb 0e jmp 19 <main+0x19>
b: 90 nop
c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
if(fd >= 3){
10: 83 f8 02 cmp $0x2,%eax
13: 0f 8f cd 00 00 00 jg e6 <main+0xe6>
{
static char buf[100];
int fd;
// Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){
19: c7 44 24 04 02 00 00 movl $0x2,0x4(%esp)
20: 00
21: c7 04 24 39 13 00 00 movl $0x1339,(%esp)
28: e8 f5 0d 00 00 call e22 <open>
2d: 85 c0 test %eax,%eax
2f: 79 df jns 10 <main+0x10>
31: eb 23 jmp 56 <main+0x56>
33: 90 nop
34: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
}
}
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
38: 80 3d 42 19 00 00 20 cmpb $0x20,0x1942
3f: 90 nop
40: 74 60 je a2 <main+0xa2>
42: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
buf[strlen(buf)-1] = 0; // chop \n
if(chdir(buf+3) < 0)
printf(2, "cannot cd %s\n", buf+3);
continue;
}
if(fork1() == 0)
48: e8 43 01 00 00 call 190 <fork1>
4d: 85 c0 test %eax,%eax
4f: 74 38 je 89 <main+0x89>
runcmd(parsecmd(buf));
wait();
51: e8 94 0d 00 00 call dea <wait>
break;
}
}
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
56: c7 44 24 04 64 00 00 movl $0x64,0x4(%esp)
5d: 00
5e: c7 04 24 40 19 00 00 movl $0x1940,(%esp)
65: e8 96 00 00 00 call 100 <getcmd>
6a: 85 c0 test %eax,%eax
6c: 78 2f js 9d <main+0x9d>
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
6e: 80 3d 40 19 00 00 63 cmpb $0x63,0x1940
75: 75 d1 jne 48 <main+0x48>
77: 80 3d 41 19 00 00 64 cmpb $0x64,0x1941
7e: 74 b8 je 38 <main+0x38>
buf[strlen(buf)-1] = 0; // chop \n
if(chdir(buf+3) < 0)
printf(2, "cannot cd %s\n", buf+3);
continue;
}
if(fork1() == 0)
80: e8 0b 01 00 00 call 190 <fork1>
85: 85 c0 test %eax,%eax
87: 75 c8 jne 51 <main+0x51>
runcmd(parsecmd(buf));
89: c7 04 24 40 19 00 00 movl $0x1940,(%esp)
90: e8 ab 0a 00 00 call b40 <parsecmd>
95: 89 04 24 mov %eax,(%esp)
98: e8 13 01 00 00 call 1b0 <runcmd>
wait();
}
exit();
9d: e8 40 0d 00 00 call de2 <exit>
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
// Chdir must be called by the parent, not the child.
buf[strlen(buf)-1] = 0; // chop \n
a2: c7 04 24 40 19 00 00 movl $0x1940,(%esp)
a9: e8 92 0b 00 00 call c40 <strlen>
if(chdir(buf+3) < 0)
ae: c7 04 24 43 19 00 00 movl $0x1943,(%esp)
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
// Chdir must be called by the parent, not the child.
buf[strlen(buf)-1] = 0; // chop \n
b5: c6 80 3f 19 00 00 00 movb $0x0,0x193f(%eax)
if(chdir(buf+3) < 0)
bc: e8 91 0d 00 00 call e52 <chdir>
c1: 85 c0 test %eax,%eax
c3: 79 91 jns 56 <main+0x56>
printf(2, "cannot cd %s\n", buf+3);
c5: c7 44 24 08 43 19 00 movl $0x1943,0x8(%esp)
cc: 00
cd: c7 44 24 04 41 13 00 movl $0x1341,0x4(%esp)
d4: 00
d5: c7 04 24 02 00 00 00 movl $0x2,(%esp)
dc: e8 4f 0e 00 00 call f30 <printf>
e1: e9 70 ff ff ff jmp 56 <main+0x56>
int fd;
// Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){
if(fd >= 3){
close(fd);
e6: 89 04 24 mov %eax,(%esp)
e9: e8 1c 0d 00 00 call e0a <close>
ee: 66 90 xchg %ax,%ax
break;
f0: e9 61 ff ff ff jmp 56 <main+0x56>
f5: 66 90 xchg %ax,%ax
f7: 66 90 xchg %ax,%ax
f9: 66 90 xchg %ax,%ax
fb: 66 90 xchg %ax,%ax
fd: 66 90 xchg %ax,%ax
ff: 90 nop
00000100 <getcmd>:
exit();
}
int
getcmd(char *buf, int nbuf)
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 56 push %esi
104: 53 push %ebx
105: 83 ec 10 sub $0x10,%esp
108: 8b 5d 08 mov 0x8(%ebp),%ebx
10b: 8b 75 0c mov 0xc(%ebp),%esi
printf(2, "$ ");
10e: c7 44 24 04 98 12 00 movl $0x1298,0x4(%esp)
115: 00
116: c7 04 24 02 00 00 00 movl $0x2,(%esp)
11d: e8 0e 0e 00 00 call f30 <printf>
memset(buf, 0, nbuf);
122: 89 74 24 08 mov %esi,0x8(%esp)
126: 89 1c 24 mov %ebx,(%esp)
129: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
130: 00
131: e8 3a 0b 00 00 call c70 <memset>
gets(buf, nbuf);
136: 89 74 24 04 mov %esi,0x4(%esp)
13a: 89 1c 24 mov %ebx,(%esp)
13d: e8 8e 0b 00 00 call cd0 <gets>
if(buf[0] == 0) // EOF
142: 31 c0 xor %eax,%eax
144: 80 3b 00 cmpb $0x0,(%ebx)
147: 0f 94 c0 sete %al
return -1;
return 0;
}
14a: 83 c4 10 add $0x10,%esp
14d: 5b pop %ebx
getcmd(char *buf, int nbuf)
{
printf(2, "$ ");
memset(buf, 0, nbuf);
gets(buf, nbuf);
if(buf[0] == 0) // EOF
14e: f7 d8 neg %eax
return -1;
return 0;
}
150: 5e pop %esi
151: 5d pop %ebp
152: c3 ret
153: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
159: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000160 <panic>:
exit();
}
void
panic(char *s)
{
160: 55 push %ebp
161: 89 e5 mov %esp,%ebp
163: 83 ec 18 sub $0x18,%esp
printf(2, "%s\n", s);
166: 8b 45 08 mov 0x8(%ebp),%eax
169: c7 44 24 04 35 13 00 movl $0x1335,0x4(%esp)
170: 00
171: c7 04 24 02 00 00 00 movl $0x2,(%esp)
178: 89 44 24 08 mov %eax,0x8(%esp)
17c: e8 af 0d 00 00 call f30 <printf>
exit();
181: e8 5c 0c 00 00 call de2 <exit>
186: 8d 76 00 lea 0x0(%esi),%esi
189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000190 <fork1>:
}
int
fork1(void)
{
190: 55 push %ebp
191: 89 e5 mov %esp,%ebp
193: 83 ec 18 sub $0x18,%esp
int pid;
pid = fork();
196: e8 3f 0c 00 00 call dda <fork>
if(pid == -1)
19b: 83 f8 ff cmp $0xffffffff,%eax
19e: 74 02 je 1a2 <fork1+0x12>
panic("fork");
return pid;
}
1a0: c9 leave
1a1: c3 ret
{
int pid;
pid = fork();
if(pid == -1)
panic("fork");
1a2: c7 04 24 9b 12 00 00 movl $0x129b,(%esp)
1a9: e8 b2 ff ff ff call 160 <panic>
1ae: 66 90 xchg %ax,%ax
000001b0 <runcmd>:
struct cmd *parsecmd(char*);
// Execute cmd. Never returns.
void
runcmd(struct cmd *cmd)
{
1b0: 55 push %ebp
1b1: 89 e5 mov %esp,%ebp
1b3: 53 push %ebx
1b4: 83 ec 24 sub $0x24,%esp
1b7: 8b 5d 08 mov 0x8(%ebp),%ebx
struct execcmd *ecmd;
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
1ba: 85 db test %ebx,%ebx
1bc: 74 5f je 21d <runcmd+0x6d>
exit();
switch(cmd->type){
1be: 83 3b 05 cmpl $0x5,(%ebx)
1c1: 0f 87 e7 00 00 00 ja 2ae <runcmd+0xfe>
1c7: 8b 03 mov (%ebx),%eax
1c9: ff 24 85 50 13 00 00 jmp *0x1350(,%eax,4)
runcmd(lcmd->right);
break;
case PIPE:
pcmd = (struct pipecmd*)cmd;
if(pipe(p) < 0)
1d0: 8d 45 f0 lea -0x10(%ebp),%eax
1d3: 89 04 24 mov %eax,(%esp)
1d6: e8 17 0c 00 00 call df2 <pipe>
1db: 85 c0 test %eax,%eax
1dd: 0f 88 d7 00 00 00 js 2ba <runcmd+0x10a>
panic("pipe");
if(fork1() == 0){
1e3: e8 a8 ff ff ff call 190 <fork1>
1e8: 85 c0 test %eax,%eax
1ea: 0f 84 2e 01 00 00 je 31e <runcmd+0x16e>
dup(p[1]);
close(p[0]);
close(p[1]);
runcmd(pcmd->left);
}
if(fork1() == 0){
1f0: e8 9b ff ff ff call 190 <fork1>
1f5: 85 c0 test %eax,%eax
1f7: 0f 84 e9 00 00 00 je 2e6 <runcmd+0x136>
dup(p[0]);
close(p[0]);
close(p[1]);
runcmd(pcmd->right);
}
close(p[0]);
1fd: 8b 45 f0 mov -0x10(%ebp),%eax
200: 89 04 24 mov %eax,(%esp)
203: e8 02 0c 00 00 call e0a <close>
close(p[1]);
208: 8b 45 f4 mov -0xc(%ebp),%eax
20b: 89 04 24 mov %eax,(%esp)
20e: e8 f7 0b 00 00 call e0a <close>
wait();
213: e8 d2 0b 00 00 call dea <wait>
wait();
218: e8 cd 0b 00 00 call dea <wait>
21d: 8d 76 00 lea 0x0(%esi),%esi
case REDIR:
rcmd = (struct redircmd*)cmd;
close(rcmd->fd);
if(open(rcmd->file, rcmd->mode) < 0){
printf(2, "open %s failed\n", rcmd->file);
exit();
220: e8 bd 0b 00 00 call de2 <exit>
wait();
break;
case BACK:
bcmd = (struct backcmd*)cmd;
if(fork1() == 0)
225: e8 66 ff ff ff call 190 <fork1>
22a: 85 c0 test %eax,%eax
22c: 75 ef jne 21d <runcmd+0x6d>
22e: 66 90 xchg %ax,%ax
230: eb 71 jmp 2a3 <runcmd+0xf3>
default:
panic("runcmd");
case EXEC:
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
232: 8b 43 04 mov 0x4(%ebx),%eax
235: 85 c0 test %eax,%eax
237: 74 e4 je 21d <runcmd+0x6d>
exit();
exec(ecmd->argv[0], ecmd->argv);
239: 8d 53 04 lea 0x4(%ebx),%edx
23c: 89 54 24 04 mov %edx,0x4(%esp)
240: 89 04 24 mov %eax,(%esp)
243: e8 d2 0b 00 00 call e1a <exec>
printf(2, "exec %s failed\n", ecmd->argv[0]);
248: 8b 43 04 mov 0x4(%ebx),%eax
24b: c7 44 24 04 a7 12 00 movl $0x12a7,0x4(%esp)
252: 00
253: c7 04 24 02 00 00 00 movl $0x2,(%esp)
25a: 89 44 24 08 mov %eax,0x8(%esp)
25e: e8 cd 0c 00 00 call f30 <printf>
break;
263: eb b8 jmp 21d <runcmd+0x6d>
runcmd(rcmd->cmd);
break;
case LIST:
lcmd = (struct listcmd*)cmd;
if(fork1() == 0)
265: e8 26 ff ff ff call 190 <fork1>
26a: 85 c0 test %eax,%eax
26c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
270: 74 31 je 2a3 <runcmd+0xf3>
runcmd(lcmd->left);
wait();
272: e8 73 0b 00 00 call dea <wait>
runcmd(lcmd->right);
277: 8b 43 08 mov 0x8(%ebx),%eax
27a: 89 04 24 mov %eax,(%esp)
27d: e8 2e ff ff ff call 1b0 <runcmd>
printf(2, "exec %s failed\n", ecmd->argv[0]);
break;
case REDIR:
rcmd = (struct redircmd*)cmd;
close(rcmd->fd);
282: 8b 43 14 mov 0x14(%ebx),%eax
285: 89 04 24 mov %eax,(%esp)
288: e8 7d 0b 00 00 call e0a <close>
if(open(rcmd->file, rcmd->mode) < 0){
28d: 8b 43 10 mov 0x10(%ebx),%eax
290: 89 44 24 04 mov %eax,0x4(%esp)
294: 8b 43 08 mov 0x8(%ebx),%eax
297: 89 04 24 mov %eax,(%esp)
29a: e8 83 0b 00 00 call e22 <open>
29f: 85 c0 test %eax,%eax
2a1: 78 23 js 2c6 <runcmd+0x116>
break;
case BACK:
bcmd = (struct backcmd*)cmd;
if(fork1() == 0)
runcmd(bcmd->cmd);
2a3: 8b 43 04 mov 0x4(%ebx),%eax
2a6: 89 04 24 mov %eax,(%esp)
2a9: e8 02 ff ff ff call 1b0 <runcmd>
if(cmd == 0)
exit();
switch(cmd->type){
default:
panic("runcmd");
2ae: c7 04 24 a0 12 00 00 movl $0x12a0,(%esp)
2b5: e8 a6 fe ff ff call 160 <panic>
break;
case PIPE:
pcmd = (struct pipecmd*)cmd;
if(pipe(p) < 0)
panic("pipe");
2ba: c7 04 24 c7 12 00 00 movl $0x12c7,(%esp)
2c1: e8 9a fe ff ff call 160 <panic>
case REDIR:
rcmd = (struct redircmd*)cmd;
close(rcmd->fd);
if(open(rcmd->file, rcmd->mode) < 0){
printf(2, "open %s failed\n", rcmd->file);
2c6: 8b 43 08 mov 0x8(%ebx),%eax
2c9: c7 44 24 04 b7 12 00 movl $0x12b7,0x4(%esp)
2d0: 00
2d1: c7 04 24 02 00 00 00 movl $0x2,(%esp)
2d8: 89 44 24 08 mov %eax,0x8(%esp)
2dc: e8 4f 0c 00 00 call f30 <printf>
2e1: e9 37 ff ff ff jmp 21d <runcmd+0x6d>
close(p[0]);
close(p[1]);
runcmd(pcmd->left);
}
if(fork1() == 0){
close(0);
2e6: c7 04 24 00 00 00 00 movl $0x0,(%esp)
2ed: e8 18 0b 00 00 call e0a <close>
dup(p[0]);
2f2: 8b 45 f0 mov -0x10(%ebp),%eax
2f5: 89 04 24 mov %eax,(%esp)
2f8: e8 5d 0b 00 00 call e5a <dup>
close(p[0]);
2fd: 8b 45 f0 mov -0x10(%ebp),%eax
300: 89 04 24 mov %eax,(%esp)
303: e8 02 0b 00 00 call e0a <close>
close(p[1]);
308: 8b 45 f4 mov -0xc(%ebp),%eax
30b: 89 04 24 mov %eax,(%esp)
30e: e8 f7 0a 00 00 call e0a <close>
runcmd(pcmd->right);
313: 8b 43 08 mov 0x8(%ebx),%eax
316: 89 04 24 mov %eax,(%esp)
319: e8 92 fe ff ff call 1b0 <runcmd>
case PIPE:
pcmd = (struct pipecmd*)cmd;
if(pipe(p) < 0)
panic("pipe");
if(fork1() == 0){
close(1);
31e: c7 04 24 01 00 00 00 movl $0x1,(%esp)
325: e8 e0 0a 00 00 call e0a <close>
dup(p[1]);
32a: 8b 45 f4 mov -0xc(%ebp),%eax
32d: 89 04 24 mov %eax,(%esp)
330: e8 25 0b 00 00 call e5a <dup>
close(p[0]);
335: 8b 45 f0 mov -0x10(%ebp),%eax
338: 89 04 24 mov %eax,(%esp)
33b: e8 ca 0a 00 00 call e0a <close>
close(p[1]);
340: 8b 45 f4 mov -0xc(%ebp),%eax
343: 89 04 24 mov %eax,(%esp)
346: e8 bf 0a 00 00 call e0a <close>
runcmd(pcmd->left);
34b: 8b 43 04 mov 0x4(%ebx),%eax
34e: 89 04 24 mov %eax,(%esp)
351: e8 5a fe ff ff call 1b0 <runcmd>
356: 8d 76 00 lea 0x0(%esi),%esi
359: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000360 <execcmd>:
//PAGEBREAK!
// Constructors
struct cmd*
execcmd(void)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 53 push %ebx
364: 83 ec 14 sub $0x14,%esp
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
367: c7 04 24 54 00 00 00 movl $0x54,(%esp)
36e: e8 3d 0e 00 00 call 11b0 <malloc>
memset(cmd, 0, sizeof(*cmd));
373: c7 44 24 08 54 00 00 movl $0x54,0x8(%esp)
37a: 00
37b: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
382: 00
struct cmd*
execcmd(void)
{
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
383: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
385: 89 04 24 mov %eax,(%esp)
388: e8 e3 08 00 00 call c70 <memset>
cmd->type = EXEC;
return (struct cmd*)cmd;
}
38d: 89 d8 mov %ebx,%eax
{
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = EXEC;
38f: c7 03 01 00 00 00 movl $0x1,(%ebx)
return (struct cmd*)cmd;
}
395: 83 c4 14 add $0x14,%esp
398: 5b pop %ebx
399: 5d pop %ebp
39a: c3 ret
39b: 90 nop
39c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000003a0 <redircmd>:
struct cmd*
redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)
{
3a0: 55 push %ebp
3a1: 89 e5 mov %esp,%ebp
3a3: 53 push %ebx
3a4: 83 ec 14 sub $0x14,%esp
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
3a7: c7 04 24 18 00 00 00 movl $0x18,(%esp)
3ae: e8 fd 0d 00 00 call 11b0 <malloc>
memset(cmd, 0, sizeof(*cmd));
3b3: c7 44 24 08 18 00 00 movl $0x18,0x8(%esp)
3ba: 00
3bb: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
3c2: 00
3c3: 89 04 24 mov %eax,(%esp)
struct cmd*
redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)
{
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
3c6: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
3c8: e8 a3 08 00 00 call c70 <memset>
cmd->type = REDIR;
cmd->cmd = subcmd;
3cd: 8b 45 08 mov 0x8(%ebp),%eax
{
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = REDIR;
3d0: c7 03 02 00 00 00 movl $0x2,(%ebx)
cmd->cmd = subcmd;
3d6: 89 43 04 mov %eax,0x4(%ebx)
cmd->file = file;
3d9: 8b 45 0c mov 0xc(%ebp),%eax
3dc: 89 43 08 mov %eax,0x8(%ebx)
cmd->efile = efile;
3df: 8b 45 10 mov 0x10(%ebp),%eax
3e2: 89 43 0c mov %eax,0xc(%ebx)
cmd->mode = mode;
3e5: 8b 45 14 mov 0x14(%ebp),%eax
3e8: 89 43 10 mov %eax,0x10(%ebx)
cmd->fd = fd;
3eb: 8b 45 18 mov 0x18(%ebp),%eax
3ee: 89 43 14 mov %eax,0x14(%ebx)
return (struct cmd*)cmd;
}
3f1: 83 c4 14 add $0x14,%esp
3f4: 89 d8 mov %ebx,%eax
3f6: 5b pop %ebx
3f7: 5d pop %ebp
3f8: c3 ret
3f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000400 <pipecmd>:
struct cmd*
pipecmd(struct cmd *left, struct cmd *right)
{
400: 55 push %ebp
401: 89 e5 mov %esp,%ebp
403: 53 push %ebx
404: 83 ec 14 sub $0x14,%esp
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
407: c7 04 24 0c 00 00 00 movl $0xc,(%esp)
40e: e8 9d 0d 00 00 call 11b0 <malloc>
memset(cmd, 0, sizeof(*cmd));
413: c7 44 24 08 0c 00 00 movl $0xc,0x8(%esp)
41a: 00
41b: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
422: 00
423: 89 04 24 mov %eax,(%esp)
struct cmd*
pipecmd(struct cmd *left, struct cmd *right)
{
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
426: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
428: e8 43 08 00 00 call c70 <memset>
cmd->type = PIPE;
cmd->left = left;
42d: 8b 45 08 mov 0x8(%ebp),%eax
{
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = PIPE;
430: c7 03 03 00 00 00 movl $0x3,(%ebx)
cmd->left = left;
436: 89 43 04 mov %eax,0x4(%ebx)
cmd->right = right;
439: 8b 45 0c mov 0xc(%ebp),%eax
43c: 89 43 08 mov %eax,0x8(%ebx)
return (struct cmd*)cmd;
}
43f: 83 c4 14 add $0x14,%esp
442: 89 d8 mov %ebx,%eax
444: 5b pop %ebx
445: 5d pop %ebp
446: c3 ret
447: 89 f6 mov %esi,%esi
449: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000450 <listcmd>:
struct cmd*
listcmd(struct cmd *left, struct cmd *right)
{
450: 55 push %ebp
451: 89 e5 mov %esp,%ebp
453: 53 push %ebx
454: 83 ec 14 sub $0x14,%esp
struct listcmd *cmd;
cmd = malloc(sizeof(*cmd));
457: c7 04 24 0c 00 00 00 movl $0xc,(%esp)
45e: e8 4d 0d 00 00 call 11b0 <malloc>
memset(cmd, 0, sizeof(*cmd));
463: c7 44 24 08 0c 00 00 movl $0xc,0x8(%esp)
46a: 00
46b: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
472: 00
473: 89 04 24 mov %eax,(%esp)
struct cmd*
listcmd(struct cmd *left, struct cmd *right)
{
struct listcmd *cmd;
cmd = malloc(sizeof(*cmd));
476: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
478: e8 f3 07 00 00 call c70 <memset>
cmd->type = LIST;
cmd->left = left;
47d: 8b 45 08 mov 0x8(%ebp),%eax
{
struct listcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = LIST;
480: c7 03 04 00 00 00 movl $0x4,(%ebx)
cmd->left = left;
486: 89 43 04 mov %eax,0x4(%ebx)
cmd->right = right;
489: 8b 45 0c mov 0xc(%ebp),%eax
48c: 89 43 08 mov %eax,0x8(%ebx)
return (struct cmd*)cmd;
}
48f: 83 c4 14 add $0x14,%esp
492: 89 d8 mov %ebx,%eax
494: 5b pop %ebx
495: 5d pop %ebp
496: c3 ret
497: 89 f6 mov %esi,%esi
499: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000004a0 <backcmd>:
struct cmd*
backcmd(struct cmd *subcmd)
{
4a0: 55 push %ebp
4a1: 89 e5 mov %esp,%ebp
4a3: 53 push %ebx
4a4: 83 ec 14 sub $0x14,%esp
struct backcmd *cmd;
cmd = malloc(sizeof(*cmd));
4a7: c7 04 24 08 00 00 00 movl $0x8,(%esp)
4ae: e8 fd 0c 00 00 call 11b0 <malloc>
memset(cmd, 0, sizeof(*cmd));
4b3: c7 44 24 08 08 00 00 movl $0x8,0x8(%esp)
4ba: 00
4bb: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
4c2: 00
4c3: 89 04 24 mov %eax,(%esp)
struct cmd*
backcmd(struct cmd *subcmd)
{
struct backcmd *cmd;
cmd = malloc(sizeof(*cmd));
4c6: 89 c3 mov %eax,%ebx
memset(cmd, 0, sizeof(*cmd));
4c8: e8 a3 07 00 00 call c70 <memset>
cmd->type = BACK;
cmd->cmd = subcmd;
4cd: 8b 45 08 mov 0x8(%ebp),%eax
{
struct backcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = BACK;
4d0: c7 03 05 00 00 00 movl $0x5,(%ebx)
cmd->cmd = subcmd;
4d6: 89 43 04 mov %eax,0x4(%ebx)
return (struct cmd*)cmd;
}
4d9: 83 c4 14 add $0x14,%esp
4dc: 89 d8 mov %ebx,%eax
4de: 5b pop %ebx
4df: 5d pop %ebp
4e0: c3 ret
4e1: eb 0d jmp 4f0 <gettoken>
4e3: 90 nop
4e4: 90 nop
4e5: 90 nop
4e6: 90 nop
4e7: 90 nop
4e8: 90 nop
4e9: 90 nop
4ea: 90 nop
4eb: 90 nop
4ec: 90 nop
4ed: 90 nop
4ee: 90 nop
4ef: 90 nop
000004f0 <gettoken>:
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()";
int
gettoken(char **ps, char *es, char **q, char **eq)
{
4f0: 55 push %ebp
4f1: 89 e5 mov %esp,%ebp
4f3: 57 push %edi
4f4: 56 push %esi
4f5: 53 push %ebx
4f6: 83 ec 1c sub $0x1c,%esp
char *s;
int ret;
s = *ps;
4f9: 8b 45 08 mov 0x8(%ebp),%eax
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()";
int
gettoken(char **ps, char *es, char **q, char **eq)
{
4fc: 8b 5d 0c mov 0xc(%ebp),%ebx
4ff: 8b 75 10 mov 0x10(%ebp),%esi
char *s;
int ret;
s = *ps;
502: 8b 38 mov (%eax),%edi
while(s < es && strchr(whitespace, *s))
504: 39 df cmp %ebx,%edi
506: 72 0f jb 517 <gettoken+0x27>
508: eb 24 jmp 52e <gettoken+0x3e>
50a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
s++;
510: 83 c7 01 add $0x1,%edi
{
char *s;
int ret;
s = *ps;
while(s < es && strchr(whitespace, *s))
513: 39 df cmp %ebx,%edi
515: 74 17 je 52e <gettoken+0x3e>
517: 0f be 07 movsbl (%edi),%eax
51a: c7 04 24 20 19 00 00 movl $0x1920,(%esp)
521: 89 44 24 04 mov %eax,0x4(%esp)
525: e8 66 07 00 00 call c90 <strchr>
52a: 85 c0 test %eax,%eax
52c: 75 e2 jne 510 <gettoken+0x20>
s++;
if(q)
52e: 85 f6 test %esi,%esi
530: 74 02 je 534 <gettoken+0x44>
*q = s;
532: 89 3e mov %edi,(%esi)
ret = *s;
534: 0f b6 0f movzbl (%edi),%ecx
537: 0f be f1 movsbl %cl,%esi
switch(*s){
53a: 80 f9 29 cmp $0x29,%cl
s = *ps;
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
53d: 89 f0 mov %esi,%eax
switch(*s){
53f: 7f 4f jg 590 <gettoken+0xa0>
541: 80 f9 28 cmp $0x28,%cl
544: 7d 55 jge 59b <gettoken+0xab>
546: 84 c9 test %cl,%cl
548: 0f 85 ca 00 00 00 jne 618 <gettoken+0x128>
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
s++;
break;
}
if(eq)
54e: 8b 45 14 mov 0x14(%ebp),%eax
551: 85 c0 test %eax,%eax
553: 74 05 je 55a <gettoken+0x6a>
*eq = s;
555: 8b 45 14 mov 0x14(%ebp),%eax
558: 89 38 mov %edi,(%eax)
while(s < es && strchr(whitespace, *s))
55a: 39 df cmp %ebx,%edi
55c: 72 09 jb 567 <gettoken+0x77>
55e: eb 1e jmp 57e <gettoken+0x8e>
s++;
560: 83 c7 01 add $0x1,%edi
break;
}
if(eq)
*eq = s;
while(s < es && strchr(whitespace, *s))
563: 39 df cmp %ebx,%edi
565: 74 17 je 57e <gettoken+0x8e>
567: 0f be 07 movsbl (%edi),%eax
56a: c7 04 24 20 19 00 00 movl $0x1920,(%esp)
571: 89 44 24 04 mov %eax,0x4(%esp)
575: e8 16 07 00 00 call c90 <strchr>
57a: 85 c0 test %eax,%eax
57c: 75 e2 jne 560 <gettoken+0x70>
s++;
*ps = s;
57e: 8b 45 08 mov 0x8(%ebp),%eax
581: 89 38 mov %edi,(%eax)
return ret;
}
583: 83 c4 1c add $0x1c,%esp
586: 89 f0 mov %esi,%eax
588: 5b pop %ebx
589: 5e pop %esi
58a: 5f pop %edi
58b: 5d pop %ebp
58c: c3 ret
58d: 8d 76 00 lea 0x0(%esi),%esi
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
590: 80 f9 3e cmp $0x3e,%cl
593: 75 0b jne 5a0 <gettoken+0xb0>
case '<':
s++;
break;
case '>':
s++;
if(*s == '>'){
595: 80 7f 01 3e cmpb $0x3e,0x1(%edi)
599: 74 6d je 608 <gettoken+0x118>
case '&':
case '<':
s++;
break;
case '>':
s++;
59b: 83 c7 01 add $0x1,%edi
59e: eb ae jmp 54e <gettoken+0x5e>
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
5a0: 7f 56 jg 5f8 <gettoken+0x108>
5a2: 83 e9 3b sub $0x3b,%ecx
5a5: 80 f9 01 cmp $0x1,%cl
5a8: 76 f1 jbe 59b <gettoken+0xab>
s++;
}
break;
default:
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
5aa: 39 fb cmp %edi,%ebx
5ac: 77 2b ja 5d9 <gettoken+0xe9>
5ae: 66 90 xchg %ax,%ax
5b0: eb 3b jmp 5ed <gettoken+0xfd>
5b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
5b8: 0f be 07 movsbl (%edi),%eax
5bb: c7 04 24 18 19 00 00 movl $0x1918,(%esp)
5c2: 89 44 24 04 mov %eax,0x4(%esp)
5c6: e8 c5 06 00 00 call c90 <strchr>
5cb: 85 c0 test %eax,%eax
5cd: 75 1e jne 5ed <gettoken+0xfd>
s++;
5cf: 83 c7 01 add $0x1,%edi
s++;
}
break;
default:
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
5d2: 39 df cmp %ebx,%edi
5d4: 74 17 je 5ed <gettoken+0xfd>
5d6: 0f be 07 movsbl (%edi),%eax
5d9: 89 44 24 04 mov %eax,0x4(%esp)
5dd: c7 04 24 20 19 00 00 movl $0x1920,(%esp)
5e4: e8 a7 06 00 00 call c90 <strchr>
5e9: 85 c0 test %eax,%eax
5eb: 74 cb je 5b8 <gettoken+0xc8>
ret = '+';
s++;
}
break;
default:
ret = 'a';
5ed: be 61 00 00 00 mov $0x61,%esi
5f2: e9 57 ff ff ff jmp 54e <gettoken+0x5e>
5f7: 90 nop
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
5f8: 80 f9 7c cmp $0x7c,%cl
5fb: 74 9e je 59b <gettoken+0xab>
5fd: 8d 76 00 lea 0x0(%esi),%esi
600: eb a8 jmp 5aa <gettoken+0xba>
602: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
break;
case '>':
s++;
if(*s == '>'){
ret = '+';
s++;
608: 83 c7 02 add $0x2,%edi
s++;
break;
case '>':
s++;
if(*s == '>'){
ret = '+';
60b: be 2b 00 00 00 mov $0x2b,%esi
610: e9 39 ff ff ff jmp 54e <gettoken+0x5e>
615: 8d 76 00 lea 0x0(%esi),%esi
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
618: 80 f9 26 cmp $0x26,%cl
61b: 75 8d jne 5aa <gettoken+0xba>
61d: e9 79 ff ff ff jmp 59b <gettoken+0xab>
622: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
629: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000630 <peek>:
return ret;
}
int
peek(char **ps, char *es, char *toks)
{
630: 55 push %ebp
631: 89 e5 mov %esp,%ebp
633: 57 push %edi
634: 56 push %esi
635: 53 push %ebx
636: 83 ec 1c sub $0x1c,%esp
639: 8b 7d 08 mov 0x8(%ebp),%edi
63c: 8b 75 0c mov 0xc(%ebp),%esi
char *s;
s = *ps;
63f: 8b 1f mov (%edi),%ebx
while(s < es && strchr(whitespace, *s))
641: 39 f3 cmp %esi,%ebx
643: 72 0a jb 64f <peek+0x1f>
645: eb 1f jmp 666 <peek+0x36>
647: 90 nop
s++;
648: 83 c3 01 add $0x1,%ebx
peek(char **ps, char *es, char *toks)
{
char *s;
s = *ps;
while(s < es && strchr(whitespace, *s))
64b: 39 f3 cmp %esi,%ebx
64d: 74 17 je 666 <peek+0x36>
64f: 0f be 03 movsbl (%ebx),%eax
652: c7 04 24 20 19 00 00 movl $0x1920,(%esp)
659: 89 44 24 04 mov %eax,0x4(%esp)
65d: e8 2e 06 00 00 call c90 <strchr>
662: 85 c0 test %eax,%eax
664: 75 e2 jne 648 <peek+0x18>
s++;
*ps = s;
666: 89 1f mov %ebx,(%edi)
return *s && strchr(toks, *s);
668: 0f be 13 movsbl (%ebx),%edx
66b: 31 c0 xor %eax,%eax
66d: 84 d2 test %dl,%dl
66f: 74 17 je 688 <peek+0x58>
671: 8b 45 10 mov 0x10(%ebp),%eax
674: 89 54 24 04 mov %edx,0x4(%esp)
678: 89 04 24 mov %eax,(%esp)
67b: e8 10 06 00 00 call c90 <strchr>
680: 85 c0 test %eax,%eax
682: 0f 95 c0 setne %al
685: 0f b6 c0 movzbl %al,%eax
}
688: 83 c4 1c add $0x1c,%esp
68b: 5b pop %ebx
68c: 5e pop %esi
68d: 5f pop %edi
68e: 5d pop %ebp
68f: c3 ret
00000690 <parseredirs>:
return cmd;
}
struct cmd*
parseredirs(struct cmd *cmd, char **ps, char *es)
{
690: 55 push %ebp
691: 89 e5 mov %esp,%ebp
693: 57 push %edi
694: 56 push %esi
695: 53 push %ebx
696: 83 ec 3c sub $0x3c,%esp
699: 8b 75 0c mov 0xc(%ebp),%esi
69c: 8b 5d 10 mov 0x10(%ebp),%ebx
69f: 90 nop
int tok;
char *q, *eq;
while(peek(ps, es, "<>")){
6a0: c7 44 24 08 e9 12 00 movl $0x12e9,0x8(%esp)
6a7: 00
6a8: 89 5c 24 04 mov %ebx,0x4(%esp)
6ac: 89 34 24 mov %esi,(%esp)
6af: e8 7c ff ff ff call 630 <peek>
6b4: 85 c0 test %eax,%eax
6b6: 0f 84 9c 00 00 00 je 758 <parseredirs+0xc8>
tok = gettoken(ps, es, 0, 0);
6bc: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
6c3: 00
6c4: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
6cb: 00
6cc: 89 5c 24 04 mov %ebx,0x4(%esp)
6d0: 89 34 24 mov %esi,(%esp)
6d3: e8 18 fe ff ff call 4f0 <gettoken>
if(gettoken(ps, es, &q, &eq) != 'a')
6d8: 89 5c 24 04 mov %ebx,0x4(%esp)
6dc: 89 34 24 mov %esi,(%esp)
{
int tok;
char *q, *eq;
while(peek(ps, es, "<>")){
tok = gettoken(ps, es, 0, 0);
6df: 89 c7 mov %eax,%edi
if(gettoken(ps, es, &q, &eq) != 'a')
6e1: 8d 45 e4 lea -0x1c(%ebp),%eax
6e4: 89 44 24 0c mov %eax,0xc(%esp)
6e8: 8d 45 e0 lea -0x20(%ebp),%eax
6eb: 89 44 24 08 mov %eax,0x8(%esp)
6ef: e8 fc fd ff ff call 4f0 <gettoken>
6f4: 83 f8 61 cmp $0x61,%eax
6f7: 75 6a jne 763 <parseredirs+0xd3>
panic("missing file for redirection");
switch(tok){
6f9: 83 ff 3c cmp $0x3c,%edi
6fc: 74 42 je 740 <parseredirs+0xb0>
6fe: 83 ff 3e cmp $0x3e,%edi
701: 74 05 je 708 <parseredirs+0x78>
703: 83 ff 2b cmp $0x2b,%edi
706: 75 98 jne 6a0 <parseredirs+0x10>
break;
case '>':
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
break;
case '+': // >>
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
708: c7 44 24 10 01 00 00 movl $0x1,0x10(%esp)
70f: 00
710: c7 44 24 0c 01 02 00 movl $0x201,0xc(%esp)
717: 00
718: 8b 45 e4 mov -0x1c(%ebp),%eax
71b: 89 44 24 08 mov %eax,0x8(%esp)
71f: 8b 45 e0 mov -0x20(%ebp),%eax
722: 89 44 24 04 mov %eax,0x4(%esp)
726: 8b 45 08 mov 0x8(%ebp),%eax
729: 89 04 24 mov %eax,(%esp)
72c: e8 6f fc ff ff call 3a0 <redircmd>
731: 89 45 08 mov %eax,0x8(%ebp)
break;
734: e9 67 ff ff ff jmp 6a0 <parseredirs+0x10>
739: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
tok = gettoken(ps, es, 0, 0);
if(gettoken(ps, es, &q, &eq) != 'a')
panic("missing file for redirection");
switch(tok){
case '<':
cmd = redircmd(cmd, q, eq, O_RDONLY, 0);
740: c7 44 24 10 00 00 00 movl $0x0,0x10(%esp)
747: 00
748: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
74f: 00
750: eb c6 jmp 718 <parseredirs+0x88>
752: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
break;
}
}
return cmd;
}
758: 8b 45 08 mov 0x8(%ebp),%eax
75b: 83 c4 3c add $0x3c,%esp
75e: 5b pop %ebx
75f: 5e pop %esi
760: 5f pop %edi
761: 5d pop %ebp
762: c3 ret
char *q, *eq;
while(peek(ps, es, "<>")){
tok = gettoken(ps, es, 0, 0);
if(gettoken(ps, es, &q, &eq) != 'a')
panic("missing file for redirection");
763: c7 04 24 cc 12 00 00 movl $0x12cc,(%esp)
76a: e8 f1 f9 ff ff call 160 <panic>
76f: 90 nop
00000770 <parseexec>:
return cmd;
}
struct cmd*
parseexec(char **ps, char *es)
{
770: 55 push %ebp
771: 89 e5 mov %esp,%ebp
773: 57 push %edi
774: 56 push %esi
775: 53 push %ebx
776: 83 ec 3c sub $0x3c,%esp
779: 8b 75 08 mov 0x8(%ebp),%esi
77c: 8b 7d 0c mov 0xc(%ebp),%edi
char *q, *eq;
int tok, argc;
struct execcmd *cmd;
struct cmd *ret;
if(peek(ps, es, "("))
77f: c7 44 24 08 ec 12 00 movl $0x12ec,0x8(%esp)
786: 00
787: 89 34 24 mov %esi,(%esp)
78a: 89 7c 24 04 mov %edi,0x4(%esp)
78e: e8 9d fe ff ff call 630 <peek>
793: 85 c0 test %eax,%eax
795: 0f 85 a5 00 00 00 jne 840 <parseexec+0xd0>
return parseblock(ps, es);
ret = execcmd();
79b: e8 c0 fb ff ff call 360 <execcmd>
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
7a0: 89 7c 24 08 mov %edi,0x8(%esp)
7a4: 89 74 24 04 mov %esi,0x4(%esp)
7a8: 89 04 24 mov %eax,(%esp)
struct cmd *ret;
if(peek(ps, es, "("))
return parseblock(ps, es);
ret = execcmd();
7ab: 89 c3 mov %eax,%ebx
7ad: 89 45 cc mov %eax,-0x34(%ebp)
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
7b0: e8 db fe ff ff call 690 <parseredirs>
return parseblock(ps, es);
ret = execcmd();
cmd = (struct execcmd*)ret;
argc = 0;
7b5: c7 45 d4 00 00 00 00 movl $0x0,-0x2c(%ebp)
ret = parseredirs(ret, ps, es);
7bc: 89 45 d0 mov %eax,-0x30(%ebp)
while(!peek(ps, es, "|)&;")){
7bf: eb 1d jmp 7de <parseexec+0x6e>
7c1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
cmd->argv[argc] = q;
cmd->eargv[argc] = eq;
argc++;
if(argc >= MAXARGS)
panic("too many args");
ret = parseredirs(ret, ps, es);
7c8: 8b 45 d0 mov -0x30(%ebp),%eax
7cb: 89 7c 24 08 mov %edi,0x8(%esp)
7cf: 89 74 24 04 mov %esi,0x4(%esp)
7d3: 89 04 24 mov %eax,(%esp)
7d6: e8 b5 fe ff ff call 690 <parseredirs>
7db: 89 45 d0 mov %eax,-0x30(%ebp)
ret = execcmd();
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
while(!peek(ps, es, "|)&;")){
7de: c7 44 24 08 03 13 00 movl $0x1303,0x8(%esp)
7e5: 00
7e6: 89 7c 24 04 mov %edi,0x4(%esp)
7ea: 89 34 24 mov %esi,(%esp)
7ed: e8 3e fe ff ff call 630 <peek>
7f2: 85 c0 test %eax,%eax
7f4: 75 62 jne 858 <parseexec+0xe8>
if((tok=gettoken(ps, es, &q, &eq)) == 0)
7f6: 8d 45 e4 lea -0x1c(%ebp),%eax
7f9: 89 44 24 0c mov %eax,0xc(%esp)
7fd: 8d 45 e0 lea -0x20(%ebp),%eax
800: 89 44 24 08 mov %eax,0x8(%esp)
804: 89 7c 24 04 mov %edi,0x4(%esp)
808: 89 34 24 mov %esi,(%esp)
80b: e8 e0 fc ff ff call 4f0 <gettoken>
810: 85 c0 test %eax,%eax
812: 74 44 je 858 <parseexec+0xe8>
break;
if(tok != 'a')
814: 83 f8 61 cmp $0x61,%eax
817: 75 61 jne 87a <parseexec+0x10a>
panic("syntax");
cmd->argv[argc] = q;
819: 8b 45 e0 mov -0x20(%ebp),%eax
81c: 83 c3 04 add $0x4,%ebx
cmd->eargv[argc] = eq;
argc++;
81f: 83 45 d4 01 addl $0x1,-0x2c(%ebp)
while(!peek(ps, es, "|)&;")){
if((tok=gettoken(ps, es, &q, &eq)) == 0)
break;
if(tok != 'a')
panic("syntax");
cmd->argv[argc] = q;
823: 89 03 mov %eax,(%ebx)
cmd->eargv[argc] = eq;
825: 8b 45 e4 mov -0x1c(%ebp),%eax
828: 89 43 28 mov %eax,0x28(%ebx)
argc++;
if(argc >= MAXARGS)
82b: 83 7d d4 0a cmpl $0xa,-0x2c(%ebp)
82f: 75 97 jne 7c8 <parseexec+0x58>
panic("too many args");
831: c7 04 24 f5 12 00 00 movl $0x12f5,(%esp)
838: e8 23 f9 ff ff call 160 <panic>
83d: 8d 76 00 lea 0x0(%esi),%esi
int tok, argc;
struct execcmd *cmd;
struct cmd *ret;
if(peek(ps, es, "("))
return parseblock(ps, es);
840: 89 7c 24 04 mov %edi,0x4(%esp)
844: 89 34 24 mov %esi,(%esp)
847: e8 84 01 00 00 call 9d0 <parseblock>
ret = parseredirs(ret, ps, es);
}
cmd->argv[argc] = 0;
cmd->eargv[argc] = 0;
return ret;
}
84c: 83 c4 3c add $0x3c,%esp
84f: 5b pop %ebx
850: 5e pop %esi
851: 5f pop %edi
852: 5d pop %ebp
853: c3 ret
854: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
858: 8b 45 cc mov -0x34(%ebp),%eax
85b: 8b 55 d4 mov -0x2c(%ebp),%edx
85e: 8d 04 90 lea (%eax,%edx,4),%eax
argc++;
if(argc >= MAXARGS)
panic("too many args");
ret = parseredirs(ret, ps, es);
}
cmd->argv[argc] = 0;
861: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax)
cmd->eargv[argc] = 0;
868: c7 40 2c 00 00 00 00 movl $0x0,0x2c(%eax)
return ret;
86f: 8b 45 d0 mov -0x30(%ebp),%eax
}
872: 83 c4 3c add $0x3c,%esp
875: 5b pop %ebx
876: 5e pop %esi
877: 5f pop %edi
878: 5d pop %ebp
879: c3 ret
ret = parseredirs(ret, ps, es);
while(!peek(ps, es, "|)&;")){
if((tok=gettoken(ps, es, &q, &eq)) == 0)
break;
if(tok != 'a')
panic("syntax");
87a: c7 04 24 ee 12 00 00 movl $0x12ee,(%esp)
881: e8 da f8 ff ff call 160 <panic>
886: 8d 76 00 lea 0x0(%esi),%esi
889: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000890 <parsepipe>:
return cmd;
}
struct cmd*
parsepipe(char **ps, char *es)
{
890: 55 push %ebp
891: 89 e5 mov %esp,%ebp
893: 57 push %edi
894: 56 push %esi
895: 53 push %ebx
896: 83 ec 1c sub $0x1c,%esp
899: 8b 5d 08 mov 0x8(%ebp),%ebx
89c: 8b 75 0c mov 0xc(%ebp),%esi
struct cmd *cmd;
cmd = parseexec(ps, es);
89f: 89 1c 24 mov %ebx,(%esp)
8a2: 89 74 24 04 mov %esi,0x4(%esp)
8a6: e8 c5 fe ff ff call 770 <parseexec>
if(peek(ps, es, "|")){
8ab: c7 44 24 08 08 13 00 movl $0x1308,0x8(%esp)
8b2: 00
8b3: 89 74 24 04 mov %esi,0x4(%esp)
8b7: 89 1c 24 mov %ebx,(%esp)
struct cmd*
parsepipe(char **ps, char *es)
{
struct cmd *cmd;
cmd = parseexec(ps, es);
8ba: 89 c7 mov %eax,%edi
if(peek(ps, es, "|")){
8bc: e8 6f fd ff ff call 630 <peek>
8c1: 85 c0 test %eax,%eax
8c3: 75 0b jne 8d0 <parsepipe+0x40>
gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es));
}
return cmd;
}
8c5: 83 c4 1c add $0x1c,%esp
8c8: 89 f8 mov %edi,%eax
8ca: 5b pop %ebx
8cb: 5e pop %esi
8cc: 5f pop %edi
8cd: 5d pop %ebp
8ce: c3 ret
8cf: 90 nop
{
struct cmd *cmd;
cmd = parseexec(ps, es);
if(peek(ps, es, "|")){
gettoken(ps, es, 0, 0);
8d0: 89 74 24 04 mov %esi,0x4(%esp)
8d4: 89 1c 24 mov %ebx,(%esp)
8d7: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
8de: 00
8df: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
8e6: 00
8e7: e8 04 fc ff ff call 4f0 <gettoken>
cmd = pipecmd(cmd, parsepipe(ps, es));
8ec: 89 74 24 04 mov %esi,0x4(%esp)
8f0: 89 1c 24 mov %ebx,(%esp)
8f3: e8 98 ff ff ff call 890 <parsepipe>
8f8: 89 7d 08 mov %edi,0x8(%ebp)
8fb: 89 45 0c mov %eax,0xc(%ebp)
}
return cmd;
}
8fe: 83 c4 1c add $0x1c,%esp
901: 5b pop %ebx
902: 5e pop %esi
903: 5f pop %edi
904: 5d pop %ebp
struct cmd *cmd;
cmd = parseexec(ps, es);
if(peek(ps, es, "|")){
gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es));
905: e9 f6 fa ff ff jmp 400 <pipecmd>
90a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000910 <parseline>:
return cmd;
}
struct cmd*
parseline(char **ps, char *es)
{
910: 55 push %ebp
911: 89 e5 mov %esp,%ebp
913: 57 push %edi
914: 56 push %esi
915: 53 push %ebx
916: 83 ec 1c sub $0x1c,%esp
919: 8b 5d 08 mov 0x8(%ebp),%ebx
91c: 8b 75 0c mov 0xc(%ebp),%esi
struct cmd *cmd;
cmd = parsepipe(ps, es);
91f: 89 1c 24 mov %ebx,(%esp)
922: 89 74 24 04 mov %esi,0x4(%esp)
926: e8 65 ff ff ff call 890 <parsepipe>
92b: 89 c7 mov %eax,%edi
while(peek(ps, es, "&")){
92d: eb 27 jmp 956 <parseline+0x46>
92f: 90 nop
gettoken(ps, es, 0, 0);
930: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
937: 00
938: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
93f: 00
940: 89 74 24 04 mov %esi,0x4(%esp)
944: 89 1c 24 mov %ebx,(%esp)
947: e8 a4 fb ff ff call 4f0 <gettoken>
cmd = backcmd(cmd);
94c: 89 3c 24 mov %edi,(%esp)
94f: e8 4c fb ff ff call 4a0 <backcmd>
954: 89 c7 mov %eax,%edi
parseline(char **ps, char *es)
{
struct cmd *cmd;
cmd = parsepipe(ps, es);
while(peek(ps, es, "&")){
956: c7 44 24 08 0a 13 00 movl $0x130a,0x8(%esp)
95d: 00
95e: 89 74 24 04 mov %esi,0x4(%esp)
962: 89 1c 24 mov %ebx,(%esp)
965: e8 c6 fc ff ff call 630 <peek>
96a: 85 c0 test %eax,%eax
96c: 75 c2 jne 930 <parseline+0x20>
gettoken(ps, es, 0, 0);
cmd = backcmd(cmd);
}
if(peek(ps, es, ";")){
96e: c7 44 24 08 06 13 00 movl $0x1306,0x8(%esp)
975: 00
976: 89 74 24 04 mov %esi,0x4(%esp)
97a: 89 1c 24 mov %ebx,(%esp)
97d: e8 ae fc ff ff call 630 <peek>
982: 85 c0 test %eax,%eax
984: 75 0a jne 990 <parseline+0x80>
gettoken(ps, es, 0, 0);
cmd = listcmd(cmd, parseline(ps, es));
}
return cmd;
}
986: 83 c4 1c add $0x1c,%esp
989: 89 f8 mov %edi,%eax
98b: 5b pop %ebx
98c: 5e pop %esi
98d: 5f pop %edi
98e: 5d pop %ebp
98f: c3 ret
while(peek(ps, es, "&")){
gettoken(ps, es, 0, 0);
cmd = backcmd(cmd);
}
if(peek(ps, es, ";")){
gettoken(ps, es, 0, 0);
990: 89 74 24 04 mov %esi,0x4(%esp)
994: 89 1c 24 mov %ebx,(%esp)
997: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
99e: 00
99f: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
9a6: 00
9a7: e8 44 fb ff ff call 4f0 <gettoken>
cmd = listcmd(cmd, parseline(ps, es));
9ac: 89 74 24 04 mov %esi,0x4(%esp)
9b0: 89 1c 24 mov %ebx,(%esp)
9b3: e8 58 ff ff ff call 910 <parseline>
9b8: 89 7d 08 mov %edi,0x8(%ebp)
9bb: 89 45 0c mov %eax,0xc(%ebp)
}
return cmd;
}
9be: 83 c4 1c add $0x1c,%esp
9c1: 5b pop %ebx
9c2: 5e pop %esi
9c3: 5f pop %edi
9c4: 5d pop %ebp
gettoken(ps, es, 0, 0);
cmd = backcmd(cmd);
}
if(peek(ps, es, ";")){
gettoken(ps, es, 0, 0);
cmd = listcmd(cmd, parseline(ps, es));
9c5: e9 86 fa ff ff jmp 450 <listcmd>
9ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
000009d0 <parseblock>:
return cmd;
}
struct cmd*
parseblock(char **ps, char *es)
{
9d0: 55 push %ebp
9d1: 89 e5 mov %esp,%ebp
9d3: 57 push %edi
9d4: 56 push %esi
9d5: 53 push %ebx
9d6: 83 ec 1c sub $0x1c,%esp
9d9: 8b 5d 08 mov 0x8(%ebp),%ebx
9dc: 8b 75 0c mov 0xc(%ebp),%esi
struct cmd *cmd;
if(!peek(ps, es, "("))
9df: c7 44 24 08 ec 12 00 movl $0x12ec,0x8(%esp)
9e6: 00
9e7: 89 1c 24 mov %ebx,(%esp)
9ea: 89 74 24 04 mov %esi,0x4(%esp)
9ee: e8 3d fc ff ff call 630 <peek>
9f3: 85 c0 test %eax,%eax
9f5: 74 76 je a6d <parseblock+0x9d>
panic("parseblock");
gettoken(ps, es, 0, 0);
9f7: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
9fe: 00
9ff: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
a06: 00
a07: 89 74 24 04 mov %esi,0x4(%esp)
a0b: 89 1c 24 mov %ebx,(%esp)
a0e: e8 dd fa ff ff call 4f0 <gettoken>
cmd = parseline(ps, es);
a13: 89 74 24 04 mov %esi,0x4(%esp)
a17: 89 1c 24 mov %ebx,(%esp)
a1a: e8 f1 fe ff ff call 910 <parseline>
if(!peek(ps, es, ")"))
a1f: c7 44 24 08 28 13 00 movl $0x1328,0x8(%esp)
a26: 00
a27: 89 74 24 04 mov %esi,0x4(%esp)
a2b: 89 1c 24 mov %ebx,(%esp)
struct cmd *cmd;
if(!peek(ps, es, "("))
panic("parseblock");
gettoken(ps, es, 0, 0);
cmd = parseline(ps, es);
a2e: 89 c7 mov %eax,%edi
if(!peek(ps, es, ")"))
a30: e8 fb fb ff ff call 630 <peek>
a35: 85 c0 test %eax,%eax
a37: 74 40 je a79 <parseblock+0xa9>
panic("syntax - missing )");
gettoken(ps, es, 0, 0);
a39: 89 74 24 04 mov %esi,0x4(%esp)
a3d: 89 1c 24 mov %ebx,(%esp)
a40: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
a47: 00
a48: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
a4f: 00
a50: e8 9b fa ff ff call 4f0 <gettoken>
cmd = parseredirs(cmd, ps, es);
a55: 89 74 24 08 mov %esi,0x8(%esp)
a59: 89 5c 24 04 mov %ebx,0x4(%esp)
a5d: 89 3c 24 mov %edi,(%esp)
a60: e8 2b fc ff ff call 690 <parseredirs>
return cmd;
}
a65: 83 c4 1c add $0x1c,%esp
a68: 5b pop %ebx
a69: 5e pop %esi
a6a: 5f pop %edi
a6b: 5d pop %ebp
a6c: c3 ret
parseblock(char **ps, char *es)
{
struct cmd *cmd;
if(!peek(ps, es, "("))
panic("parseblock");
a6d: c7 04 24 0c 13 00 00 movl $0x130c,(%esp)
a74: e8 e7 f6 ff ff call 160 <panic>
gettoken(ps, es, 0, 0);
cmd = parseline(ps, es);
if(!peek(ps, es, ")"))
panic("syntax - missing )");
a79: c7 04 24 17 13 00 00 movl $0x1317,(%esp)
a80: e8 db f6 ff ff call 160 <panic>
a85: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
a89: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000a90 <nulterminate>:
}
// NUL-terminate all the counted strings.
struct cmd*
nulterminate(struct cmd *cmd)
{
a90: 55 push %ebp
a91: 89 e5 mov %esp,%ebp
a93: 53 push %ebx
a94: 83 ec 14 sub $0x14,%esp
a97: 8b 5d 08 mov 0x8(%ebp),%ebx
struct execcmd *ecmd;
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
a9a: 85 db test %ebx,%ebx
a9c: 0f 84 8e 00 00 00 je b30 <nulterminate+0xa0>
return 0;
switch(cmd->type){
aa2: 83 3b 05 cmpl $0x5,(%ebx)
aa5: 77 49 ja af0 <nulterminate+0x60>
aa7: 8b 03 mov (%ebx),%eax
aa9: ff 24 85 68 13 00 00 jmp *0x1368(,%eax,4)
nulterminate(pcmd->right);
break;
case LIST:
lcmd = (struct listcmd*)cmd;
nulterminate(lcmd->left);
ab0: 8b 43 04 mov 0x4(%ebx),%eax
ab3: 89 04 24 mov %eax,(%esp)
ab6: e8 d5 ff ff ff call a90 <nulterminate>
nulterminate(lcmd->right);
abb: 8b 43 08 mov 0x8(%ebx),%eax
abe: 89 04 24 mov %eax,(%esp)
ac1: e8 ca ff ff ff call a90 <nulterminate>
break;
ac6: 89 d8 mov %ebx,%eax
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
ac8: 83 c4 14 add $0x14,%esp
acb: 5b pop %ebx
acc: 5d pop %ebp
acd: c3 ret
ace: 66 90 xchg %ax,%ax
return 0;
switch(cmd->type){
case EXEC:
ecmd = (struct execcmd*)cmd;
for(i=0; ecmd->argv[i]; i++)
ad0: 8b 4b 04 mov 0x4(%ebx),%ecx
ad3: 89 d8 mov %ebx,%eax
ad5: 85 c9 test %ecx,%ecx
ad7: 74 17 je af0 <nulterminate+0x60>
ad9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
*ecmd->eargv[i] = 0;
ae0: 8b 50 2c mov 0x2c(%eax),%edx
ae3: 83 c0 04 add $0x4,%eax
ae6: c6 02 00 movb $0x0,(%edx)
return 0;
switch(cmd->type){
case EXEC:
ecmd = (struct execcmd*)cmd;
for(i=0; ecmd->argv[i]; i++)
ae9: 8b 50 04 mov 0x4(%eax),%edx
aec: 85 d2 test %edx,%edx
aee: 75 f0 jne ae0 <nulterminate+0x50>
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
af0: 83 c4 14 add $0x14,%esp
struct redircmd *rcmd;
if(cmd == 0)
return 0;
switch(cmd->type){
af3: 89 d8 mov %ebx,%eax
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
af5: 5b pop %ebx
af6: 5d pop %ebp
af7: c3 ret
nulterminate(lcmd->right);
break;
case BACK:
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
af8: 8b 43 04 mov 0x4(%ebx),%eax
afb: 89 04 24 mov %eax,(%esp)
afe: e8 8d ff ff ff call a90 <nulterminate>
break;
}
return cmd;
}
b03: 83 c4 14 add $0x14,%esp
break;
case BACK:
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
b06: 89 d8 mov %ebx,%eax
}
return cmd;
}
b08: 5b pop %ebx
b09: 5d pop %ebp
b0a: c3 ret
b0b: 90 nop
b0c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*ecmd->eargv[i] = 0;
break;
case REDIR:
rcmd = (struct redircmd*)cmd;
nulterminate(rcmd->cmd);
b10: 8b 43 04 mov 0x4(%ebx),%eax
b13: 89 04 24 mov %eax,(%esp)
b16: e8 75 ff ff ff call a90 <nulterminate>
*rcmd->efile = 0;
b1b: 8b 43 0c mov 0xc(%ebx),%eax
b1e: c6 00 00 movb $0x0,(%eax)
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
b21: 83 c4 14 add $0x14,%esp
case REDIR:
rcmd = (struct redircmd*)cmd;
nulterminate(rcmd->cmd);
*rcmd->efile = 0;
break;
b24: 89 d8 mov %ebx,%eax
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
b26: 5b pop %ebx
b27: 5d pop %ebp
b28: c3 ret
b29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
return 0;
b30: 31 c0 xor %eax,%eax
b32: eb 94 jmp ac8 <nulterminate+0x38>
b34: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
b3a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000b40 <parsecmd>:
struct cmd *parseexec(char**, char*);
struct cmd *nulterminate(struct cmd*);
struct cmd*
parsecmd(char *s)
{
b40: 55 push %ebp
b41: 89 e5 mov %esp,%ebp
b43: 56 push %esi
b44: 53 push %ebx
b45: 83 ec 10 sub $0x10,%esp
char *es;
struct cmd *cmd;
es = s + strlen(s);
b48: 8b 5d 08 mov 0x8(%ebp),%ebx
b4b: 89 1c 24 mov %ebx,(%esp)
b4e: e8 ed 00 00 00 call c40 <strlen>
b53: 01 c3 add %eax,%ebx
cmd = parseline(&s, es);
b55: 8d 45 08 lea 0x8(%ebp),%eax
b58: 89 5c 24 04 mov %ebx,0x4(%esp)
b5c: 89 04 24 mov %eax,(%esp)
b5f: e8 ac fd ff ff call 910 <parseline>
peek(&s, es, "");
b64: c7 44 24 08 b6 12 00 movl $0x12b6,0x8(%esp)
b6b: 00
b6c: 89 5c 24 04 mov %ebx,0x4(%esp)
{
char *es;
struct cmd *cmd;
es = s + strlen(s);
cmd = parseline(&s, es);
b70: 89 c6 mov %eax,%esi
peek(&s, es, "");
b72: 8d 45 08 lea 0x8(%ebp),%eax
b75: 89 04 24 mov %eax,(%esp)
b78: e8 b3 fa ff ff call 630 <peek>
if(s != es){
b7d: 8b 45 08 mov 0x8(%ebp),%eax
b80: 39 d8 cmp %ebx,%eax
b82: 75 11 jne b95 <parsecmd+0x55>
printf(2, "leftovers: %s\n", s);
panic("syntax");
}
nulterminate(cmd);
b84: 89 34 24 mov %esi,(%esp)
b87: e8 04 ff ff ff call a90 <nulterminate>
return cmd;
}
b8c: 83 c4 10 add $0x10,%esp
b8f: 89 f0 mov %esi,%eax
b91: 5b pop %ebx
b92: 5e pop %esi
b93: 5d pop %ebp
b94: c3 ret
es = s + strlen(s);
cmd = parseline(&s, es);
peek(&s, es, "");
if(s != es){
printf(2, "leftovers: %s\n", s);
b95: 89 44 24 08 mov %eax,0x8(%esp)
b99: c7 44 24 04 2a 13 00 movl $0x132a,0x4(%esp)
ba0: 00
ba1: c7 04 24 02 00 00 00 movl $0x2,(%esp)
ba8: e8 83 03 00 00 call f30 <printf>
panic("syntax");
bad: c7 04 24 ee 12 00 00 movl $0x12ee,(%esp)
bb4: e8 a7 f5 ff ff call 160 <panic>
bb9: 66 90 xchg %ax,%ax
bbb: 66 90 xchg %ax,%ax
bbd: 66 90 xchg %ax,%ax
bbf: 90 nop
00000bc0 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
bc0: 55 push %ebp
bc1: 89 e5 mov %esp,%ebp
bc3: 8b 45 08 mov 0x8(%ebp),%eax
bc6: 8b 4d 0c mov 0xc(%ebp),%ecx
bc9: 53 push %ebx
char *os;
os = s;
while((*s++ = *t++) != 0)
bca: 89 c2 mov %eax,%edx
bcc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bd0: 83 c1 01 add $0x1,%ecx
bd3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
bd7: 83 c2 01 add $0x1,%edx
bda: 84 db test %bl,%bl
bdc: 88 5a ff mov %bl,-0x1(%edx)
bdf: 75 ef jne bd0 <strcpy+0x10>
;
return os;
}
be1: 5b pop %ebx
be2: 5d pop %ebp
be3: c3 ret
be4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
bea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000bf0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
bf0: 55 push %ebp
bf1: 89 e5 mov %esp,%ebp
bf3: 8b 55 08 mov 0x8(%ebp),%edx
bf6: 53 push %ebx
bf7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
bfa: 0f b6 02 movzbl (%edx),%eax
bfd: 84 c0 test %al,%al
bff: 74 2d je c2e <strcmp+0x3e>
c01: 0f b6 19 movzbl (%ecx),%ebx
c04: 38 d8 cmp %bl,%al
c06: 74 0e je c16 <strcmp+0x26>
c08: eb 2b jmp c35 <strcmp+0x45>
c0a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
c10: 38 c8 cmp %cl,%al
c12: 75 15 jne c29 <strcmp+0x39>
p++, q++;
c14: 89 d9 mov %ebx,%ecx
c16: 83 c2 01 add $0x1,%edx
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
c19: 0f b6 02 movzbl (%edx),%eax
p++, q++;
c1c: 8d 59 01 lea 0x1(%ecx),%ebx
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
c1f: 0f b6 49 01 movzbl 0x1(%ecx),%ecx
c23: 84 c0 test %al,%al
c25: 75 e9 jne c10 <strcmp+0x20>
c27: 31 c0 xor %eax,%eax
p++, q++;
return (uchar)*p - (uchar)*q;
c29: 29 c8 sub %ecx,%eax
}
c2b: 5b pop %ebx
c2c: 5d pop %ebp
c2d: c3 ret
c2e: 0f b6 09 movzbl (%ecx),%ecx
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
c31: 31 c0 xor %eax,%eax
c33: eb f4 jmp c29 <strcmp+0x39>
c35: 0f b6 cb movzbl %bl,%ecx
c38: eb ef jmp c29 <strcmp+0x39>
c3a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000c40 <strlen>:
return (uchar)*p - (uchar)*q;
}
uint
strlen(char *s)
{
c40: 55 push %ebp
c41: 89 e5 mov %esp,%ebp
c43: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
c46: 80 39 00 cmpb $0x0,(%ecx)
c49: 74 12 je c5d <strlen+0x1d>
c4b: 31 d2 xor %edx,%edx
c4d: 8d 76 00 lea 0x0(%esi),%esi
c50: 83 c2 01 add $0x1,%edx
c53: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
c57: 89 d0 mov %edx,%eax
c59: 75 f5 jne c50 <strlen+0x10>
;
return n;
}
c5b: 5d pop %ebp
c5c: c3 ret
uint
strlen(char *s)
{
int n;
for(n = 0; s[n]; n++)
c5d: 31 c0 xor %eax,%eax
;
return n;
}
c5f: 5d pop %ebp
c60: c3 ret
c61: eb 0d jmp c70 <memset>
c63: 90 nop
c64: 90 nop
c65: 90 nop
c66: 90 nop
c67: 90 nop
c68: 90 nop
c69: 90 nop
c6a: 90 nop
c6b: 90 nop
c6c: 90 nop
c6d: 90 nop
c6e: 90 nop
c6f: 90 nop
00000c70 <memset>:
void*
memset(void *dst, int c, uint n)
{
c70: 55 push %ebp
c71: 89 e5 mov %esp,%ebp
c73: 8b 55 08 mov 0x8(%ebp),%edx
c76: 57 push %edi
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
c77: 8b 4d 10 mov 0x10(%ebp),%ecx
c7a: 8b 45 0c mov 0xc(%ebp),%eax
c7d: 89 d7 mov %edx,%edi
c7f: fc cld
c80: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
c82: 89 d0 mov %edx,%eax
c84: 5f pop %edi
c85: 5d pop %ebp
c86: c3 ret
c87: 89 f6 mov %esi,%esi
c89: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000c90 <strchr>:
char*
strchr(const char *s, char c)
{
c90: 55 push %ebp
c91: 89 e5 mov %esp,%ebp
c93: 8b 45 08 mov 0x8(%ebp),%eax
c96: 53 push %ebx
c97: 8b 55 0c mov 0xc(%ebp),%edx
for(; *s; s++)
c9a: 0f b6 18 movzbl (%eax),%ebx
c9d: 84 db test %bl,%bl
c9f: 74 1d je cbe <strchr+0x2e>
if(*s == c)
ca1: 38 d3 cmp %dl,%bl
ca3: 89 d1 mov %edx,%ecx
ca5: 75 0d jne cb4 <strchr+0x24>
ca7: eb 17 jmp cc0 <strchr+0x30>
ca9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
cb0: 38 ca cmp %cl,%dl
cb2: 74 0c je cc0 <strchr+0x30>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
cb4: 83 c0 01 add $0x1,%eax
cb7: 0f b6 10 movzbl (%eax),%edx
cba: 84 d2 test %dl,%dl
cbc: 75 f2 jne cb0 <strchr+0x20>
if(*s == c)
return (char*)s;
return 0;
cbe: 31 c0 xor %eax,%eax
}
cc0: 5b pop %ebx
cc1: 5d pop %ebp
cc2: c3 ret
cc3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000cd0 <gets>:
char*
gets(char *buf, int max)
{
cd0: 55 push %ebp
cd1: 89 e5 mov %esp,%ebp
cd3: 57 push %edi
cd4: 56 push %esi
int i, cc;
char c;
for(i=0; i+1 < max; ){
cd5: 31 f6 xor %esi,%esi
return 0;
}
char*
gets(char *buf, int max)
{
cd7: 53 push %ebx
cd8: 83 ec 2c sub $0x2c,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
cdb: 8d 7d e7 lea -0x19(%ebp),%edi
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
cde: eb 31 jmp d11 <gets+0x41>
cc = read(0, &c, 1);
ce0: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
ce7: 00
ce8: 89 7c 24 04 mov %edi,0x4(%esp)
cec: c7 04 24 00 00 00 00 movl $0x0,(%esp)
cf3: e8 02 01 00 00 call dfa <read>
if(cc < 1)
cf8: 85 c0 test %eax,%eax
cfa: 7e 1d jle d19 <gets+0x49>
break;
buf[i++] = c;
cfc: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
d00: 89 de mov %ebx,%esi
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
d02: 8b 55 08 mov 0x8(%ebp),%edx
if(c == '\n' || c == '\r')
d05: 3c 0d cmp $0xd,%al
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
d07: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1)
if(c == '\n' || c == '\r')
d0b: 74 0c je d19 <gets+0x49>
d0d: 3c 0a cmp $0xa,%al
d0f: 74 08 je d19 <gets+0x49>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
d11: 8d 5e 01 lea 0x1(%esi),%ebx
d14: 3b 5d 0c cmp 0xc(%ebp),%ebx
d17: 7c c7 jl ce0 <gets+0x10>
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
d19: 8b 45 08 mov 0x8(%ebp),%eax
d1c: c6 04 30 00 movb $0x0,(%eax,%esi,1)
return buf;
}
d20: 83 c4 2c add $0x2c,%esp
d23: 5b pop %ebx
d24: 5e pop %esi
d25: 5f pop %edi
d26: 5d pop %ebp
d27: c3 ret
d28: 90 nop
d29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000d30 <stat>:
int
stat(char *n, struct stat *st)
{
d30: 55 push %ebp
d31: 89 e5 mov %esp,%ebp
d33: 56 push %esi
d34: 53 push %ebx
d35: 83 ec 10 sub $0x10,%esp
int fd;
int r;
fd = open(n, O_RDONLY);
d38: 8b 45 08 mov 0x8(%ebp),%eax
d3b: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
d42: 00
d43: 89 04 24 mov %eax,(%esp)
d46: e8 d7 00 00 00 call e22 <open>
if(fd < 0)
d4b: 85 c0 test %eax,%eax
stat(char *n, struct stat *st)
{
int fd;
int r;
fd = open(n, O_RDONLY);
d4d: 89 c3 mov %eax,%ebx
if(fd < 0)
d4f: 78 27 js d78 <stat+0x48>
return -1;
r = fstat(fd, st);
d51: 8b 45 0c mov 0xc(%ebp),%eax
d54: 89 1c 24 mov %ebx,(%esp)
d57: 89 44 24 04 mov %eax,0x4(%esp)
d5b: e8 da 00 00 00 call e3a <fstat>
close(fd);
d60: 89 1c 24 mov %ebx,(%esp)
int r;
fd = open(n, O_RDONLY);
if(fd < 0)
return -1;
r = fstat(fd, st);
d63: 89 c6 mov %eax,%esi
close(fd);
d65: e8 a0 00 00 00 call e0a <close>
return r;
d6a: 89 f0 mov %esi,%eax
}
d6c: 83 c4 10 add $0x10,%esp
d6f: 5b pop %ebx
d70: 5e pop %esi
d71: 5d pop %ebp
d72: c3 ret
d73: 90 nop
d74: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
int fd;
int r;
fd = open(n, O_RDONLY);
if(fd < 0)
return -1;
d78: b8 ff ff ff ff mov $0xffffffff,%eax
d7d: eb ed jmp d6c <stat+0x3c>
d7f: 90 nop
00000d80 <atoi>:
return r;
}
int
atoi(const char *s)
{
d80: 55 push %ebp
d81: 89 e5 mov %esp,%ebp
d83: 8b 4d 08 mov 0x8(%ebp),%ecx
d86: 53 push %ebx
int n;
n = 0;
while('0' <= *s && *s <= '9')
d87: 0f be 11 movsbl (%ecx),%edx
d8a: 8d 42 d0 lea -0x30(%edx),%eax
d8d: 3c 09 cmp $0x9,%al
int
atoi(const char *s)
{
int n;
n = 0;
d8f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
d94: 77 17 ja dad <atoi+0x2d>
d96: 66 90 xchg %ax,%ax
n = n*10 + *s++ - '0';
d98: 83 c1 01 add $0x1,%ecx
d9b: 8d 04 80 lea (%eax,%eax,4),%eax
d9e: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
da2: 0f be 11 movsbl (%ecx),%edx
da5: 8d 5a d0 lea -0x30(%edx),%ebx
da8: 80 fb 09 cmp $0x9,%bl
dab: 76 eb jbe d98 <atoi+0x18>
n = n*10 + *s++ - '0';
return n;
}
dad: 5b pop %ebx
dae: 5d pop %ebp
daf: c3 ret
00000db0 <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
db0: 55 push %ebp
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
db1: 31 d2 xor %edx,%edx
return n;
}
void*
memmove(void *vdst, void *vsrc, int n)
{
db3: 89 e5 mov %esp,%ebp
db5: 56 push %esi
db6: 8b 45 08 mov 0x8(%ebp),%eax
db9: 53 push %ebx
dba: 8b 5d 10 mov 0x10(%ebp),%ebx
dbd: 8b 75 0c mov 0xc(%ebp),%esi
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
dc0: 85 db test %ebx,%ebx
dc2: 7e 12 jle dd6 <memmove+0x26>
dc4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
dc8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
dcc: 88 0c 10 mov %cl,(%eax,%edx,1)
dcf: 83 c2 01 add $0x1,%edx
{
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
dd2: 39 da cmp %ebx,%edx
dd4: 75 f2 jne dc8 <memmove+0x18>
*dst++ = *src++;
return vdst;
}
dd6: 5b pop %ebx
dd7: 5e pop %esi
dd8: 5d pop %ebp
dd9: c3 ret
00000dda <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
dda: b8 01 00 00 00 mov $0x1,%eax
ddf: cd 40 int $0x40
de1: c3 ret
00000de2 <exit>:
SYSCALL(exit)
de2: b8 02 00 00 00 mov $0x2,%eax
de7: cd 40 int $0x40
de9: c3 ret
00000dea <wait>:
SYSCALL(wait)
dea: b8 03 00 00 00 mov $0x3,%eax
def: cd 40 int $0x40
df1: c3 ret
00000df2 <pipe>:
SYSCALL(pipe)
df2: b8 04 00 00 00 mov $0x4,%eax
df7: cd 40 int $0x40
df9: c3 ret
00000dfa <read>:
SYSCALL(read)
dfa: b8 05 00 00 00 mov $0x5,%eax
dff: cd 40 int $0x40
e01: c3 ret
00000e02 <write>:
SYSCALL(write)
e02: b8 10 00 00 00 mov $0x10,%eax
e07: cd 40 int $0x40
e09: c3 ret
00000e0a <close>:
SYSCALL(close)
e0a: b8 15 00 00 00 mov $0x15,%eax
e0f: cd 40 int $0x40
e11: c3 ret
00000e12 <kill>:
SYSCALL(kill)
e12: b8 06 00 00 00 mov $0x6,%eax
e17: cd 40 int $0x40
e19: c3 ret
00000e1a <exec>:
SYSCALL(exec)
e1a: b8 07 00 00 00 mov $0x7,%eax
e1f: cd 40 int $0x40
e21: c3 ret
00000e22 <open>:
SYSCALL(open)
e22: b8 0f 00 00 00 mov $0xf,%eax
e27: cd 40 int $0x40
e29: c3 ret
00000e2a <mknod>:
SYSCALL(mknod)
e2a: b8 11 00 00 00 mov $0x11,%eax
e2f: cd 40 int $0x40
e31: c3 ret
00000e32 <unlink>:
SYSCALL(unlink)
e32: b8 12 00 00 00 mov $0x12,%eax
e37: cd 40 int $0x40
e39: c3 ret
00000e3a <fstat>:
SYSCALL(fstat)
e3a: b8 08 00 00 00 mov $0x8,%eax
e3f: cd 40 int $0x40
e41: c3 ret
00000e42 <link>:
SYSCALL(link)
e42: b8 13 00 00 00 mov $0x13,%eax
e47: cd 40 int $0x40
e49: c3 ret
00000e4a <mkdir>:
SYSCALL(mkdir)
e4a: b8 14 00 00 00 mov $0x14,%eax
e4f: cd 40 int $0x40
e51: c3 ret
00000e52 <chdir>:
SYSCALL(chdir)
e52: b8 09 00 00 00 mov $0x9,%eax
e57: cd 40 int $0x40
e59: c3 ret
00000e5a <dup>:
SYSCALL(dup)
e5a: b8 0a 00 00 00 mov $0xa,%eax
e5f: cd 40 int $0x40
e61: c3 ret
00000e62 <getpid>:
SYSCALL(getpid)
e62: b8 0b 00 00 00 mov $0xb,%eax
e67: cd 40 int $0x40
e69: c3 ret
00000e6a <sbrk>:
SYSCALL(sbrk)
e6a: b8 0c 00 00 00 mov $0xc,%eax
e6f: cd 40 int $0x40
e71: c3 ret
00000e72 <sleep>:
SYSCALL(sleep)
e72: b8 0d 00 00 00 mov $0xd,%eax
e77: cd 40 int $0x40
e79: c3 ret
00000e7a <uptime>:
SYSCALL(uptime)
e7a: b8 0e 00 00 00 mov $0xe,%eax
e7f: cd 40 int $0x40
e81: c3 ret
00000e82 <lotto>:
SYSCALL(lotto)
e82: b8 16 00 00 00 mov $0x16,%eax
e87: cd 40 int $0x40
e89: c3 ret
e8a: 66 90 xchg %ax,%ax
e8c: 66 90 xchg %ax,%ax
e8e: 66 90 xchg %ax,%ax
00000e90 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
e90: 55 push %ebp
e91: 89 e5 mov %esp,%ebp
e93: 57 push %edi
e94: 56 push %esi
e95: 89 c6 mov %eax,%esi
e97: 53 push %ebx
e98: 83 ec 4c sub $0x4c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
e9b: 8b 5d 08 mov 0x8(%ebp),%ebx
e9e: 85 db test %ebx,%ebx
ea0: 74 09 je eab <printint+0x1b>
ea2: 89 d0 mov %edx,%eax
ea4: c1 e8 1f shr $0x1f,%eax
ea7: 84 c0 test %al,%al
ea9: 75 75 jne f20 <printint+0x90>
neg = 1;
x = -xx;
} else {
x = xx;
eab: 89 d0 mov %edx,%eax
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
ead: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
eb4: 89 75 c0 mov %esi,-0x40(%ebp)
x = -xx;
} else {
x = xx;
}
i = 0;
eb7: 31 ff xor %edi,%edi
eb9: 89 ce mov %ecx,%esi
ebb: 8d 5d d7 lea -0x29(%ebp),%ebx
ebe: eb 02 jmp ec2 <printint+0x32>
do{
buf[i++] = digits[x % base];
ec0: 89 cf mov %ecx,%edi
ec2: 31 d2 xor %edx,%edx
ec4: f7 f6 div %esi
ec6: 8d 4f 01 lea 0x1(%edi),%ecx
ec9: 0f b6 92 87 13 00 00 movzbl 0x1387(%edx),%edx
}while((x /= base) != 0);
ed0: 85 c0 test %eax,%eax
x = xx;
}
i = 0;
do{
buf[i++] = digits[x % base];
ed2: 88 14 0b mov %dl,(%ebx,%ecx,1)
}while((x /= base) != 0);
ed5: 75 e9 jne ec0 <printint+0x30>
if(neg)
ed7: 8b 55 c4 mov -0x3c(%ebp),%edx
x = xx;
}
i = 0;
do{
buf[i++] = digits[x % base];
eda: 89 c8 mov %ecx,%eax
edc: 8b 75 c0 mov -0x40(%ebp),%esi
}while((x /= base) != 0);
if(neg)
edf: 85 d2 test %edx,%edx
ee1: 74 08 je eeb <printint+0x5b>
buf[i++] = '-';
ee3: 8d 4f 02 lea 0x2(%edi),%ecx
ee6: c6 44 05 d8 2d movb $0x2d,-0x28(%ebp,%eax,1)
while(--i >= 0)
eeb: 8d 79 ff lea -0x1(%ecx),%edi
eee: 66 90 xchg %ax,%ax
ef0: 0f b6 44 3d d8 movzbl -0x28(%ebp,%edi,1),%eax
ef5: 83 ef 01 sub $0x1,%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
ef8: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
eff: 00
f00: 89 5c 24 04 mov %ebx,0x4(%esp)
f04: 89 34 24 mov %esi,(%esp)
f07: 88 45 d7 mov %al,-0x29(%ebp)
f0a: e8 f3 fe ff ff call e02 <write>
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
f0f: 83 ff ff cmp $0xffffffff,%edi
f12: 75 dc jne ef0 <printint+0x60>
putc(fd, buf[i]);
}
f14: 83 c4 4c add $0x4c,%esp
f17: 5b pop %ebx
f18: 5e pop %esi
f19: 5f pop %edi
f1a: 5d pop %ebp
f1b: c3 ret
f1c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
uint x;
neg = 0;
if(sgn && xx < 0){
neg = 1;
x = -xx;
f20: 89 d0 mov %edx,%eax
f22: f7 d8 neg %eax
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
neg = 1;
f24: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
f2b: eb 87 jmp eb4 <printint+0x24>
f2d: 8d 76 00 lea 0x0(%esi),%esi
00000f30 <printf>:
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
f30: 55 push %ebp
f31: 89 e5 mov %esp,%ebp
f33: 57 push %edi
char *s;
int c, i, state;
uint *ap;
state = 0;
f34: 31 ff xor %edi,%edi
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
f36: 56 push %esi
f37: 53 push %ebx
f38: 83 ec 3c sub $0x3c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
f3b: 8b 5d 0c mov 0xc(%ebp),%ebx
char *s;
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
f3e: 8d 45 10 lea 0x10(%ebp),%eax
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
f41: 8b 75 08 mov 0x8(%ebp),%esi
char *s;
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
f44: 89 45 d4 mov %eax,-0x2c(%ebp)
for(i = 0; fmt[i]; i++){
f47: 0f b6 13 movzbl (%ebx),%edx
f4a: 83 c3 01 add $0x1,%ebx
f4d: 84 d2 test %dl,%dl
f4f: 75 39 jne f8a <printf+0x5a>
f51: e9 c2 00 00 00 jmp 1018 <printf+0xe8>
f56: 66 90 xchg %ax,%ax
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
f58: 83 fa 25 cmp $0x25,%edx
f5b: 0f 84 bf 00 00 00 je 1020 <printf+0xf0>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
f61: 8d 45 e2 lea -0x1e(%ebp),%eax
f64: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
f6b: 00
f6c: 89 44 24 04 mov %eax,0x4(%esp)
f70: 89 34 24 mov %esi,(%esp)
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
state = '%';
} else {
putc(fd, c);
f73: 88 55 e2 mov %dl,-0x1e(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
f76: e8 87 fe ff ff call e02 <write>
f7b: 83 c3 01 add $0x1,%ebx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
f7e: 0f b6 53 ff movzbl -0x1(%ebx),%edx
f82: 84 d2 test %dl,%dl
f84: 0f 84 8e 00 00 00 je 1018 <printf+0xe8>
c = fmt[i] & 0xff;
if(state == 0){
f8a: 85 ff test %edi,%edi
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
f8c: 0f be c2 movsbl %dl,%eax
if(state == 0){
f8f: 74 c7 je f58 <printf+0x28>
if(c == '%'){
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
f91: 83 ff 25 cmp $0x25,%edi
f94: 75 e5 jne f7b <printf+0x4b>
if(c == 'd'){
f96: 83 fa 64 cmp $0x64,%edx
f99: 0f 84 31 01 00 00 je 10d0 <printf+0x1a0>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
f9f: 25 f7 00 00 00 and $0xf7,%eax
fa4: 83 f8 70 cmp $0x70,%eax
fa7: 0f 84 83 00 00 00 je 1030 <printf+0x100>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
fad: 83 fa 73 cmp $0x73,%edx
fb0: 0f 84 a2 00 00 00 je 1058 <printf+0x128>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
fb6: 83 fa 63 cmp $0x63,%edx
fb9: 0f 84 35 01 00 00 je 10f4 <printf+0x1c4>
putc(fd, *ap);
ap++;
} else if(c == '%'){
fbf: 83 fa 25 cmp $0x25,%edx
fc2: 0f 84 e0 00 00 00 je 10a8 <printf+0x178>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
fc8: 8d 45 e6 lea -0x1a(%ebp),%eax
fcb: 83 c3 01 add $0x1,%ebx
fce: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
fd5: 00
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
fd6: 31 ff xor %edi,%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
fd8: 89 44 24 04 mov %eax,0x4(%esp)
fdc: 89 34 24 mov %esi,(%esp)
fdf: 89 55 d0 mov %edx,-0x30(%ebp)
fe2: c6 45 e6 25 movb $0x25,-0x1a(%ebp)
fe6: e8 17 fe ff ff call e02 <write>
} else if(c == '%'){
putc(fd, c);
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
feb: 8b 55 d0 mov -0x30(%ebp),%edx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
fee: 8d 45 e7 lea -0x19(%ebp),%eax
ff1: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
ff8: 00
ff9: 89 44 24 04 mov %eax,0x4(%esp)
ffd: 89 34 24 mov %esi,(%esp)
} else if(c == '%'){
putc(fd, c);
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
1000: 88 55 e7 mov %dl,-0x19(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
1003: e8 fa fd ff ff call e02 <write>
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
1008: 0f b6 53 ff movzbl -0x1(%ebx),%edx
100c: 84 d2 test %dl,%dl
100e: 0f 85 76 ff ff ff jne f8a <printf+0x5a>
1014: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
putc(fd, c);
}
state = 0;
}
}
}
1018: 83 c4 3c add $0x3c,%esp
101b: 5b pop %ebx
101c: 5e pop %esi
101d: 5f pop %edi
101e: 5d pop %ebp
101f: c3 ret
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
state = '%';
1020: bf 25 00 00 00 mov $0x25,%edi
1025: e9 51 ff ff ff jmp f7b <printf+0x4b>
102a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
1030: 8b 45 d4 mov -0x2c(%ebp),%eax
1033: b9 10 00 00 00 mov $0x10,%ecx
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
1038: 31 ff xor %edi,%edi
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
103a: c7 04 24 00 00 00 00 movl $0x0,(%esp)
1041: 8b 10 mov (%eax),%edx
1043: 89 f0 mov %esi,%eax
1045: e8 46 fe ff ff call e90 <printint>
ap++;
104a: 83 45 d4 04 addl $0x4,-0x2c(%ebp)
104e: e9 28 ff ff ff jmp f7b <printf+0x4b>
1053: 90 nop
1054: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
} else if(c == 's'){
s = (char*)*ap;
1058: 8b 45 d4 mov -0x2c(%ebp),%eax
ap++;
105b: 83 45 d4 04 addl $0x4,-0x2c(%ebp)
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
s = (char*)*ap;
105f: 8b 38 mov (%eax),%edi
ap++;
if(s == 0)
s = "(null)";
1061: b8 80 13 00 00 mov $0x1380,%eax
1066: 85 ff test %edi,%edi
1068: 0f 44 f8 cmove %eax,%edi
while(*s != 0){
106b: 0f b6 07 movzbl (%edi),%eax
106e: 84 c0 test %al,%al
1070: 74 2a je 109c <printf+0x16c>
1072: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
1078: 88 45 e3 mov %al,-0x1d(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
107b: 8d 45 e3 lea -0x1d(%ebp),%eax
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
107e: 83 c7 01 add $0x1,%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
1081: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
1088: 00
1089: 89 44 24 04 mov %eax,0x4(%esp)
108d: 89 34 24 mov %esi,(%esp)
1090: e8 6d fd ff ff call e02 <write>
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
1095: 0f b6 07 movzbl (%edi),%eax
1098: 84 c0 test %al,%al
109a: 75 dc jne 1078 <printf+0x148>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
109c: 31 ff xor %edi,%edi
109e: e9 d8 fe ff ff jmp f7b <printf+0x4b>
10a3: 90 nop
10a4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
10a8: 8d 45 e5 lea -0x1b(%ebp),%eax
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
10ab: 31 ff xor %edi,%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
10ad: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
10b4: 00
10b5: 89 44 24 04 mov %eax,0x4(%esp)
10b9: 89 34 24 mov %esi,(%esp)
10bc: c6 45 e5 25 movb $0x25,-0x1b(%ebp)
10c0: e8 3d fd ff ff call e02 <write>
10c5: e9 b1 fe ff ff jmp f7b <printf+0x4b>
10ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
} else {
putc(fd, c);
}
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
10d0: 8b 45 d4 mov -0x2c(%ebp),%eax
10d3: b9 0a 00 00 00 mov $0xa,%ecx
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
10d8: 66 31 ff xor %di,%di
} else {
putc(fd, c);
}
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
10db: c7 04 24 01 00 00 00 movl $0x1,(%esp)
10e2: 8b 10 mov (%eax),%edx
10e4: 89 f0 mov %esi,%eax
10e6: e8 a5 fd ff ff call e90 <printint>
ap++;
10eb: 83 45 d4 04 addl $0x4,-0x2c(%ebp)
10ef: e9 87 fe ff ff jmp f7b <printf+0x4b>
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
putc(fd, *ap);
10f4: 8b 45 d4 mov -0x2c(%ebp),%eax
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
10f7: 31 ff xor %edi,%edi
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
putc(fd, *ap);
10f9: 8b 00 mov (%eax),%eax
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
10fb: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
1102: 00
1103: 89 34 24 mov %esi,(%esp)
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
putc(fd, *ap);
1106: 88 45 e4 mov %al,-0x1c(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
1109: 8d 45 e4 lea -0x1c(%ebp),%eax
110c: 89 44 24 04 mov %eax,0x4(%esp)
1110: e8 ed fc ff ff call e02 <write>
putc(fd, *s);
s++;
}
} else if(c == 'c'){
putc(fd, *ap);
ap++;
1115: 83 45 d4 04 addl $0x4,-0x2c(%ebp)
1119: e9 5d fe ff ff jmp f7b <printf+0x4b>
111e: 66 90 xchg %ax,%ax
00001120 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
1120: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1121: a1 a4 19 00 00 mov 0x19a4,%eax
static Header base;
static Header *freep;
void
free(void *ap)
{
1126: 89 e5 mov %esp,%ebp
1128: 57 push %edi
1129: 56 push %esi
112a: 53 push %ebx
112b: 8b 5d 08 mov 0x8(%ebp),%ebx
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
112e: 8b 08 mov (%eax),%ecx
void
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
1130: 8d 53 f8 lea -0x8(%ebx),%edx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1133: 39 d0 cmp %edx,%eax
1135: 72 11 jb 1148 <free+0x28>
1137: 90 nop
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
1138: 39 c8 cmp %ecx,%eax
113a: 72 04 jb 1140 <free+0x20>
113c: 39 ca cmp %ecx,%edx
113e: 72 10 jb 1150 <free+0x30>
1140: 89 c8 mov %ecx,%eax
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1142: 39 d0 cmp %edx,%eax
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
1144: 8b 08 mov (%eax),%ecx
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
1146: 73 f0 jae 1138 <free+0x18>
1148: 39 ca cmp %ecx,%edx
114a: 72 04 jb 1150 <free+0x30>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
114c: 39 c8 cmp %ecx,%eax
114e: 72 f0 jb 1140 <free+0x20>
break;
if(bp + bp->s.size == p->s.ptr){
1150: 8b 73 fc mov -0x4(%ebx),%esi
1153: 8d 3c f2 lea (%edx,%esi,8),%edi
1156: 39 cf cmp %ecx,%edi
1158: 74 1e je 1178 <free+0x58>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
115a: 89 4b f8 mov %ecx,-0x8(%ebx)
if(p + p->s.size == bp){
115d: 8b 48 04 mov 0x4(%eax),%ecx
1160: 8d 34 c8 lea (%eax,%ecx,8),%esi
1163: 39 f2 cmp %esi,%edx
1165: 74 28 je 118f <free+0x6f>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
1167: 89 10 mov %edx,(%eax)
freep = p;
1169: a3 a4 19 00 00 mov %eax,0x19a4
}
116e: 5b pop %ebx
116f: 5e pop %esi
1170: 5f pop %edi
1171: 5d pop %ebp
1172: c3 ret
1173: 90 nop
1174: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
bp->s.size += p->s.ptr->s.size;
1178: 03 71 04 add 0x4(%ecx),%esi
117b: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
117e: 8b 08 mov (%eax),%ecx
1180: 8b 09 mov (%ecx),%ecx
1182: 89 4b f8 mov %ecx,-0x8(%ebx)
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
1185: 8b 48 04 mov 0x4(%eax),%ecx
1188: 8d 34 c8 lea (%eax,%ecx,8),%esi
118b: 39 f2 cmp %esi,%edx
118d: 75 d8 jne 1167 <free+0x47>
p->s.size += bp->s.size;
118f: 03 4b fc add -0x4(%ebx),%ecx
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
freep = p;
1192: a3 a4 19 00 00 mov %eax,0x19a4
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
p->s.size += bp->s.size;
1197: 89 48 04 mov %ecx,0x4(%eax)
p->s.ptr = bp->s.ptr;
119a: 8b 53 f8 mov -0x8(%ebx),%edx
119d: 89 10 mov %edx,(%eax)
} else
p->s.ptr = bp;
freep = p;
}
119f: 5b pop %ebx
11a0: 5e pop %esi
11a1: 5f pop %edi
11a2: 5d pop %ebp
11a3: c3 ret
11a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
11aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000011b0 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
11b0: 55 push %ebp
11b1: 89 e5 mov %esp,%ebp
11b3: 57 push %edi
11b4: 56 push %esi
11b5: 53 push %ebx
11b6: 83 ec 1c sub $0x1c,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
11b9: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
11bc: 8b 1d a4 19 00 00 mov 0x19a4,%ebx
malloc(uint nbytes)
{
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
11c2: 8d 48 07 lea 0x7(%eax),%ecx
11c5: c1 e9 03 shr $0x3,%ecx
if((prevp = freep) == 0){
11c8: 85 db test %ebx,%ebx
malloc(uint nbytes)
{
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
11ca: 8d 71 01 lea 0x1(%ecx),%esi
if((prevp = freep) == 0){
11cd: 0f 84 9b 00 00 00 je 126e <malloc+0xbe>
11d3: 8b 13 mov (%ebx),%edx
11d5: 8b 7a 04 mov 0x4(%edx),%edi
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
11d8: 39 fe cmp %edi,%esi
11da: 76 64 jbe 1240 <malloc+0x90>
11dc: 8d 04 f5 00 00 00 00 lea 0x0(,%esi,8),%eax
morecore(uint nu)
{
char *p;
Header *hp;
if(nu < 4096)
11e3: bb 00 80 00 00 mov $0x8000,%ebx
11e8: 89 45 e4 mov %eax,-0x1c(%ebp)
11eb: eb 0e jmp 11fb <malloc+0x4b>
11ed: 8d 76 00 lea 0x0(%esi),%esi
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
11f0: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
11f2: 8b 78 04 mov 0x4(%eax),%edi
11f5: 39 fe cmp %edi,%esi
11f7: 76 4f jbe 1248 <malloc+0x98>
11f9: 89 c2 mov %eax,%edx
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
11fb: 3b 15 a4 19 00 00 cmp 0x19a4,%edx
1201: 75 ed jne 11f0 <malloc+0x40>
morecore(uint nu)
{
char *p;
Header *hp;
if(nu < 4096)
1203: 8b 45 e4 mov -0x1c(%ebp),%eax
1206: 81 fe 00 10 00 00 cmp $0x1000,%esi
120c: bf 00 10 00 00 mov $0x1000,%edi
1211: 0f 43 fe cmovae %esi,%edi
1214: 0f 42 c3 cmovb %ebx,%eax
nu = 4096;
p = sbrk(nu * sizeof(Header));
1217: 89 04 24 mov %eax,(%esp)
121a: e8 4b fc ff ff call e6a <sbrk>
if(p == (char*)-1)
121f: 83 f8 ff cmp $0xffffffff,%eax
1222: 74 18 je 123c <malloc+0x8c>
return 0;
hp = (Header*)p;
hp->s.size = nu;
1224: 89 78 04 mov %edi,0x4(%eax)
free((void*)(hp + 1));
1227: 83 c0 08 add $0x8,%eax
122a: 89 04 24 mov %eax,(%esp)
122d: e8 ee fe ff ff call 1120 <free>
return freep;
1232: 8b 15 a4 19 00 00 mov 0x19a4,%edx
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
1238: 85 d2 test %edx,%edx
123a: 75 b4 jne 11f0 <malloc+0x40>
return 0;
123c: 31 c0 xor %eax,%eax
123e: eb 20 jmp 1260 <malloc+0xb0>
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
1240: 89 d0 mov %edx,%eax
1242: 89 da mov %ebx,%edx
1244: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
if(p->s.size == nunits)
1248: 39 fe cmp %edi,%esi
124a: 74 1c je 1268 <malloc+0xb8>
prevp->s.ptr = p->s.ptr;
else {
p->s.size -= nunits;
124c: 29 f7 sub %esi,%edi
124e: 89 78 04 mov %edi,0x4(%eax)
p += p->s.size;
1251: 8d 04 f8 lea (%eax,%edi,8),%eax
p->s.size = nunits;
1254: 89 70 04 mov %esi,0x4(%eax)
}
freep = prevp;
1257: 89 15 a4 19 00 00 mov %edx,0x19a4
return (void*)(p + 1);
125d: 83 c0 08 add $0x8,%eax
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
}
1260: 83 c4 1c add $0x1c,%esp
1263: 5b pop %ebx
1264: 5e pop %esi
1265: 5f pop %edi
1266: 5d pop %ebp
1267: c3 ret
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
prevp->s.ptr = p->s.ptr;
1268: 8b 08 mov (%eax),%ecx
126a: 89 0a mov %ecx,(%edx)
126c: eb e9 jmp 1257 <malloc+0xa7>
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
126e: c7 05 a4 19 00 00 a8 movl $0x19a8,0x19a4
1275: 19 00 00
base.s.size = 0;
1278: ba a8 19 00 00 mov $0x19a8,%edx
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
127d: c7 05 a8 19 00 00 a8 movl $0x19a8,0x19a8
1284: 19 00 00
base.s.size = 0;
1287: c7 05 ac 19 00 00 00 movl $0x0,0x19ac
128e: 00 00 00
1291: e9 46 ff ff ff jmp 11dc <malloc+0x2c>
|
;[]-----------------------------------------------------------------[]
;| TAN.ASM -- trigonometric function |
;[]-----------------------------------------------------------------[]
;
; C/C++ Run Time Library - Version 10.0
;
; Copyright (c) 1991, 2000 by Inprise Corporation
; All Rights Reserved.
;
; $Revision: 9.1 $
;----------------------------------------------------------------------
; function(s)
; tan - trigonometric tangent function
;----------------------------------------------------------------------
include RULES.ASI
include _MATH.INC
; Segments Definitions
Header@
Data_Seg@
NANTRIG dw 00000H, 00000H, 00420H, 07FF8H
Data_EndS@
;--------------------------------------------------------------------------
;
;Name tan - trigonometric tangent function
;
;Usage double tan(double x);
;
;Prototype in math.h
;
;Description tan returns the tangent of the input value. Angles are
; specified in radians.
;
;Return value tan returns any value for valid angles.
; For very large arguments (magnitude 2^53 or greater) all
; precision is lost. This occurs "silently" since the ANSI C
; spec does not specify an error return.
;
;--------------------------------------------------------------------------
Code_Seg@
Func@ tan, _EXPFUNC, _RTLENTRY, <double x>
Link@ ebx
FLD x.double
mov ax, 7FF0h
and ax, W0 (x [6]) ; extract the exponent field
cmp ax, (53 * 16) + 3FF0h ; biased version of exponent 53
jae tan_tooLarge
FPTAN
FSTP ST(0) ; Remove extraneous 1.0 on the stack
; since FPTAN pushes 1.0 after result
tan_end:
Unlink@ ebx
Return@
tan_tooLarge: ; total loss of precision
FSTP ST(0) ; pop x from stack
; return __matherr (TLOSS, "tan", &x, NULL, *((double *) NANTRIG));
matherr TLOSS, tan, x, NULL, NANTRIG
jmp tan_end
EndFunc@ tan
Code_EndS@
end
|
;
; Maskierung.asm
;
; Created: 07/05/2021 14:26:56
; Author : Markus
;
.INCLUDE "m16def.inc"
init:
; Setup Bit-Mask
LDI R16, 0b00001111 ; low-nibbl Mask
LDI R17, 0b11110000 ; high-nibbl Mask
LDI R18, 0 ; Register for low nibbl mask
LDI R19, 0 ; Register for high nibbl mask
LDI R20, 0xff ; Initialize PORTA
out DDRA, R20
LDI R21, 0x00 ; Initialize PORTB
out DDRB, R21
main:
in R18, PORTA ; Save PORTA Results
in R19, PORTA
AND R18, R16 ; Mask Results
AND R19, R17
ADD R18, R19 ; Add both results
out PORTB, R18 ; Write results to PORTB
|
# mp_limb_t mulredc13(mp_limb_t * z, const mp_limb_t * x, const mp_limb_t * y,
# const mp_limb_t *m, mp_limb_t inv_m);
#
# Stack:
# inv_m ## parameters
# m
# y
# x
# z (4*(2k+7))%esp
# ??? (1 limb???)
# ebp ## pushed registers (4*(2k+5))%esp
# edi
# esi
# ebx
# ... ## counter (1 mp_limb_t) (4*(2k+1))%esp
# ... ## tmp space (2*k+1 mp_limb_t)
include(`config.m4')
TEXT
GLOBL GSYM_PREFIX`'mulredc13
TYPE(GSYM_PREFIX`'mulredc13,`function')
GSYM_PREFIX`'mulredc13:
pushl %ebp
pushl %edi
pushl %esi
pushl %ebx
subl $112, %esp
movl %esp, %edi
### set tmp[0..2k+1[ to 0
movl $0, (%edi)
movl $0, 4(%edi)
movl $0, 8(%edi)
movl $0, 12(%edi)
movl $0, 16(%edi)
movl $0, 20(%edi)
movl $0, 24(%edi)
movl $0, 28(%edi)
movl $0, 32(%edi)
movl $0, 36(%edi)
movl $0, 40(%edi)
movl $0, 44(%edi)
movl $0, 48(%edi)
movl $0, 52(%edi)
movl $0, 56(%edi)
movl $0, 60(%edi)
movl $0, 64(%edi)
movl $0, 68(%edi)
movl $0, 72(%edi)
movl $0, 76(%edi)
movl $0, 80(%edi)
movl $0, 84(%edi)
movl $0, 88(%edi)
movl $0, 92(%edi)
movl $0, 96(%edi)
movl $0, 100(%edi)
movl $0, 104(%edi)
###########################################
movl $13, 108(%esp)
.align 32
Loop:
## compute u and store in %ebp
movl 136(%esp), %eax
movl 140(%esp), %esi
movl (%eax), %eax
mull (%esi)
addl (%edi), %eax
mull 148(%esp)
movl %eax, %ebp
movl 144(%esp), %esi
### addmul1: src[0] is (%esi)
### dst[0] is (%edi)
### mult is %ebp
### k is 13
### kills %eax, %edx and mmx regs
### dst[0,k[ += mult*src[0,k[ plus carry put in ecx
pxor %mm0, %mm0
movd %ebp, %mm7
movd (%esi), %mm1
movd (%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, (%edi)
psrlq $32, %mm0
movd 4(%esi), %mm1
movd 4(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 4(%edi)
psrlq $32, %mm0
movd 8(%esi), %mm1
movd 8(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 8(%edi)
psrlq $32, %mm0
movd 12(%esi), %mm1
movd 12(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 12(%edi)
psrlq $32, %mm0
movd 16(%esi), %mm1
movd 16(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 16(%edi)
psrlq $32, %mm0
movd 20(%esi), %mm1
movd 20(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 20(%edi)
psrlq $32, %mm0
movd 24(%esi), %mm1
movd 24(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 24(%edi)
psrlq $32, %mm0
movd 28(%esi), %mm1
movd 28(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 28(%edi)
psrlq $32, %mm0
movd 32(%esi), %mm1
movd 32(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 32(%edi)
psrlq $32, %mm0
movd 36(%esi), %mm1
movd 36(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 36(%edi)
psrlq $32, %mm0
movd 40(%esi), %mm1
movd 40(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 40(%edi)
psrlq $32, %mm0
movd 44(%esi), %mm1
movd 44(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 44(%edi)
psrlq $32, %mm0
movd 48(%esi), %mm1
movd 48(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 48(%edi)
psrlq $32, %mm0
movd %mm0, %ecx
### carry limb is in %ecx
addl %ecx, 52(%edi)
adcl $0, 56(%edi)
movl 136(%esp), %eax
movl (%eax), %ebp
movl 140(%esp), %esi
### addmul1: src[0] is (%esi)
### dst[0] is (%edi)
### mult is %ebp
### k is 13
### kills %eax, %edx and mmx regs
### dst[0,k[ += mult*src[0,k[ plus carry put in ecx
pxor %mm0, %mm0
movd %ebp, %mm7
movd (%esi), %mm1
movd (%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, (%edi)
psrlq $32, %mm0
movd 4(%esi), %mm1
movd 4(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 4(%edi)
psrlq $32, %mm0
movd 8(%esi), %mm1
movd 8(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 8(%edi)
psrlq $32, %mm0
movd 12(%esi), %mm1
movd 12(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 12(%edi)
psrlq $32, %mm0
movd 16(%esi), %mm1
movd 16(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 16(%edi)
psrlq $32, %mm0
movd 20(%esi), %mm1
movd 20(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 20(%edi)
psrlq $32, %mm0
movd 24(%esi), %mm1
movd 24(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 24(%edi)
psrlq $32, %mm0
movd 28(%esi), %mm1
movd 28(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 28(%edi)
psrlq $32, %mm0
movd 32(%esi), %mm1
movd 32(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 32(%edi)
psrlq $32, %mm0
movd 36(%esi), %mm1
movd 36(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 36(%edi)
psrlq $32, %mm0
movd 40(%esi), %mm1
movd 40(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 40(%edi)
psrlq $32, %mm0
movd 44(%esi), %mm1
movd 44(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 44(%edi)
psrlq $32, %mm0
movd 48(%esi), %mm1
movd 48(%edi), %mm2
pmuludq %mm7, %mm1
paddq %mm1, %mm2
paddq %mm2, %mm0
movd %mm0, 48(%edi)
psrlq $32, %mm0
movd %mm0, %ecx
### carry limb is in %ecx
addl %ecx, 52(%edi)
adcl $0, 56(%edi)
addl $4, 136(%esp)
addl $4, %edi
decl 108(%esp)
jnz Loop
###########################################
### Copy result in z
movl 132(%esp), %ebx
movl (%edi), %eax
movl %eax, (%ebx)
movl 4(%edi), %eax
movl %eax, 4(%ebx)
movl 8(%edi), %eax
movl %eax, 8(%ebx)
movl 12(%edi), %eax
movl %eax, 12(%ebx)
movl 16(%edi), %eax
movl %eax, 16(%ebx)
movl 20(%edi), %eax
movl %eax, 20(%ebx)
movl 24(%edi), %eax
movl %eax, 24(%ebx)
movl 28(%edi), %eax
movl %eax, 28(%ebx)
movl 32(%edi), %eax
movl %eax, 32(%ebx)
movl 36(%edi), %eax
movl %eax, 36(%ebx)
movl 40(%edi), %eax
movl %eax, 40(%ebx)
movl 44(%edi), %eax
movl %eax, 44(%ebx)
movl 48(%edi), %eax
movl %eax, 48(%ebx)
movl 52(%edi), %eax # carry
addl $112, %esp
popl %ebx
popl %esi
popl %edi
popl %ebp
emms
ret
|
#include <iostream>
using namespace std;
int Find_Set(int *parent,int x);
void Union_set(int *parent, int x, int y);
int main()
{
int n, m;
cin >> n >> m; // m = number of operations , n = number of sets
int *parent = new int[n + 1];
for (int i = 0; i <= n; i++)
parent[i] = i;
for (int i = 0; i < m; i++)
{
int input, a, b;
cin >> input >> a >> b;
if (input == 1) // input==1 ==> Find_set
{
if (Find_Set(parent,b) == Find_Set(parent,a))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
else // input==0 ==> Union_set
{
Union_set(parent,a, b);
}
}
delete[]parent;
return 0;
}
int Find_Set(int *parent,int x)
{
while (parent[x] != x)
{
x = parent[x];
}
return x;
}
void Union_set(int *parent, int x, int y)
{
x = Find_Set(parent,x);
y = Find_Set(parent,y);
if (x != y)
{
parent[y] = x;
}
}
|
dp2(8) g35<1>.xF g34<4>.xyyyF g34<4>.xyyyF { align16 1Q };
dp2(8) g4<1>.yF g1<0>.xyyyF g1.4<0>.xyyyF { align16 NoDDClr 1Q };
dp2(8) g4<1>.zF g1<0>.xyyyF g1.4<0>.zwwwF { align16 NoDDClr,NoDDChk 1Q };
dp2(8) g4<1>.wF g1<0>.xyyyF g2<0>.xyyyF { align16 NoDDChk 1Q };
|
; A053508: a(n) = binomial(n-1,3)*n^(n-4).
; Submitted by Jon Maiga
; 0,0,0,1,20,360,6860,143360,3306744,84000000,2338460520,70946979840,2332989862060,82726831323136,3148511132812500,128071114403348480,5546563698427324720,254873089955815096320,12387799656377835411984,635043840000000000000000,34247814444393128760004740,1938473622423383014042501120,114907825228489694265339069980,7119400019295709106141864656896,460204319097101688385009765625000,30984285902271589350058538880204800,2169401437660809387806829054607735800,157731568725052910039152355368029388800
sub $0,3
mov $1,-4
sub $1,$0
pow $1,$0
mov $2,-4
bin $2,$0
mul $1,$2
mov $0,$1
|
;;; traps.asm
;;; Sets up the interrupt service routines (system calls)
;; fill all traps with the halt routine
.orig 0x20 ; traps go from 0x20 to 0xff, 0xe0 traps total
.blkw 0xe0, 0xfd70 ; halt address
;; fill standard traps with addresses of their routines
.orig 0x20
.fill 0x0400 ; 0x20, getc
.fill 0x0430 ; 0x21, out
.fill 0x0450 ; 0x22, puts
.fill 0x04a0 ; 0x23, in
|
/*
Author: Jason Williams <[email protected]>
Copyright (c) 2015 Cromulence LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
extern "C"
{
#include "cgc_stdio.h"
#include "cgc_stdlib.h"
#include "cgc_string.h"
}
#include "cgc_common.h"
#if 0
CUtil::String ReadLine( void )
{
char pszLine[512];
char c;
cgc_size_t num_bytes;
cgc_size_t pos;
for ( pos = 0; pos < 511; pos++ )
{
if ( receive( STDIN, &c, 1, &num_bytes ) != 0 )
_terminate( -1 );
if ( num_bytes == 0 )
_terminate( -1 );
if ( c == '\n' )
break;
pszLine[pos] = c;
}
pszLine[pos] = '\0';
return CUtil::String(pszLine);
}
#else
char cgc_g_szLineBuffer[4096+1];
uint32_t cgc_g_lineLength = 0;
CUtil::String ReadLine( void )
{
uint32_t maxLen = 4096;
char *pszLine = new char[maxLen+1];
bool bLineFound = false;
uint32_t lastScanPos = 0;
while ( 1 )
{
uint32_t pos;
for ( pos = lastScanPos; pos < cgc_g_lineLength; pos++ )
{
if ( cgc_g_szLineBuffer[pos] == '\n' )
{
bLineFound = true;
break;
}
}
if ( bLineFound )
{
// Include newline
lastScanPos = pos;
break;
}
if ( pos == cgc_g_lineLength && cgc_g_lineLength == maxLen )
{
// Exceeded max length!
lastScanPos = pos;
break;
}
lastScanPos = pos;
cgc_size_t num_bytes;
uint32_t readRemaining = (maxLen - pos);
if ( cgc_receive( STDIN, cgc_g_szLineBuffer+pos, readRemaining, &num_bytes ) != 0 )
cgc__terminate( -1 );
if ( num_bytes == 0 )
cgc__terminate( -1 );
cgc_g_lineLength += num_bytes;
}
cgc_memcpy( pszLine, cgc_g_szLineBuffer, lastScanPos );
pszLine[lastScanPos] = '\0';
CUtil::String sLine = pszLine;
delete pszLine;
uint32_t copyToPos = 0;
uint32_t copyFromPos = lastScanPos+1;
if ( bLineFound )
{
for ( uint32_t copyAmount = 0; copyAmount < (cgc_g_lineLength-(lastScanPos+1)); copyAmount++ )
cgc_g_szLineBuffer[copyToPos++] = cgc_g_szLineBuffer[copyFromPos++];
cgc_g_lineLength -= (lastScanPos+1);
}
else
{
for ( uint32_t copyAmount = 0; copyAmount < (cgc_g_lineLength-lastScanPos); copyAmount++ )
cgc_g_szLineBuffer[copyToPos++] = cgc_g_szLineBuffer[copyFromPos++];
cgc_g_lineLength -= (lastScanPos);
}
return (sLine);
}
#endif
bool HexCharToInt( char c, uint8_t &outValue )
{
if ( c >= 'A' && c <= 'F' )
outValue = (10 + (c - 'A'));
else if ( c >= 'a' && c <= 'f' )
outValue = (10 + (c -'a'));
else if ( c >= '0' && c <= '9' )
outValue = (c - '0');
else
return (false);
return (true);
}
void PrintHexBytes( uint8_t *pData, uint32_t dataLen )
{
for ( uint32_t i = 0; i < dataLen; i++ )
cgc_printf( "$x$x", (pData[i] >> 4) & 0xF, pData[i] & 0xF );
cgc_printf( "\n" );
}
|
; A010981: Binomial coefficient C(n,28).
; 1,29,435,4495,35960,237336,1344904,6724520,30260340,124403620,472733756,1676056044,5586853480,17620076360,52860229080,151532656696,416714805914,1103068603890,2818953098830,6973199770790,16735679449896,39049918716424,88749815264600,196793068630200,426384982032100,903936161908052,1877405874732108,3824345300380220,7648690600760440,15033633249770520,29065024282889672,55317304280338408,103719945525634515,191724747789809255,349615716557887465,629308289804197437,1118770292985239888,1965407271460556560
add $0,28
bin $0,28
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>gettid() -> str
Invokes the syscall gettid.
See 'man 2 gettid' for more information.
Arguments:
Returns:
pid_t
</%docstring>
<%page args=""/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = []
argument_values = []
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_gettid']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* gettid(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
; int find_file (char *filename, struct flos_file file);
; CALLER linkage for function pointers
;
; $Id: find_file.asm,v 1.4 2016-06-22 22:13:09 dom Exp $
;
SECTION code_clib
PUBLIC find_file
PUBLIC _find_file
EXTERN asm_find_file
find_file:
_find_file:
pop bc
pop de ; ptr to file struct
pop hl ; ptr to file name
push hl
push de
push bc
jp asm_find_file
|
; void *sms_set_vram(unsigned char c, unsigned int n)
SECTION code_clib
SECTION code_crt_common
PUBLIC _sms_set_vram_callee
EXTERN asm_sms_set_vram
_sms_set_vram_callee:
pop hl
dec sp
pop af
pop bc
push hl
jp asm_sms_set_vram
|
//===--- ImportType.cpp - Import Clang Types ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements support for importing Clang types as Swift types.
//
//===----------------------------------------------------------------------===//
#include "CFTypeInfo.h"
#include "ClangDiagnosticConsumer.h"
#include "ImporterImpl.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsClangImporter.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Types.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Parse/Token.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/TypeVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace importer;
/// Given that a type is the result of a special typedef import, was
/// it originally a CF pointer?
static bool isImportedCFPointer(clang::QualType clangType, Type type) {
return (clangType->isPointerType() &&
(type->is<ClassType>() || type->isClassExistentialType()));
}
bool ClangImporter::Implementation::isOverAligned(const clang::TypeDecl *decl) {
auto type = getClangASTContext().getTypeDeclType(decl);
return isOverAligned(type);
}
bool ClangImporter::Implementation::isOverAligned(clang::QualType type) {
auto align = getClangASTContext().getTypeAlignInChars(type);
return align > clang::CharUnits::fromQuantity(MaximumAlignment);
}
namespace {
/// Various types that we want to do something interesting to after
/// importing them.
struct ImportHint {
enum ImportHintKind {
/// There is nothing special about the source type.
None,
/// The source type is 'void'.
Void,
/// The source type is 'BOOL' or 'Boolean' -- a type mapped to Swift's
/// 'Bool'.
Boolean,
/// The source type is 'NSUInteger'.
NSUInteger,
/// The source type is 'va_list'.
VAList,
/// The source type is an Objective-C class type bridged to a Swift
/// type.
ObjCBridged,
/// The source type is an Objective-C object pointer type.
ObjCPointer,
/// The source type is a CF object pointer type.
CFPointer,
/// The source type is a block pointer type.
Block,
/// The source type is a function pointer type.
CFunctionPointer,
/// The source type is any other pointer type.
OtherPointer,
};
ImportHintKind Kind;
/// The type to which the imported type is bridged.
Type BridgedType;
/// Allow conversion from an import hint to an import hint kind,
/// which is useful for switches and comparisons.
operator ImportHintKind() const { return Kind; }
ImportHint(ImportHintKind kind) : Kind(kind) {
assert(kind != ObjCBridged &&
"Bridged entry point requires a bridged type");
}
ImportHint(ImportHintKind kind, Type bridgedType)
: Kind(kind), BridgedType(bridgedType) {
assert(kind == ImportHint::ObjCBridged && "Wrong kind for bridged type");
}
};
bool canImportAsOptional(ImportHint hint) {
// See also ClangImporter.cpp's canImportAsOptional.
switch (hint) {
case ImportHint::None:
case ImportHint::Boolean:
case ImportHint::NSUInteger:
case ImportHint::Void:
return false;
case ImportHint::Block:
case ImportHint::CFPointer:
case ImportHint::ObjCBridged:
case ImportHint::ObjCPointer:
case ImportHint::CFunctionPointer:
case ImportHint::OtherPointer:
case ImportHint::VAList:
return true;
}
llvm_unreachable("Invalid ImportHint.");
}
struct ImportResult {
Type AbstractType;
ImportHint Hint;
/*implicit*/ ImportResult(Type type = Type(),
ImportHint hint = ImportHint::None)
: AbstractType(type), Hint(hint) {}
/*implicit*/ ImportResult(TypeBase *type,
ImportHint hint = ImportHint::None)
: AbstractType(type), Hint(hint) {}
explicit operator bool() const { return (bool) AbstractType; }
};
class SwiftTypeConverter :
public clang::TypeVisitor<SwiftTypeConverter, ImportResult>
{
ClangImporter::Implementation &Impl;
bool AllowNSUIntegerAsInt;
Bridgeability Bridging;
public:
SwiftTypeConverter(ClangImporter::Implementation &impl,
bool allowNSUIntegerAsInt,
Bridgeability bridging)
: Impl(impl), AllowNSUIntegerAsInt(allowNSUIntegerAsInt),
Bridging(bridging) {}
using TypeVisitor::Visit;
ImportResult Visit(clang::QualType type) {
auto IR = Visit(type.getTypePtr());
return IR;
}
ImportResult VisitType(const Type*) = delete;
#define DEPENDENT_TYPE(Class, Base) \
ImportResult Visit##Class##Type(const clang::Class##Type *) { \
llvm_unreachable("Dependent types cannot be converted"); \
}
#define TYPE(Class, Base)
#include "clang/AST/TypeNodes.inc"
// Given a loaded type like CInt, look through the type alias sugar that the
// stdlib uses to show the underlying type. We want to import the signature
// of the exit(3) libc function as "func exit(Int32)", not as
// "func exit(CInt)".
static Type unwrapCType(Type T) {
// Handle missing or invalid stdlib declarations
if (!T || T->hasError())
return Type();
if (auto *NAT = dyn_cast<TypeAliasType>(T.getPointer()))
return NAT->getSinglyDesugaredType();
return T;
}
ImportResult VisitBuiltinType(const clang::BuiltinType *type) {
switch (type->getKind()) {
case clang::BuiltinType::Void:
return { Type(), ImportHint::Void };
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) \
case clang::BuiltinType::CLANG_BUILTIN_KIND: \
return unwrapCType(Impl.getNamedSwiftType(Impl.getStdlibModule(), \
#SWIFT_TYPE_NAME));
#include "swift/ClangImporter/BuiltinMappedTypes.def"
// Types that cannot be mapped into Swift, and probably won't ever be.
case clang::BuiltinType::Dependent:
case clang::BuiltinType::ARCUnbridgedCast:
case clang::BuiltinType::BoundMember:
case clang::BuiltinType::BuiltinFn:
case clang::BuiltinType::Overload:
case clang::BuiltinType::PseudoObject:
case clang::BuiltinType::UnknownAny:
return Type();
// FIXME: Types that can be mapped, but aren't yet.
case clang::BuiltinType::ShortAccum:
case clang::BuiltinType::Accum:
case clang::BuiltinType::LongAccum:
case clang::BuiltinType::UShortAccum:
case clang::BuiltinType::UAccum:
case clang::BuiltinType::ULongAccum:
case clang::BuiltinType::ShortFract:
case clang::BuiltinType::Fract:
case clang::BuiltinType::LongFract:
case clang::BuiltinType::UShortFract:
case clang::BuiltinType::UFract:
case clang::BuiltinType::ULongFract:
case clang::BuiltinType::SatShortAccum:
case clang::BuiltinType::SatAccum:
case clang::BuiltinType::SatLongAccum:
case clang::BuiltinType::SatUShortAccum:
case clang::BuiltinType::SatUAccum:
case clang::BuiltinType::SatULongAccum:
case clang::BuiltinType::SatShortFract:
case clang::BuiltinType::SatFract:
case clang::BuiltinType::SatLongFract:
case clang::BuiltinType::SatUShortFract:
case clang::BuiltinType::SatUFract:
case clang::BuiltinType::SatULongFract:
case clang::BuiltinType::Float128:
case clang::BuiltinType::NullPtr:
case clang::BuiltinType::Char8:
return Type();
// Objective-C types that aren't mapped directly; rather, pointers to
// these types will be mapped.
case clang::BuiltinType::ObjCClass:
case clang::BuiltinType::ObjCId:
case clang::BuiltinType::ObjCSel:
return Type();
// OpenCL types that don't have Swift equivalents.
case clang::BuiltinType::OCLImage1dRO:
case clang::BuiltinType::OCLImage1dRW:
case clang::BuiltinType::OCLImage1dWO:
case clang::BuiltinType::OCLImage1dArrayRO:
case clang::BuiltinType::OCLImage1dArrayRW:
case clang::BuiltinType::OCLImage1dArrayWO:
case clang::BuiltinType::OCLImage1dBufferRO:
case clang::BuiltinType::OCLImage1dBufferRW:
case clang::BuiltinType::OCLImage1dBufferWO:
case clang::BuiltinType::OCLImage2dRO:
case clang::BuiltinType::OCLImage2dRW:
case clang::BuiltinType::OCLImage2dWO:
case clang::BuiltinType::OCLImage2dArrayRO:
case clang::BuiltinType::OCLImage2dArrayRW:
case clang::BuiltinType::OCLImage2dArrayWO:
case clang::BuiltinType::OCLImage2dDepthRO:
case clang::BuiltinType::OCLImage2dDepthRW:
case clang::BuiltinType::OCLImage2dDepthWO:
case clang::BuiltinType::OCLImage2dArrayDepthRO:
case clang::BuiltinType::OCLImage2dArrayDepthRW:
case clang::BuiltinType::OCLImage2dArrayDepthWO:
case clang::BuiltinType::OCLImage2dMSAARO:
case clang::BuiltinType::OCLImage2dMSAARW:
case clang::BuiltinType::OCLImage2dMSAAWO:
case clang::BuiltinType::OCLImage2dArrayMSAARO:
case clang::BuiltinType::OCLImage2dArrayMSAARW:
case clang::BuiltinType::OCLImage2dArrayMSAAWO:
case clang::BuiltinType::OCLImage2dMSAADepthRO:
case clang::BuiltinType::OCLImage2dMSAADepthRW:
case clang::BuiltinType::OCLImage2dMSAADepthWO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRW:
case clang::BuiltinType::OCLImage2dArrayMSAADepthWO:
case clang::BuiltinType::OCLImage3dRO:
case clang::BuiltinType::OCLImage3dRW:
case clang::BuiltinType::OCLImage3dWO:
case clang::BuiltinType::OCLSampler:
case clang::BuiltinType::OCLEvent:
case clang::BuiltinType::OCLClkEvent:
case clang::BuiltinType::OCLQueue:
case clang::BuiltinType::OCLReserveID:
case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
return Type();
// OpenMP types that don't have Swift equivalents.
case clang::BuiltinType::OMPArraySection:
return Type();
// SVE builtin types that don't have Swift equivalents.
case clang::BuiltinType::SveInt8:
case clang::BuiltinType::SveInt16:
case clang::BuiltinType::SveInt32:
case clang::BuiltinType::SveInt64:
case clang::BuiltinType::SveUint8:
case clang::BuiltinType::SveUint16:
case clang::BuiltinType::SveUint32:
case clang::BuiltinType::SveUint64:
case clang::BuiltinType::SveFloat16:
case clang::BuiltinType::SveFloat32:
case clang::BuiltinType::SveFloat64:
case clang::BuiltinType::SveBool:
return Type();
}
llvm_unreachable("Invalid BuiltinType.");
}
ImportResult VisitPipeType(const clang::PipeType *) {
// OpenCL types are not supported in Swift.
return Type();
}
ImportResult VisitComplexType(const clang::ComplexType *type) {
// FIXME: Implement once Complex is in the library.
return Type();
}
ImportResult VisitAtomicType(const clang::AtomicType *type) {
// FIXME: handle pointers and fields of atomic type
return Type();
}
ImportResult VisitMemberPointerType(const clang::MemberPointerType *type) {
return Type();
}
ImportResult VisitPointerType(const clang::PointerType *type) {
auto pointeeQualType = type->getPointeeType();
auto quals = pointeeQualType.getQualifiers();
// Special case for NSZone*, which has its own Swift wrapper.
if (const clang::RecordType *pointee =
pointeeQualType->getAsStructureType()) {
if (pointee && !pointee->getDecl()->isCompleteDefinition() &&
pointee->getDecl()->getName() == "_NSZone") {
Identifier Id_ObjectiveC = Impl.SwiftContext.Id_ObjectiveC;
ModuleDecl *objCModule = Impl.SwiftContext.getLoadedModule(Id_ObjectiveC);
Type wrapperTy = Impl.getNamedSwiftType(
objCModule,
Impl.SwiftContext.getSwiftName(
KnownFoundationEntity::NSZone));
if (wrapperTy)
return {wrapperTy, ImportHint::OtherPointer};
}
}
// Import 'void*' as 'UnsafeMutableRawPointer' and 'const void*' as
// 'UnsafeRawPointer'. This is Swift's version of an untyped pointer. Note
// that 'Unsafe[Mutable]Pointer<T>' implicitly converts to
// 'Unsafe[Mutable]RawPointer' for interoperability.
if (pointeeQualType->isVoidType()) {
auto pointerTypeDecl =
(quals.hasConst()
? Impl.SwiftContext.getUnsafeRawPointerDecl()
: Impl.SwiftContext.getUnsafeMutableRawPointerDecl());
if (!pointerTypeDecl)
return Type();
return {pointerTypeDecl->getDeclaredType(),
ImportHint::OtherPointer};
}
// All other C pointers to concrete types map to
// UnsafeMutablePointer<T> or OpaquePointer.
// With pointer conversions enabled, map to the normal pointer types
// without special hints.
Type pointeeType = Impl.importTypeIgnoreIUO(
pointeeQualType, ImportTypeKind::Value, AllowNSUIntegerAsInt,
Bridgeability::None);
// If the pointed-to type is unrepresentable in Swift, or its C
// alignment is greater than the maximum Swift alignment, import as
// OpaquePointer.
if (!pointeeType || Impl.isOverAligned(pointeeQualType)) {
auto opaquePointer = Impl.SwiftContext.getOpaquePointerDecl();
if (!opaquePointer)
return Type();
return {opaquePointer->getDeclaredType(),
ImportHint::OtherPointer};
}
if (pointeeQualType->isFunctionType()) {
auto funcTy = pointeeType->castTo<FunctionType>();
return {
FunctionType::get(funcTy->getParams(), funcTy->getResult(),
funcTy->getExtInfo()
.withRepresentation(
AnyFunctionType::Representation::CFunctionPointer)
.withClangFunctionType(type)),
ImportHint::CFunctionPointer
};
}
PointerTypeKind pointerKind;
if (quals.hasConst()) {
pointerKind = PTK_UnsafePointer;
} else {
switch (quals.getObjCLifetime()) {
case clang::Qualifiers::OCL_Autoreleasing:
case clang::Qualifiers::OCL_ExplicitNone:
// Mutable pointers with __autoreleasing or __unsafe_unretained
// ownership map to AutoreleasingUnsafeMutablePointer<T>.
pointerKind = PTK_AutoreleasingUnsafeMutablePointer;
// FIXME: We have tests using a non-Apple stdlib that nevertheless
// exercise ObjC interop. Fail softly for those tests.
if (!Impl.SwiftContext.getAutoreleasingUnsafeMutablePointerDecl())
return Type();
break;
case clang::Qualifiers::OCL_Weak:
// FIXME: We should refuse to import this.
LLVM_FALLTHROUGH;
case clang::Qualifiers::OCL_None:
case clang::Qualifiers::OCL_Strong:
// All other mutable pointers map to UnsafeMutablePointer.
pointerKind = PTK_UnsafeMutablePointer;
}
}
return {pointeeType->wrapInPointer(pointerKind),
ImportHint::OtherPointer};
}
ImportResult VisitBlockPointerType(const clang::BlockPointerType *type) {
// Block pointer types are mapped to function types.
Type pointeeType = Visit(type->getPointeeType()).AbstractType;
if (!pointeeType)
return Type();
FunctionType *fTy = pointeeType->castTo<FunctionType>();
auto rep = FunctionType::Representation::Block;
auto funcTy =
FunctionType::get(fTy->getParams(), fTy->getResult(),
fTy->getExtInfo().withRepresentation(rep));
return { funcTy, ImportHint::Block };
}
ImportResult VisitReferenceType(const clang::ReferenceType *type) {
return Type();
}
ImportResult VisitMemberPointer(const clang::MemberPointerType *type) {
// FIXME: Member function pointers can be mapped to curried functions,
// but only when we can express the notion of a function that does
// not capture anything from its enclosing context.
return Type();
}
ImportResult VisitArrayType(const clang::ArrayType *type) {
// FIXME: Array types will need to be mapped differently depending on
// context.
return Type();
}
ImportResult VisitConstantArrayType(const clang::ConstantArrayType *type) {
// FIXME: Map to a real fixed-size Swift array type when we have those.
// Importing as a tuple at least fills the right amount of space, and
// we can cheese static-offset "indexing" using .$n operations.
Type elementType = Impl.importTypeIgnoreIUO(
type->getElementType(), ImportTypeKind::Value, AllowNSUIntegerAsInt,
Bridgeability::None);
if (!elementType)
return Type();
auto size = type->getSize().getZExtValue();
// An array of size N is imported as an N-element tuple which
// takes very long to compile. We chose 4096 as the upper limit because
// we don't want to break arrays of size PATH_MAX.
if (size > 4096)
return Type();
SmallVector<TupleTypeElt, 8> elts{size, elementType};
return TupleType::get(elts, elementType->getASTContext());
}
ImportResult VisitVectorType(const clang::VectorType *type) {
// Get the imported element type and count.
Type element = Impl.importTypeIgnoreIUO(
type->getElementType(), ImportTypeKind::Abstract,
false /* No NSUIntegerAsInt */, Bridgeability::None,
OptionalTypeKind::OTK_None);
if (!element) { return Type(); }
unsigned count = type->getNumElements();
// Import vector-of-one as the element type.
if (count == 1) { return element; }
// Imported element type needs to conform to SIMDScalar.
auto nominal = element->getAnyNominal();
auto simdscalar = Impl.SwiftContext.getProtocol(KnownProtocolKind::SIMDScalar);
SmallVector<ProtocolConformance *, 2> conformances;
if (simdscalar && nominal->lookupConformance(nominal->getParentModule(),
simdscalar, conformances)) {
// Element type conforms to SIMDScalar. Get the SIMDn generic type
// if it exists.
SmallString<8> name("SIMD");
name.append(std::to_string(count));
if (auto vector = Impl.getNamedSwiftType(Impl.getStdlibModule(), name)) {
if (auto unbound = vector->getAs<UnboundGenericType>()) {
// All checks passed: the imported element type is SIMDScalar,
// and a generic SIMDn type exists with n == count. Construct the
// bound generic type and return that.
return BoundGenericType::get(
cast<NominalTypeDecl>(unbound->getDecl()), Type(), { element }
);
}
}
}
return Type();
}
ImportResult VisitFunctionProtoType(const clang::FunctionProtoType *type) {
// C-style variadic functions cannot be called from Swift.
if (type->isVariadic())
return Type();
// Import the result type.
auto resultTy = Impl.importTypeIgnoreIUO(
type->getReturnType(), ImportTypeKind::Result, AllowNSUIntegerAsInt,
Bridging, OTK_Optional);
if (!resultTy)
return Type();
SmallVector<FunctionType::Param, 4> params;
for (auto param = type->param_type_begin(),
paramEnd = type->param_type_end();
param != paramEnd; ++param) {
auto swiftParamTy = Impl.importTypeIgnoreIUO(
*param, ImportTypeKind::Parameter, AllowNSUIntegerAsInt, Bridging,
OTK_Optional);
if (!swiftParamTy)
return Type();
// FIXME: If we were walking TypeLocs, we could actually get parameter
// names. The probably doesn't matter outside of a FuncDecl, which
// we'll have to special-case, but it's an interesting bit of data loss.
// <https://bugs.swift.org/browse/SR-2529>
params.push_back(FunctionType::Param(swiftParamTy));
}
// Form the function type.
return FunctionType::get(params, resultTy, FunctionType::ExtInfo());
}
ImportResult
VisitFunctionNoProtoType(const clang::FunctionNoProtoType *type) {
// Import functions without prototypes as functions with no parameters.
auto resultTy = Impl.importTypeIgnoreIUO(
type->getReturnType(), ImportTypeKind::Result, AllowNSUIntegerAsInt,
Bridging, OTK_Optional);
if (!resultTy)
return Type();
return FunctionType::get({}, resultTy);
}
ImportResult VisitParenType(const clang::ParenType *type) {
auto inner = Visit(type->getInnerType());
if (!inner)
return Type();
return { ParenType::get(Impl.SwiftContext, inner.AbstractType),
inner.Hint };
}
/// Imports the type defined by \p objcTypeParamDecl.
///
/// If the type parameter is not imported for some reason, returns \c None.
/// This is different from a failure; it means the caller should try
/// importing the underlying type instead.
Optional<ImportResult>
importObjCTypeParamDecl(const clang::ObjCTypeParamDecl *objcTypeParamDecl) {
// Pull the corresponding generic type parameter from the imported class.
const auto *typeParamContext = objcTypeParamDecl->getDeclContext();
GenericSignature genericSig;
if (auto *category =
dyn_cast<clang::ObjCCategoryDecl>(typeParamContext)) {
auto ext = cast_or_null<ExtensionDecl>(
Impl.importDecl(category, Impl.CurrentVersion));
if (!ext)
return ImportResult();
genericSig = ext->getGenericSignature();
} else if (auto *interface =
dyn_cast<clang::ObjCInterfaceDecl>(typeParamContext)) {
auto cls = castIgnoringCompatibilityAlias<ClassDecl>(
Impl.importDecl(interface, Impl.CurrentVersion));
if (!cls)
return ImportResult();
genericSig = cls->getGenericSignature();
}
unsigned index = objcTypeParamDecl->getIndex();
// Pull the generic param decl out of the imported class.
if (!genericSig) {
// The ObjC type param didn't get imported, possibly because it was
// suppressed. Treat it as a typedef.
return None;
}
if (index > genericSig->getGenericParams().size()) {
return ImportResult();
}
return ImportResult(genericSig->getGenericParams()[index],
ImportHint::ObjCPointer);
}
ImportResult VisitObjCTypeParamType(const clang::ObjCTypeParamType *type) {
// FIXME: This drops any added protocols on the floor, which is the whole
// point of ObjCTypeParamType. Fixing this might be source-breaking,
// though. rdar://problem/29763975
if (auto result = importObjCTypeParamDecl(type->getDecl()))
return result.getValue();
// Fall back to importing the desugared type, which uses the parameter's
// bound. This isn't perfect but it's better than dropping the type.
return Visit(type->getLocallyUnqualifiedSingleStepDesugaredType());
}
ImportResult VisitTypedefType(const clang::TypedefType *type) {
// If the underlying declaration is an Objective-C type parameter,
// pull the corresponding generic type parameter from the imported class.
if (auto *objcTypeParamDecl =
dyn_cast<clang::ObjCTypeParamDecl>(type->getDecl())) {
if (auto result = importObjCTypeParamDecl(objcTypeParamDecl))
return result.getValue();
return Visit(type->getLocallyUnqualifiedSingleStepDesugaredType());
}
// Import the underlying declaration.
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(type->getDecl(), Impl.CurrentVersion));
// If that fails, fall back on importing the underlying type.
if (!decl) return Visit(type->desugar());
Type mappedType = decl->getDeclaredInterfaceType();
if (getSwiftNewtypeAttr(type->getDecl(), Impl.CurrentVersion)) {
auto underlying = Visit(type->getDecl()->getUnderlyingType());
switch (underlying.Hint) {
case ImportHint::None:
case ImportHint::Void:
case ImportHint::Block:
case ImportHint::CFPointer:
case ImportHint::ObjCPointer:
case ImportHint::CFunctionPointer:
case ImportHint::OtherPointer:
case ImportHint::VAList:
return {mappedType, underlying.Hint};
case ImportHint::Boolean:
case ImportHint::NSUInteger:
// Toss out the special rules for these types; we still want to
// import as a wrapper.
return {mappedType, ImportHint::None};
case ImportHint::ObjCBridged:
// If the underlying type was bridged, the wrapper type is
// only useful in bridged cases. Exit early.
return { underlying.AbstractType,
ImportHint(ImportHint::ObjCBridged, mappedType) };
}
}
// For certain special typedefs, we don't want to use the imported type.
if (auto specialKind = Impl.getSpecialTypedefKind(type->getDecl())) {
switch (specialKind.getValue()) {
case MappedTypeNameKind::DoNothing:
case MappedTypeNameKind::DefineAndUse:
break;
case MappedTypeNameKind::DefineOnly:
if (auto typealias = dyn_cast<TypeAliasDecl>(decl))
mappedType = typealias->getDeclaredInterfaceType()
->getDesugaredType();
break;
}
static const llvm::StringLiteral vaListNames[] = {
"va_list", "__gnuc_va_list", "__va_list"
};
ImportHint hint = ImportHint::None;
if (type->getDecl()->getName() == "BOOL") {
hint = ImportHint::Boolean;
} else if (type->getDecl()->getName() == "Boolean") {
// FIXME: Darwin only?
hint = ImportHint::Boolean;
} else if (type->getDecl()->getName() == "NSUInteger") {
hint = ImportHint::NSUInteger;
} else if (llvm::is_contained(vaListNames,
type->getDecl()->getName())) {
hint = ImportHint::VAList;
} else if (isImportedCFPointer(type->desugar(), mappedType)) {
hint = ImportHint::CFPointer;
} else if (mappedType->isAnyExistentialType()) { // id, Class
hint = ImportHint::ObjCPointer;
} else if (type->isPointerType() || type->isBlockPointerType()) {
hint = ImportHint::OtherPointer;
}
// Any other interesting mapped types should be hinted here.
return { mappedType, hint };
}
// Otherwise, recurse on the underlying type. We need to recompute
// the hint, and if the typedef uses different bridgeability than the
// context then we may also need to bypass the typedef.
auto underlyingResult = Visit(type->desugar());
// If we used different bridgeability than this typedef normally
// would because we're in a non-bridgeable context, and therefore
// the underlying type is different from the mapping of the typedef,
// use the underlying type.
if (Bridging != getTypedefBridgeability(type->getDecl()) &&
!underlyingResult.AbstractType->isEqual(mappedType)) {
return underlyingResult;
}
#ifndef NDEBUG
switch (underlyingResult.Hint) {
case ImportHint::Block:
case ImportHint::ObjCBridged:
// Bridging is fine for Objective-C and blocks.
break;
case ImportHint::NSUInteger:
// NSUInteger might be imported as Int rather than UInt depending
// on where the import lives.
if (underlyingResult.AbstractType->getAnyNominal() ==
Impl.SwiftContext.getIntDecl())
break;
LLVM_FALLTHROUGH;
default:
if (!underlyingResult.AbstractType->isEqual(mappedType)) {
underlyingResult.AbstractType->dump(llvm::errs());
mappedType->dump(llvm::errs());
}
assert(underlyingResult.AbstractType->isEqual(mappedType) &&
"typedef without special typedef kind was mapped "
"differently from its underlying type?");
}
#endif
// If the imported typealias is unavailable, return the underlying type.
if (decl->getAttrs().isUnavailable(Impl.SwiftContext))
return underlyingResult;
return { mappedType, underlyingResult.Hint };
}
#define SUGAR_TYPE(KIND) \
ImportResult Visit##KIND##Type(const clang::KIND##Type *type) { \
return Visit(type->desugar()); \
}
SUGAR_TYPE(TypeOfExpr)
SUGAR_TYPE(TypeOf)
SUGAR_TYPE(Decltype)
SUGAR_TYPE(UnaryTransform)
SUGAR_TYPE(Elaborated)
SUGAR_TYPE(SubstTemplateTypeParm)
SUGAR_TYPE(TemplateSpecialization)
SUGAR_TYPE(Auto)
SUGAR_TYPE(DeducedTemplateSpecialization)
SUGAR_TYPE(Adjusted)
SUGAR_TYPE(PackExpansion)
SUGAR_TYPE(Attributed)
SUGAR_TYPE(MacroQualified)
ImportResult VisitDecayedType(const clang::DecayedType *type) {
clang::ASTContext &clangCtx = Impl.getClangASTContext();
if (clangCtx.hasSameType(type->getOriginalType(),
clangCtx.getBuiltinVaListType())) {
return {Impl.getNamedSwiftType(Impl.getStdlibModule(),
"CVaListPointer"),
ImportHint::VAList};
}
return Visit(type->desugar());
}
ImportResult VisitRecordType(const clang::RecordType *type) {
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(type->getDecl(), Impl.CurrentVersion));
if (!decl)
return nullptr;
return decl->getDeclaredInterfaceType();
}
ImportResult VisitEnumType(const clang::EnumType *type) {
auto clangDecl = type->getDecl()->getDefinition();
if (!clangDecl) {
// FIXME: If the enum has a fixed underlying type, can we use that
// instead? Or import it opaquely somehow?
return nullptr;
}
switch (Impl.getEnumKind(clangDecl)) {
case EnumKind::Constants: {
// Map anonymous enums with no fixed underlying type to Int /if/
// they fit in an Int32. If not, this mapping isn't guaranteed to be
// consistent for all platforms we care about.
if (!clangDecl->isFixed() && clangDecl->isFreeStanding() &&
clangDecl->getNumPositiveBits() < 32 &&
clangDecl->getNumNegativeBits() <= 32)
return Impl.getNamedSwiftType(Impl.getStdlibModule(), "Int");
// Import the underlying integer type.
return Visit(clangDecl->getIntegerType());
}
case EnumKind::NonFrozenEnum:
case EnumKind::FrozenEnum:
case EnumKind::Unknown:
case EnumKind::Options: {
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(clangDecl, Impl.CurrentVersion));
if (!decl)
return nullptr;
return decl->getDeclaredInterfaceType();
}
}
llvm_unreachable("Invalid EnumKind.");
}
ImportResult VisitObjCObjectType(const clang::ObjCObjectType *type) {
// We only handle pointers to objects.
return nullptr;
}
/// Map the Clang swift_bridge attribute to a specific type.
Type mapSwiftBridgeAttr(const clang::NamedDecl *clangDecl) {
// Check whether there is a swift_bridge attribute.
if (Impl.DisableSwiftBridgeAttr)
return Type();
auto bridgeAttr = clangDecl->getAttr<clang::SwiftBridgeAttr>();
if (!bridgeAttr) return Type();
// Determine the module and Swift declaration names.
StringRef moduleName;
StringRef name = bridgeAttr->getSwiftType();
auto dotPos = name.find('.');
if (dotPos == StringRef::npos) {
// Determine the module name from the Clang declaration.
if (auto module = clangDecl->getImportedOwningModule())
moduleName = module->getTopLevelModuleName();
else
moduleName = clangDecl->getASTContext().getLangOpts().CurrentModule;
} else {
// The string is ModuleName.TypeName.
moduleName = name.substr(0, dotPos);
name = name.substr(dotPos + 1);
}
return Impl.getNamedSwiftType(moduleName, name);
}
ImportResult
VisitObjCObjectPointerType(const clang::ObjCObjectPointerType *type) {
Type importedType = Impl.SwiftContext.getAnyObjectType();
// If this object pointer refers to an Objective-C class (possibly
// qualified),
if (auto objcClass = type->getInterfaceDecl()) {
auto imported = castIgnoringCompatibilityAlias<ClassDecl>(
Impl.importDecl(objcClass, Impl.CurrentVersion));
if (!imported)
return nullptr;
// If the objc type has any generic args, convert them and bind them to
// the imported class type.
if (imported->getGenericParams()) {
unsigned typeParamCount = imported->getGenericParams()->size();
auto typeArgs = type->getObjectType()->getTypeArgs();
assert(typeArgs.empty() || typeArgs.size() == typeParamCount);
SmallVector<Type, 2> importedTypeArgs;
importedTypeArgs.reserve(typeParamCount);
if (!typeArgs.empty()) {
for (auto typeArg : typeArgs) {
Type importedTypeArg = Visit(typeArg).AbstractType;
if (!importedTypeArg)
return nullptr;
importedTypeArgs.push_back(importedTypeArg);
}
} else {
for (auto typeParam : imported->getGenericParams()->getParams()) {
if (typeParam->getSuperclass() &&
typeParam->getConformingProtocols().empty()) {
importedTypeArgs.push_back(typeParam->getSuperclass());
continue;
}
SmallVector<Type, 4> memberTypes;
if (auto superclassType = typeParam->getSuperclass())
memberTypes.push_back(superclassType);
for (auto protocolDecl : typeParam->getConformingProtocols())
memberTypes.push_back(protocolDecl->getDeclaredType());
bool hasExplicitAnyObject = false;
if (memberTypes.empty())
hasExplicitAnyObject = true;
Type importedTypeArg = ProtocolCompositionType::get(
Impl.SwiftContext, memberTypes,
hasExplicitAnyObject);
importedTypeArgs.push_back(importedTypeArg);
}
}
assert(importedTypeArgs.size() == typeParamCount);
importedType = BoundGenericClassType::get(
imported, nullptr, importedTypeArgs);
} else {
importedType = imported->getDeclaredType();
}
if (!type->qual_empty()) {
// As a special case, turn 'NSObject <NSCopying>' into
// 'id <NSObject, NSCopying>', which can be imported more usefully.
Type nsObjectTy = Impl.getNSObjectType();
if (!nsObjectTy) {
// Input is malformed
return {};
}
if (nsObjectTy && importedType->isEqual(nsObjectTy)) {
// Skip if there is no NSObject protocol.
auto nsObjectProtoType =
Impl.getNSObjectProtocolType();
if (nsObjectProtoType) {
auto *nsObjectProto = nsObjectProtoType->getAnyNominal();
if (!nsObjectProto) {
// Input is malformed
return {};
}
SmallVector<clang::ObjCProtocolDecl *, 4> protocols{
type->qual_begin(), type->qual_end()
};
auto *clangProto =
cast<clang::ObjCProtocolDecl>(nsObjectProto->getClangDecl());
protocols.push_back(
const_cast<clang::ObjCProtocolDecl *>(clangProto));
clang::ASTContext &clangCtx = Impl.getClangASTContext();
clang::QualType protosOnlyType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy,
/*type args*/{},
protocols,
/*kindof*/false);
return Visit(clangCtx.getObjCObjectPointerType(protosOnlyType));
}
}
}
// Determine whether this Objective-C class type is bridged to
// a Swift type. Hardcode "NSString" since it's referenced from
// the ObjectiveC module (a level below Foundation).
Type bridgedType;
if (auto objcClassDef = objcClass->getDefinition())
bridgedType = mapSwiftBridgeAttr(objcClassDef);
else if (objcClass->getName() == "NSString")
bridgedType = Impl.SwiftContext.getStringDecl()->getDeclaredType();
if (bridgedType) {
// Gather the type arguments.
SmallVector<Type, 2> importedTypeArgs;
ArrayRef<clang::QualType> typeArgs = type->getTypeArgs();
SmallVector<clang::QualType, 2> typeArgsScratch;
// If we have an unspecialized form of a parameterized
// Objective-C class type, fill in the defaults.
if (typeArgs.empty()) {
if (auto objcGenericParams = objcClass->getTypeParamList()) {
objcGenericParams->gatherDefaultTypeArgs(typeArgsScratch);
typeArgs = typeArgsScratch;
}
}
// Convert the type arguments.
for (auto typeArg : typeArgs) {
Type importedTypeArg = Impl.importTypeIgnoreIUO(
typeArg, ImportTypeKind::ObjCCollectionElement,
AllowNSUIntegerAsInt, Bridging, OTK_None);
if (!importedTypeArg) {
importedTypeArgs.clear();
break;
}
importedTypeArgs.push_back(importedTypeArg);
}
// If we have an unbound generic bridged type, get the arguments.
if (auto unboundType = bridgedType->getAs<UnboundGenericType>()) {
auto unboundDecl = unboundType->getDecl();
auto bridgedSig = unboundDecl->getGenericSignature();
assert(bridgedSig && "Bridged signature");
unsigned numExpectedTypeArgs = bridgedSig->getGenericParams().size();
if (importedTypeArgs.size() != numExpectedTypeArgs)
return Type();
// The first type argument for Dictionary or Set needs
// to be Hashable. If something isn't Hashable, fall back
// to AnyHashable as a key type.
if (unboundDecl == Impl.SwiftContext.getDictionaryDecl() ||
unboundDecl == Impl.SwiftContext.getSetDecl()) {
auto &keyType = importedTypeArgs[0];
auto keyStructDecl = keyType->getStructOrBoundGenericStruct();
if (!Impl.matchesHashableBound(keyType) ||
// Dictionary and Array conditionally conform to Hashable,
// but the conformance doesn't necessarily apply with the
// imported versions of their type arguments.
// FIXME: Import their non-Hashable type parameters as
// AnyHashable in this context.
keyStructDecl == Impl.SwiftContext.getDictionaryDecl() ||
keyStructDecl == Impl.SwiftContext.getArrayDecl()) {
if (auto anyHashable = Impl.SwiftContext.getAnyHashableDecl())
keyType = anyHashable->getDeclaredType();
else
keyType = Type();
}
}
// Form the specialized type.
if (unboundDecl == Impl.SwiftContext.getArrayDecl()) {
// Type sugar for arrays.
assert(importedTypeArgs.size() == 1);
bridgedType = ArraySliceType::get(importedTypeArgs[0]);
} else if (unboundDecl == Impl.SwiftContext.getDictionaryDecl()) {
// Type sugar for dictionaries.
assert(importedTypeArgs.size() == 2);
bridgedType = DictionaryType::get(importedTypeArgs[0],
importedTypeArgs[1]);
} else {
// Everything else.
bridgedType =
BoundGenericType::get(cast<NominalTypeDecl>(unboundDecl),
Type(), importedTypeArgs);
}
}
return { importedType,
ImportHint(ImportHint::ObjCBridged, bridgedType) };
}
}
if (!type->qual_empty()) {
SmallVector<Type, 4> members;
if (!importedType->isAnyObject())
members.push_back(importedType);
for (auto cp = type->qual_begin(), cpEnd = type->qual_end();
cp != cpEnd; ++cp) {
auto proto = castIgnoringCompatibilityAlias<ProtocolDecl>(
Impl.importDecl(*cp, Impl.CurrentVersion));
if (!proto)
return Type();
members.push_back(proto->getDeclaredType());
}
importedType = ProtocolCompositionType::get(Impl.SwiftContext,
members,
/*HasExplicitAnyObject=*/false);
}
// Class or Class<P> maps to an existential metatype.
if (type->isObjCClassType() ||
type->isObjCQualifiedClassType()) {
importedType = ExistentialMetatypeType::get(importedType);
return { importedType, ImportHint::ObjCPointer };
}
// Beyond here, we're using AnyObject.
// id maps to Any in bridgeable contexts, AnyObject otherwise.
if (type->isObjCIdType()) {
return { Impl.SwiftContext.getAnyObjectType(),
ImportHint(ImportHint::ObjCBridged,
Impl.SwiftContext.TheAnyType)};
}
return { importedType, ImportHint::ObjCPointer };
}
};
} // end anonymous namespace
/// True if we're converting a function parameter, property type, or
/// function result type, and can thus safely apply representation
/// conversions for bridged types.
static bool canBridgeTypes(ImportTypeKind importKind) {
switch (importKind) {
case ImportTypeKind::Abstract:
case ImportTypeKind::Value:
case ImportTypeKind::Variable:
case ImportTypeKind::AuditedVariable:
case ImportTypeKind::Enum:
case ImportTypeKind::RecordField:
return false;
case ImportTypeKind::Result:
case ImportTypeKind::AuditedResult:
case ImportTypeKind::Parameter:
case ImportTypeKind::CFRetainedOutParameter:
case ImportTypeKind::CFUnretainedOutParameter:
case ImportTypeKind::Property:
case ImportTypeKind::PropertyWithReferenceSemantics:
case ImportTypeKind::ObjCCollectionElement:
case ImportTypeKind::Typedef:
return true;
}
llvm_unreachable("Invalid ImportTypeKind.");
}
/// True if the type has known CoreFoundation reference counting semantics.
static bool isCFAudited(ImportTypeKind importKind) {
switch (importKind) {
case ImportTypeKind::Abstract:
case ImportTypeKind::Typedef:
case ImportTypeKind::Value:
case ImportTypeKind::ObjCCollectionElement:
case ImportTypeKind::Variable:
case ImportTypeKind::Result:
case ImportTypeKind::Enum:
case ImportTypeKind::RecordField:
return false;
case ImportTypeKind::AuditedVariable:
case ImportTypeKind::AuditedResult:
case ImportTypeKind::Parameter:
case ImportTypeKind::CFRetainedOutParameter:
case ImportTypeKind::CFUnretainedOutParameter:
case ImportTypeKind::Property:
case ImportTypeKind::PropertyWithReferenceSemantics:
return true;
}
llvm_unreachable("Invalid ImportTypeKind.");
}
/// Turn T into Unmanaged<T>.
static Type getUnmanagedType(ClangImporter::Implementation &impl,
Type payloadType) {
NominalTypeDecl *unmanagedDecl = impl.SwiftContext.getUnmanagedDecl();
if (!unmanagedDecl || unmanagedDecl->getGenericParams()->size() != 1)
return payloadType;
Type unmanagedClassType = BoundGenericType::get(unmanagedDecl,
/*parent*/ Type(),
payloadType);
return unmanagedClassType;
}
/// Determine whether type is 'NSString.
static bool isNSString(Type type) {
if (auto classType = type->getAs<ClassType>()) {
if (auto clangDecl = classType->getDecl()->getClangDecl()) {
if (auto objcClass = dyn_cast<clang::ObjCInterfaceDecl>(clangDecl)) {
return objcClass->getName() == "NSString";
}
}
}
return false;
}
static Type maybeImportNSErrorOutParameter(ClangImporter::Implementation &impl,
Type importedType,
bool resugarNSErrorPointer) {
PointerTypeKind PTK;
auto elementType = importedType->getAnyPointerElementType(PTK);
if (!elementType || PTK != PTK_AutoreleasingUnsafeMutablePointer)
return Type();
auto elementObj = elementType->getOptionalObjectType();
if (!elementObj)
return Type();
auto elementClass = elementObj->getClassOrBoundGenericClass();
if (!elementClass)
return Type();
// FIXME: Avoid string comparison by caching this identifier.
if (elementClass->getName().str() !=
impl.SwiftContext.getSwiftName(KnownFoundationEntity::NSError))
return Type();
ModuleDecl *foundationModule = impl.tryLoadFoundationModule();
if (!foundationModule ||
foundationModule->getName()
!= elementClass->getModuleContext()->getName())
return Type();
if (resugarNSErrorPointer)
return impl.getNamedSwiftType(
foundationModule,
impl.SwiftContext.getSwiftName(
KnownFoundationEntity::NSErrorPointer));
// The imported type is AUMP<NSError?>, but the typealias is AUMP<NSError?>?
// so we have to manually make them match. We also want to assume this in
// general for error out-parameters even if they weren't marked nullable in C.
// Or at least we do for source-compatibility reasons...
return OptionalType::get(importedType);
}
static Type maybeImportCFOutParameter(ClangImporter::Implementation &impl,
Type importedType,
ImportTypeKind importKind) {
PointerTypeKind PTK;
auto elementType = importedType->getAnyPointerElementType(PTK);
if (!elementType || PTK != PTK_UnsafeMutablePointer)
return Type();
auto insideOptionalType = elementType->getOptionalObjectType();
bool isOptional = (bool) insideOptionalType;
if (!insideOptionalType)
insideOptionalType = elementType;
auto boundGenericTy = insideOptionalType->getAs<BoundGenericType>();
if (!boundGenericTy)
return Type();
auto boundGenericBase = boundGenericTy->getDecl();
if (boundGenericBase != impl.SwiftContext.getUnmanagedDecl())
return Type();
assert(boundGenericTy->getGenericArgs().size() == 1 &&
"signature of Unmanaged has changed");
auto resultTy = boundGenericTy->getGenericArgs().front();
if (isOptional)
resultTy = OptionalType::get(resultTy);
PointerTypeKind pointerKind;
if (importKind == ImportTypeKind::CFRetainedOutParameter)
pointerKind = PTK_UnsafeMutablePointer;
else
pointerKind = PTK_AutoreleasingUnsafeMutablePointer;
resultTy = resultTy->wrapInPointer(pointerKind);
return resultTy;
}
static ImportedType adjustTypeForConcreteImport(
ClangImporter::Implementation &impl,
ImportResult importResult, ImportTypeKind importKind,
bool allowNSUIntegerAsInt, Bridgeability bridging, OptionalTypeKind optKind,
bool resugarNSErrorPointer) {
Type importedType = importResult.AbstractType;
ImportHint hint = importResult.Hint;
if (importKind == ImportTypeKind::Abstract) {
return {importedType, false};
}
// If we completely failed to import the type, give up now.
// Special-case for 'void' which is valid in result positions.
if (!importedType && hint != ImportHint::Void)
return {Type(), false};
switch (hint) {
case ImportHint::None:
break;
case ImportHint::ObjCPointer:
case ImportHint::CFunctionPointer:
break;
case ImportHint::Void:
// 'void' can only be imported as a function result type.
if (importKind != ImportTypeKind::AuditedResult &&
importKind != ImportTypeKind::Result) {
return {Type(), false};
}
importedType = impl.getNamedSwiftType(impl.getStdlibModule(), "Void");
break;
case ImportHint::ObjCBridged:
// Import NSString * globals as non-optional String.
if (isNSString(importedType)) {
if (importKind == ImportTypeKind::Variable ||
importKind == ImportTypeKind::AuditedVariable) {
importedType = hint.BridgedType;
optKind = OTK_None;
break;
}
}
// If we have a bridged Objective-C type and we are allowed to
// bridge, do so.
if (canBridgeTypes(importKind) &&
importKind != ImportTypeKind::PropertyWithReferenceSemantics &&
!(importKind == ImportTypeKind::Typedef &&
bridging == Bridgeability::None)) {
// id and Any can be bridged without Foundation. There would be
// bootstrapping issues with the ObjectiveC module otherwise.
if (hint.BridgedType->isAny()
|| impl.tryLoadFoundationModule()
|| impl.ImportForwardDeclarations) {
// Set the bridged type if it wasn't done already.
if (!importedType->isEqual(hint.BridgedType))
importedType = hint.BridgedType;
}
}
break;
case ImportHint::Block: {
// SwiftTypeConverter turns block pointers into @convention(block) types.
// In some contexts, we bridge them to use the Swift function type
// representation. This includes typedefs of block types, which use the
// Swift function type representation.
if (!canBridgeTypes(importKind))
break;
// Determine the function type representation we need.
//
// For Objective-C collection arguments, we cannot bridge from a block
// to a Swift function type, so force the block representation. Normally
// the mapped type will have a block representation (making this a no-op),
// but in cases where the Clang type was written as a typedef of a
// block type, that typedef will have a Swift function type
// representation. This code will then break down the imported type
// alias and produce a function type with block representation.
auto requiredFunctionTypeRepr = FunctionTypeRepresentation::Swift;
if (importKind == ImportTypeKind::ObjCCollectionElement) {
requiredFunctionTypeRepr = FunctionTypeRepresentation::Block;
}
auto fTy = importedType->castTo<FunctionType>();
FunctionType::ExtInfo einfo = fTy->getExtInfo();
if (einfo.getRepresentation() != requiredFunctionTypeRepr) {
einfo = einfo.withRepresentation(requiredFunctionTypeRepr);
importedType = fTy->withExtInfo(einfo);
}
break;
}
case ImportHint::Boolean:
// Turn BOOL and DarwinBoolean into Bool in contexts that can bridge types
// losslessly.
if (bridging == Bridgeability::Full && canBridgeTypes(importKind))
importedType = impl.SwiftContext.getBoolDecl()->getDeclaredType();
break;
case ImportHint::NSUInteger:
// When NSUInteger is used as an enum's underlying type or if it does not
// come from a system module, make sure it stays unsigned.
if (importKind == ImportTypeKind::Enum || !allowNSUIntegerAsInt)
importedType = impl.SwiftContext.getUIntDecl()->getDeclaredType();
break;
case ImportHint::CFPointer:
// Wrap CF pointers up as unmanaged types, unless this is an audited
// context.
if (!isCFAudited(importKind)) {
Type underlyingType = importedType->getSwiftNewtypeUnderlyingType();
if (!underlyingType)
underlyingType = importedType;
importedType = getUnmanagedType(impl, underlyingType);
}
break;
case ImportHint::VAList:
// Treat va_list specially: null-unspecified va_list parameters should be
// assumed to be non-optional. (Most people don't even think of va_list as a
// pointer, and it's not a portable assumption anyway.)
if (importKind == ImportTypeKind::Parameter &&
optKind == OTK_ImplicitlyUnwrappedOptional) {
optKind = OTK_None;
}
break;
case ImportHint::OtherPointer:
// Special-case AutoreleasingUnsafeMutablePointer<NSError?> parameters.
if (importKind == ImportTypeKind::Parameter) {
if (Type result = maybeImportNSErrorOutParameter(impl, importedType,
resugarNSErrorPointer)) {
importedType = result;
optKind = OTK_None;
break;
}
}
// Remove 'Unmanaged' from audited CF out-parameters.
if (importKind == ImportTypeKind::CFRetainedOutParameter ||
importKind == ImportTypeKind::CFUnretainedOutParameter) {
if (Type outParamTy = maybeImportCFOutParameter(impl, importedType,
importKind)) {
importedType = outParamTy;
break;
}
}
break;
}
assert(importedType);
if (importKind == ImportTypeKind::RecordField &&
importedType->isAnyClassReferenceType()) {
// Wrap retainable struct fields in Unmanaged.
// FIXME: Eventually we might get C++-like support for strong pointers in
// structs, at which point we should really be checking the lifetime
// qualifiers.
// FIXME: This should apply to blocks as well, but Unmanaged is constrained
// to AnyObject.
importedType = getUnmanagedType(impl, importedType);
}
// Wrap class, class protocol, function, and metatype types in an
// optional type.
bool isIUO = false;
if (importKind != ImportTypeKind::Typedef && optKind != OTK_None &&
canImportAsOptional(hint)) {
isIUO = optKind == OTK_ImplicitlyUnwrappedOptional;
importedType = OptionalType::get(importedType);
}
return {importedType, isIUO};
}
ImportedType ClangImporter::Implementation::importType(
clang::QualType type, ImportTypeKind importKind, bool allowNSUIntegerAsInt,
Bridgeability bridging, OptionalTypeKind optionality,
bool resugarNSErrorPointer) {
if (type.isNull())
return {Type(), false};
// The "built-in" Objective-C types id, Class, and SEL can actually be (and
// are) defined within the library. Clang tracks the redefinition types
// separately, so it can provide fallbacks in certain cases. For Swift, we
// map the redefinition types back to the equivalent of the built-in types.
// This bans some trickery that the redefinition types enable, but is a more
// sane model overall.
auto &clangContext = getClangASTContext();
if (clangContext.getLangOpts().ObjC) {
if (clangContext.hasSameUnqualifiedType(
type, clangContext.getObjCIdRedefinitionType()) &&
!clangContext.hasSameUnqualifiedType(
clangContext.getObjCIdType(),
clangContext.getObjCIdRedefinitionType()))
type = clangContext.getObjCIdType();
else if (clangContext.hasSameUnqualifiedType(
type, clangContext.getObjCClassRedefinitionType()) &&
!clangContext.hasSameUnqualifiedType(
clangContext.getObjCClassType(),
clangContext.getObjCClassRedefinitionType()))
type = clangContext.getObjCClassType();
else if (clangContext.hasSameUnqualifiedType(
type, clangContext.getObjCSelRedefinitionType()) &&
!clangContext.hasSameUnqualifiedType(
clangContext.getObjCSelType(),
clangContext.getObjCSelRedefinitionType()))
type = clangContext.getObjCSelType();
}
// If nullability is provided as part of the type, that overrides
// optionality provided externally.
if (auto nullability = type->getNullability(clangContext)) {
optionality = translateNullability(*nullability);
}
// Perform abstract conversion, ignoring how the type is actually used.
SwiftTypeConverter converter(*this, allowNSUIntegerAsInt, bridging);
auto importResult = converter.Visit(type);
// Now fix up the type based on how we're concretely using it.
auto adjustedType = adjustTypeForConcreteImport(
*this, importResult, importKind, allowNSUIntegerAsInt, bridging,
optionality, resugarNSErrorPointer);
return adjustedType;
}
Type ClangImporter::Implementation::importTypeIgnoreIUO(
clang::QualType type, ImportTypeKind importKind, bool allowNSUIntegerAsInt,
Bridgeability bridging, OptionalTypeKind optionality,
bool resugarNSErrorPointer) {
auto importedType = importType(type, importKind, allowNSUIntegerAsInt,
bridging, optionality, resugarNSErrorPointer);
return importedType.getType();
}
bool ClangImporter::Implementation::shouldImportGlobalAsLet(
clang::QualType type)
{
// Const variables should be imported as 'let'.
if (type.isConstQualified()) {
return true;
}
// Globals of type NSString * should be imported as 'let'.
if (isNSString(type))
return true;
return false;
}
/// Returns true if \p name contains the substring "Unsigned" or "unsigned".
static bool nameContainsUnsigned(StringRef name) {
size_t pos = name.find("nsigned");
if (pos == StringRef::npos || pos == 0)
return false;
--pos;
return (name[pos] == 'u') || (name[pos] == 'U');
}
bool ClangImporter::Implementation::shouldAllowNSUIntegerAsInt(
bool isFromSystemModule, const clang::NamedDecl *decl) {
if (isFromSystemModule)
if (auto identInfo = decl->getIdentifier())
return !nameContainsUnsigned(identInfo->getName());
return false;
}
ImportedType ClangImporter::Implementation::importPropertyType(
const clang::ObjCPropertyDecl *decl, bool isFromSystemModule) {
const auto assignOrUnsafeUnretained =
clang::ObjCPropertyDecl::OBJC_PR_assign |
clang::ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
ImportTypeKind importKind;
// HACK: Certain decls are always imported using bridged types,
// because that's what a standalone method would do.
if (shouldImportPropertyAsAccessors(decl)) {
importKind = ImportTypeKind::Property;
} else {
switch (decl->getSetterKind()) {
case clang::ObjCPropertyDecl::Assign:
// If it's readonly, this might just be returned as a default.
if (decl->isReadOnly() &&
(decl->getPropertyAttributes() & assignOrUnsafeUnretained) == 0) {
importKind = ImportTypeKind::Property;
} else {
importKind = ImportTypeKind::PropertyWithReferenceSemantics;
}
break;
case clang::ObjCPropertyDecl::Retain:
case clang::ObjCPropertyDecl::Copy:
importKind = ImportTypeKind::Property;
break;
case clang::ObjCPropertyDecl::Weak:
importKind = ImportTypeKind::PropertyWithReferenceSemantics;
break;
}
}
OptionalTypeKind optionality = OTK_ImplicitlyUnwrappedOptional;
return importType(decl->getType(), importKind,
shouldAllowNSUIntegerAsInt(isFromSystemModule, decl),
Bridgeability::Full, optionality);
}
/// Apply the @noescape attribute
static Type applyNoEscape(Type type) {
// Recurse into optional types.
if (Type objectType = type->getOptionalObjectType()) {
return OptionalType::get(applyNoEscape(objectType));
}
// Apply @noescape to function types.
if (auto funcType = type->getAs<FunctionType>()) {
return FunctionType::get(funcType->getParams(), funcType->getResult(),
funcType->getExtInfo().withNoEscape());
}
return type;
}
ImportedType ClangImporter::Implementation::importFunctionReturnType(
DeclContext *dc, const clang::FunctionDecl *clangDecl,
bool allowNSUIntegerAsInt) {
// Hardcode handling of certain result types for builtins.
if (auto builtinID = clangDecl->getBuiltinID()) {
switch (getClangASTContext().BuiltinInfo.getTypeString(builtinID)[0]) {
case 'z': // size_t
case 'Y': // ptrdiff_t
return {SwiftContext.getIntDecl()->getDeclaredType(), false};
default:
break;
}
}
// CF function results can be managed if they are audited or
// the ownership convention is explicitly declared.
assert(clangDecl && "expected to have a decl to import");
bool isAuditedResult =
(clangDecl->hasAttr<clang::CFAuditedTransferAttr>() ||
clangDecl->hasAttr<clang::CFReturnsRetainedAttr>() ||
clangDecl->hasAttr<clang::CFReturnsNotRetainedAttr>());
// Fix up optionality.
OptionalTypeKind OptionalityOfReturn;
if (clangDecl->hasAttr<clang::ReturnsNonNullAttr>()) {
OptionalityOfReturn = OTK_None;
} else {
OptionalityOfReturn = OTK_ImplicitlyUnwrappedOptional;
}
// Import the result type.
return importType(clangDecl->getReturnType(),
(isAuditedResult ? ImportTypeKind::AuditedResult
: ImportTypeKind::Result),
allowNSUIntegerAsInt, Bridgeability::Full,
OptionalityOfReturn);
}
ImportedType ClangImporter::Implementation::importFunctionParamsAndReturnType(
DeclContext *dc, const clang::FunctionDecl *clangDecl,
ArrayRef<const clang::ParmVarDecl *> params, bool isVariadic,
bool isFromSystemModule, DeclName name, ParameterList *¶meterList) {
bool allowNSUIntegerAsInt =
shouldAllowNSUIntegerAsInt(isFromSystemModule, clangDecl);
auto importedType =
importFunctionReturnType(dc, clangDecl, allowNSUIntegerAsInt);
if (!importedType)
return {Type(), false};
ArrayRef<Identifier> argNames = name.getArgumentNames();
parameterList = importFunctionParameterList(dc, clangDecl, params, isVariadic,
allowNSUIntegerAsInt, argNames);
if (!parameterList)
return {Type(), false};
Type swiftResultTy = importedType.getType();
if (clangDecl->isNoReturn())
swiftResultTy = SwiftContext.getNeverType();
return {swiftResultTy, importedType.isImplicitlyUnwrapped()};
}
ParameterList *ClangImporter::Implementation::importFunctionParameterList(
DeclContext *dc, const clang::FunctionDecl *clangDecl,
ArrayRef<const clang::ParmVarDecl *> params, bool isVariadic,
bool allowNSUIntegerAsInt, ArrayRef<Identifier> argNames) {
// Import the parameters.
SmallVector<ParamDecl *, 4> parameters;
unsigned index = 0;
SmallBitVector nonNullArgs = getNonNullArgs(clangDecl, params);
for (auto param : params) {
auto paramTy = param->getType();
if (paramTy->isVoidType()) {
++index;
continue;
}
// Check nullability of the parameter.
OptionalTypeKind OptionalityOfParam =
getParamOptionality(SwiftContext.LangOpts.EffectiveLanguageVersion,
param, !nonNullArgs.empty() && nonNullArgs[index]);
ImportTypeKind importKind = ImportTypeKind::Parameter;
if (param->hasAttr<clang::CFReturnsRetainedAttr>())
importKind = ImportTypeKind::CFRetainedOutParameter;
else if (param->hasAttr<clang::CFReturnsNotRetainedAttr>())
importKind = ImportTypeKind::CFUnretainedOutParameter;
// Import the parameter type into Swift.
auto importedType = importType(paramTy, importKind, allowNSUIntegerAsInt,
Bridgeability::Full, OptionalityOfParam);
if (!importedType)
return nullptr;
auto swiftParamTy = importedType.getType();
// Map __attribute__((noescape)) to @noescape.
if (param->hasAttr<clang::NoEscapeAttr>()) {
Type newParamTy = applyNoEscape(swiftParamTy);
if (newParamTy.getPointer() != swiftParamTy.getPointer()) {
swiftParamTy = newParamTy;
}
}
// Figure out the name for this parameter.
Identifier bodyName = importFullName(param, CurrentVersion)
.getDeclName()
.getBaseIdentifier();
// Retrieve the argument name.
Identifier name;
if (index < argNames.size())
name = argNames[index];
// It doesn't actually matter which DeclContext we use, so just use the
// imported header unit.
auto paramInfo = createDeclWithClangNode<ParamDecl>(
param, AccessLevel::Private, SourceLoc(), SourceLoc(), name,
importSourceLoc(param->getLocation()), bodyName,
ImportedHeaderUnit);
paramInfo->setSpecifier(ParamSpecifier::Default);
paramInfo->setInterfaceType(swiftParamTy);
recordImplicitUnwrapForDecl(paramInfo,
importedType.isImplicitlyUnwrapped());
parameters.push_back(paramInfo);
++index;
}
// Append an additional argument to represent varargs.
if (isVariadic) {
auto paramTy =
BoundGenericType::get(SwiftContext.getArrayDecl(), Type(),
{SwiftContext.TheAnyType});
auto name = SwiftContext.getIdentifier("varargs");
auto param = new (SwiftContext) ParamDecl(SourceLoc(), SourceLoc(),
Identifier(), SourceLoc(),
name,
ImportedHeaderUnit);
param->setSpecifier(ParamSpecifier::Default);
param->setInterfaceType(paramTy);
param->setVariadic();
parameters.push_back(param);
}
// Form the parameter list.
return ParameterList::create(SwiftContext, parameters);
}
static bool isObjCMethodResultAudited(const clang::Decl *decl) {
if (!decl)
return false;
return (decl->hasAttr<clang::CFReturnsRetainedAttr>() ||
decl->hasAttr<clang::CFReturnsNotRetainedAttr>() ||
decl->hasAttr<clang::ObjCReturnsInnerPointerAttr>());
}
DefaultArgumentKind ClangImporter::Implementation::inferDefaultArgument(
clang::QualType type, OptionalTypeKind clangOptionality,
DeclBaseName baseName, StringRef argumentLabel, bool isFirstParameter,
bool isLastParameter, NameImporter &nameImporter) {
auto baseNameStr = baseName.userFacingName();
// Don't introduce a default argument for the first parameter of setters.
if (isFirstParameter && camel_case::getFirstWord(baseNameStr) == "set")
return DefaultArgumentKind::None;
// Some nullable parameters default to 'nil'.
if (clangOptionality == OTK_Optional) {
// Nullable trailing closure parameters default to 'nil'.
if (isLastParameter &&
(type->isFunctionPointerType() || type->isBlockPointerType()))
return DefaultArgumentKind::NilLiteral;
// NSZone parameters default to 'nil'.
if (auto ptrType = type->getAs<clang::PointerType>()) {
if (auto recType
= ptrType->getPointeeType()->getAs<clang::RecordType>()) {
if (recType->isStructureOrClassType() &&
recType->getDecl()->getName() == "_NSZone")
return DefaultArgumentKind::NilLiteral;
}
}
}
// Option sets default to "[]" if they have "Options" in their name.
if (const clang::EnumType *enumTy = type->getAs<clang::EnumType>()) {
const clang::EnumDecl *enumDef = enumTy->getDecl()->getDefinition();
if (enumDef && nameImporter.getEnumKind(enumDef) == EnumKind::Options) {
auto enumName = enumDef->getName();
for (auto word : llvm::reverse(camel_case::getWords(enumName))) {
if (camel_case::sameWordIgnoreFirstCase(word, "options"))
return DefaultArgumentKind::EmptyArray;
}
}
}
// NSDictionary arguments default to [:] (or nil, if nullable) if "options",
// "attributes", or "userInfo" occur in the argument label or (if there is no
// argument label) at the end of the base name.
if (auto objcPtrTy = type->getAs<clang::ObjCObjectPointerType>()) {
if (auto objcClass = objcPtrTy->getInterfaceDecl()) {
if (objcClass->getName() == "NSDictionary") {
StringRef searchStr = argumentLabel;
if (searchStr.empty() && !baseNameStr.empty())
searchStr = baseNameStr;
auto emptyDictionaryKind = DefaultArgumentKind::EmptyDictionary;
if (clangOptionality == OTK_Optional)
emptyDictionaryKind = DefaultArgumentKind::NilLiteral;
bool sawInfo = false;
for (auto word : llvm::reverse(camel_case::getWords(searchStr))) {
if (camel_case::sameWordIgnoreFirstCase(word, "options"))
return emptyDictionaryKind;
if (camel_case::sameWordIgnoreFirstCase(word, "attributes"))
return emptyDictionaryKind;
if (camel_case::sameWordIgnoreFirstCase(word, "info")) {
sawInfo = true;
continue;
}
if (sawInfo && camel_case::sameWordIgnoreFirstCase(word, "user"))
return emptyDictionaryKind;
if (argumentLabel.empty())
break;
sawInfo = false;
}
}
}
}
return DefaultArgumentKind::None;
}
/// Adjust the result type of a throwing function based on the
/// imported error information.
static ImportedType
adjustResultTypeForThrowingFunction(ForeignErrorConvention::Info errorInfo,
ImportedType importedType) {
switch (errorInfo.TheKind) {
case ForeignErrorConvention::ZeroResult:
case ForeignErrorConvention::NonZeroResult:
// Check for a bad override.
if (importedType.getType()->isVoid())
return {Type(), false};
return {TupleType::getEmpty(importedType.getType()->getASTContext()),
false};
case ForeignErrorConvention::NilResult:
if (Type unwrappedTy = importedType.getType()->getOptionalObjectType())
return {unwrappedTy, false};
// Check for a bad override.
if (importedType.getType()->isVoid())
return {Type(), false};
// It's possible an Objective-C method overrides the base method to never
// fail, and marks the method _Nonnull to indicate that. Swift can't
// represent that, but it shouldn't fall over either.
return importedType;
case ForeignErrorConvention::ZeroPreservedResult:
// Check for a bad override.
if (importedType.getType()->isVoid())
return {Type(), false};
return importedType;
case ForeignErrorConvention::NonNilError:
return importedType;
}
llvm_unreachable("Invalid ForeignErrorConvention.");
}
/// Produce the foreign error convention from the imported error info,
/// error parameter type, and original result type.
static ForeignErrorConvention
getForeignErrorInfo(ForeignErrorConvention::Info errorInfo,
CanType errorParamTy, CanType origResultTy) {
assert(errorParamTy && "not fully initialized!");
using FEC = ForeignErrorConvention;
auto ParamIndex = errorInfo.ErrorParameterIndex;
auto IsOwned = (FEC::IsOwned_t) errorInfo.ErrorIsOwned;
auto ReplaceParamWithVoid = errorInfo.ErrorParameterIsReplaced
? FEC::IsReplaced
: FEC::IsNotReplaced;
switch (errorInfo.TheKind) {
case FEC::ZeroResult:
return FEC::getZeroResult(ParamIndex, IsOwned, ReplaceParamWithVoid,
errorParamTy, origResultTy);
case FEC::NonZeroResult:
return FEC::getNonZeroResult(ParamIndex, IsOwned, ReplaceParamWithVoid,
errorParamTy, origResultTy);
case FEC::ZeroPreservedResult:
return FEC::getZeroPreservedResult(ParamIndex, IsOwned,
ReplaceParamWithVoid, errorParamTy);
case FEC::NilResult:
return FEC::getNilResult(ParamIndex, IsOwned, ReplaceParamWithVoid,
errorParamTy);
case FEC::NonNilError:
return FEC::getNonNilError(ParamIndex, IsOwned, ReplaceParamWithVoid,
errorParamTy);
}
llvm_unreachable("bad error convention");
}
// 'toDC' must be a subclass or a type conforming to the protocol
// 'fromDC'.
static Type mapGenericArgs(const DeclContext *fromDC,
const DeclContext *toDC, Type type) {
if (fromDC == toDC)
return type;
auto subs = toDC->getDeclaredInterfaceType()->getContextSubstitutionMap(
toDC->getParentModule(), fromDC);
return type.subst(subs);
}
ImportedType ClangImporter::Implementation::importMethodParamsAndReturnType(
const DeclContext *dc, const clang::ObjCMethodDecl *clangDecl,
ArrayRef<const clang::ParmVarDecl *> params, bool isVariadic,
bool isFromSystemModule, ParameterList **bodyParams,
ImportedName importedName,
Optional<ForeignErrorConvention> &foreignErrorInfo,
SpecialMethodKind kind) {
// Cannot import variadic types unless specially handled before calling this
// function.
if (isVariadic || clangDecl->sel_param_end() != clangDecl->param_end())
return {Type(), false};
// Clang doesn't provide pragmas for auditing the CF behavior of
// ObjC methods, but it does have attributes for declaring
// return-type management:
// - cf_returns_retained and cf_returns_not_retained are obvious
// - objc_returns_inner_pointer is sometimes used on methods
// returning CF types as a workaround for ARC not managing CF
// objects
ImportTypeKind resultKind;
if (isObjCMethodResultAudited(clangDecl))
resultKind = ImportTypeKind::AuditedResult;
else
resultKind = ImportTypeKind::Result;
// The member was defined in 'origDC', but is being imported into 'dc'.
// 'dc' must be a subclass or a type conforming to protocol.
DeclContext *origDC = importDeclContextOf(clangDecl,
clangDecl->getDeclContext());
assert(origDC);
// Import the result type.
CanType origSwiftResultTy;
Optional<ForeignErrorConvention::Info> errorInfo =
importedName.getErrorInfo();
OptionalTypeKind OptionalityOfReturn;
if (clangDecl->hasAttr<clang::ReturnsNonNullAttr>()) {
OptionalityOfReturn = OTK_None;
} else {
OptionalityOfReturn = OTK_ImplicitlyUnwrappedOptional;
}
bool allowNSUIntegerAsIntInResult = isFromSystemModule;
if (allowNSUIntegerAsIntInResult) {
clang::Selector sel = clangDecl->getSelector();
StringRef name = sel.getNameForSlot(0);
if (!name.empty()) {
allowNSUIntegerAsIntInResult = !nameContainsUnsigned(name);
}
}
clang::QualType resultType = clangDecl->getReturnType();
auto importedType =
importType(resultType, resultKind, allowNSUIntegerAsIntInResult,
Bridgeability::Full, OptionalityOfReturn);
// Adjust the result type for a throwing function.
if (importedType.getType() && errorInfo) {
// Get the original unbridged result type.
auto origImportedType =
importType(resultType, resultKind, allowNSUIntegerAsIntInResult,
Bridgeability::None, OptionalityOfReturn);
origSwiftResultTy = origImportedType.getType()->getCanonicalType();
importedType =
adjustResultTypeForThrowingFunction(*errorInfo, importedType);
}
auto swiftResultTy = importedType.getType();
if (swiftResultTy &&
clangDecl->getMethodFamily() == clang::OMF_performSelector) {
// performSelector methods that return 'id' should be imported into Swift
// as returning Unmanaged<AnyObject>.
Type nonOptionalTy = swiftResultTy->getOptionalObjectType();
bool resultIsOptional = (bool) nonOptionalTy;
if (!nonOptionalTy)
nonOptionalTy = swiftResultTy;
// Undo 'Any' bridging.
if (nonOptionalTy->isAny())
nonOptionalTy = SwiftContext.getAnyObjectType();
if (nonOptionalTy->isAnyClassReferenceType()) {
swiftResultTy = getUnmanagedType(*this, nonOptionalTy);
if (resultIsOptional)
swiftResultTy = OptionalType::get(swiftResultTy);
}
}
if (!swiftResultTy)
return {Type(), false};
swiftResultTy = mapGenericArgs(origDC, dc, swiftResultTy);
CanType errorParamType;
SmallBitVector nonNullArgs = getNonNullArgs(clangDecl, params);
// Import the parameters.
SmallVector<ParamDecl*, 4> swiftParams;
auto addEmptyTupleParameter = [&](Identifier argName) {
// It doesn't actually matter which DeclContext we use, so just
// use the imported header unit.
auto type = TupleType::getEmpty(SwiftContext);
auto var = new (SwiftContext) ParamDecl(SourceLoc(),
SourceLoc(), argName,
SourceLoc(), argName,
ImportedHeaderUnit);
var->setSpecifier(ParamSpecifier::Default);
var->setInterfaceType(type);
swiftParams.push_back(var);
};
// Determine the number of parameters.
unsigned numEffectiveParams = params.size();
if (errorInfo) --numEffectiveParams;
auto argNames = importedName.getDeclName().getArgumentNames();
unsigned nameIndex = 0;
for (size_t paramIndex = 0; paramIndex != params.size(); paramIndex++) {
auto param = params[paramIndex];
auto paramTy = param->getType();
auto paramIsError = errorInfo && paramIndex == errorInfo->ErrorParameterIndex;
if (paramTy->isVoidType()) {
assert(!paramIsError);
++nameIndex;
continue;
}
// Import the parameter type into Swift.
// Check nullability of the parameter.
OptionalTypeKind optionalityOfParam
= getParamOptionality(SwiftContext.LangOpts.EffectiveLanguageVersion,
param,
!nonNullArgs.empty() && nonNullArgs[paramIndex]);
bool allowNSUIntegerAsIntInParam = isFromSystemModule;
if (allowNSUIntegerAsIntInParam) {
StringRef name;
clang::Selector sel = clangDecl->getSelector();
if (nameIndex < sel.getNumArgs())
name = sel.getNameForSlot(nameIndex);
if (name.empty() && nameIndex == 0)
name = sel.getNameForSlot(0);
if (!name.empty())
allowNSUIntegerAsIntInParam = !nameContainsUnsigned(name);
}
// Special case for NSDictionary's subscript.
Type swiftParamTy;
bool paramIsIUO;
if (kind == SpecialMethodKind::NSDictionarySubscriptGetter &&
paramTy->isObjCIdType()) {
swiftParamTy = SwiftContext.getNSCopyingType();
if (optionalityOfParam != OTK_None)
swiftParamTy = OptionalType::get(swiftParamTy);
paramIsIUO = optionalityOfParam == OTK_ImplicitlyUnwrappedOptional;
} else {
ImportTypeKind importKind = ImportTypeKind::Parameter;
if (param->hasAttr<clang::CFReturnsRetainedAttr>())
importKind = ImportTypeKind::CFRetainedOutParameter;
else if (param->hasAttr<clang::CFReturnsNotRetainedAttr>())
importKind = ImportTypeKind::CFUnretainedOutParameter;
// If this is the throws error parameter, we don't need to convert any
// NSError** arguments to the sugared NSErrorPointer typealias form,
// because all that is done with it is retrieving the canonical
// type. Avoiding the sugar breaks a loop in Foundation caused by method
// on NSString that has an error parameter. FIXME: This is a work-around
// for the specific case when the throws conversion works, but is not
// sufficient if it fails. (The correct, overarching fix is ClangImporter
// being lazier.)
auto importedParamType =
importType(paramTy, importKind, allowNSUIntegerAsIntInParam,
Bridgeability::Full, optionalityOfParam,
/*resugarNSErrorPointer=*/!paramIsError);
paramIsIUO = importedParamType.isImplicitlyUnwrapped();
swiftParamTy = importedParamType.getType();
}
if (!swiftParamTy)
return {Type(), false};
swiftParamTy = mapGenericArgs(origDC, dc, swiftParamTy);
// If this is the error parameter, remember it, but don't build it
// into the parameter type.
if (paramIsError) {
errorParamType = swiftParamTy->getCanonicalType();
// ...unless we're supposed to replace it with ().
if (errorInfo->ErrorParameterIsReplaced) {
addEmptyTupleParameter(argNames[nameIndex]);
++nameIndex;
}
continue;
}
// Map __attribute__((noescape)) to @noescape.
bool addNoEscapeAttr = false;
if (param->hasAttr<clang::NoEscapeAttr>()) {
Type newParamTy = applyNoEscape(swiftParamTy);
if (newParamTy.getPointer() != swiftParamTy.getPointer()) {
swiftParamTy = newParamTy;
addNoEscapeAttr = true;
}
}
// Figure out the name for this parameter.
Identifier bodyName = importFullName(param, CurrentVersion)
.getDeclName()
.getBaseIdentifier();
// Figure out the name for this argument, which comes from the method name.
Identifier name;
if (nameIndex < argNames.size()) {
name = argNames[nameIndex];
}
++nameIndex;
// Set up the parameter info.
auto paramInfo
= createDeclWithClangNode<ParamDecl>(param, AccessLevel::Private,
SourceLoc(), SourceLoc(), name,
importSourceLoc(param->getLocation()),
bodyName,
ImportedHeaderUnit);
paramInfo->setSpecifier(ParamSpecifier::Default);
paramInfo->setInterfaceType(swiftParamTy);
recordImplicitUnwrapForDecl(paramInfo, paramIsIUO);
// Determine whether we have a default argument.
if (kind == SpecialMethodKind::Regular ||
kind == SpecialMethodKind::Constructor) {
bool isLastParameter =
(paramIndex == params.size() - 1) ||
(paramIndex == params.size() - 2 && errorInfo &&
errorInfo->ErrorParameterIndex == params.size() - 1);
auto defaultArg = inferDefaultArgument(
param->getType(), optionalityOfParam,
importedName.getDeclName().getBaseName(), name.str(), paramIndex == 0,
isLastParameter, getNameImporter());
if (defaultArg != DefaultArgumentKind::None)
paramInfo->setDefaultArgumentKind(defaultArg);
}
swiftParams.push_back(paramInfo);
}
// If we have a constructor with no parameters and a name with an
// argument name, synthesize a Void parameter with that name.
if (kind == SpecialMethodKind::Constructor && params.empty() &&
argNames.size() == 1) {
addEmptyTupleParameter(argNames[0]);
}
if (importedName.hasCustomName() && argNames.size() != swiftParams.size()) {
// Note carefully: we're emitting a warning in the /Clang/ buffer.
auto &srcMgr = getClangASTContext().getSourceManager();
ClangSourceBufferImporter &bufferImporter =
getBufferImporterForDiagnostics();
SourceLoc methodLoc =
bufferImporter.resolveSourceLocation(srcMgr, clangDecl->getLocation());
if (methodLoc.isValid()) {
SwiftContext.Diags.diagnose(methodLoc, diag::invalid_swift_name_method,
swiftParams.size() < argNames.size(),
swiftParams.size(), argNames.size());
ModuleDecl *parentModule = dc->getParentModule();
if (parentModule != ImportedHeaderUnit->getParentModule()) {
SwiftContext.Diags.diagnose(
methodLoc, diag::unresolvable_clang_decl_is_a_framework_bug,
parentModule->getName().str());
}
}
return {Type(), false};
}
// Form the parameter list.
*bodyParams = ParameterList::create(SwiftContext, swiftParams);
if (clangDecl->hasAttr<clang::NoReturnAttr>()) {
origSwiftResultTy = SwiftContext.getNeverType();
swiftResultTy = SwiftContext.getNeverType();
}
if (errorInfo) {
foreignErrorInfo = getForeignErrorInfo(*errorInfo, errorParamType,
origSwiftResultTy);
}
return {swiftResultTy,
importedType.isImplicitlyUnwrapped()};
}
ImportedType ClangImporter::Implementation::importAccessorParamsAndReturnType(
const DeclContext *dc, const clang::ObjCPropertyDecl *property,
const clang::ObjCMethodDecl *clangDecl, bool isFromSystemModule,
ImportedName functionName, swift::ParameterList **params) {
// Note: We're using a pointer instead of a reference here to make it clear
// at the call site that this is an out-parameter.
assert(params && "'params' is a required out-parameter");
// Determine if the method is a property getter or setter.
bool isGetter;
if (clangDecl->parameters().empty())
isGetter = true;
else if (clangDecl->parameters().size() == 1)
isGetter = false;
else
llvm_unreachable("not a valid accessor");
// The member was defined in 'origDC', but is being imported into 'dc'.
// 'dc' must be a subclass or a type conforming to protocol.
// FIXME: Duplicated from importMethodParamsAndReturnType.
DeclContext *origDC = importDeclContextOf(property,
property->getDeclContext());
assert(origDC);
// Import the property type, independent of what kind of accessor this is.
auto importedType = importPropertyType(property, isFromSystemModule);
if (!importedType)
return {Type(), false};
auto propertyTy = mapGenericArgs(origDC, dc, importedType.getType());
bool isIUO = importedType.isImplicitlyUnwrapped();
// Now build up the resulting FunctionType and parameters.
Type resultTy;
if (isGetter) {
*params = ParameterList::createEmpty(SwiftContext);
resultTy = propertyTy;
} else {
const clang::ParmVarDecl *param = clangDecl->parameters().front();
ImportedName fullBodyName = importFullName(param, CurrentVersion);
Identifier bodyName = fullBodyName.getDeclName().getBaseIdentifier();
SourceLoc nameLoc = importSourceLoc(param->getLocation());
Identifier argLabel = functionName.getDeclName().getArgumentNames().front();
auto paramInfo
= createDeclWithClangNode<ParamDecl>(param, AccessLevel::Private,
/*let loc*/SourceLoc(),
/*label loc*/SourceLoc(),
argLabel, nameLoc, bodyName,
/*dummy DC*/ImportedHeaderUnit);
paramInfo->setSpecifier(ParamSpecifier::Default);
paramInfo->setInterfaceType(propertyTy);
*params = ParameterList::create(SwiftContext, paramInfo);
resultTy = SwiftContext.getVoidDecl()->getDeclaredInterfaceType();
isIUO = false;
}
return {resultTy, isIUO};
}
ModuleDecl *ClangImporter::Implementation::getStdlibModule() {
return SwiftContext.getStdlibModule(true);
}
ModuleDecl *ClangImporter::Implementation::getNamedModule(StringRef name) {
return SwiftContext.getLoadedModule(SwiftContext.getIdentifier(name));
}
static ModuleDecl *tryLoadModule(ASTContext &C,
Identifier moduleName,
bool importForwardDeclarations,
llvm::DenseMap<Identifier, ModuleDecl *>
&checkedModules) {
// If we've already done this check, return the cached result.
auto known = checkedModules.find(moduleName);
if (known != checkedModules.end())
return known->second;
ModuleDecl *module;
// If we're synthesizing forward declarations, we don't want to pull in
// the module too eagerly.
if (importForwardDeclarations)
module = C.getLoadedModule(moduleName);
else
module = C.getModule({ {moduleName, SourceLoc()} });
checkedModules[moduleName] = module;
return module;
}
ModuleDecl *ClangImporter::Implementation::tryLoadFoundationModule() {
return tryLoadModule(SwiftContext, SwiftContext.Id_Foundation,
ImportForwardDeclarations, checkedModules);
}
Type ClangImporter::Implementation::getNamedSwiftType(ModuleDecl *module,
StringRef name) {
if (!module)
return Type();
// Look for the type.
Identifier identifier = SwiftContext.getIdentifier(name);
SmallVector<ValueDecl *, 2> results;
// Check if the lookup we're about to perform a lookup within is
// a Clang module.
for (auto *file : module->getFiles()) {
if (auto clangUnit = dyn_cast<ClangModuleUnit>(file)) {
// If we have an overlay, look in the overlay. Otherwise, skip
// the lookup to avoid infinite recursion.
if (auto module = clangUnit->getOverlayModule())
module->lookupValue(identifier, NLKind::UnqualifiedLookup, results);
} else {
file->lookupValue(identifier, NLKind::UnqualifiedLookup, results);
}
}
if (results.size() != 1)
return Type();
auto decl = dyn_cast<TypeDecl>(results.front());
if (!decl)
return Type();
assert(!decl->hasClangNode() && "picked up the original type?");
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(decl))
return nominalDecl->getDeclaredType();
return decl->getDeclaredInterfaceType();
}
Type ClangImporter::Implementation::getNamedSwiftType(StringRef moduleName,
StringRef name) {
// Try to load the module.
auto module = tryLoadModule(SwiftContext,
SwiftContext.getIdentifier(moduleName),
ImportForwardDeclarations, checkedModules);
if (!module) return Type();
return getNamedSwiftType(module, name);
}
Decl *ClangImporter::Implementation::importDeclByName(StringRef name) {
auto &sema = Instance->getSema();
// Map the name. If we can't represent the Swift name in Clang, bail out now.
auto clangName = &getClangASTContext().Idents.get(name);
// Perform name lookup into the global scope.
// FIXME: Map source locations over.
clang::LookupResult lookupResult(sema, clangName, clang::SourceLocation(),
clang::Sema::LookupOrdinaryName);
lookupResult.setAllowHidden(true);
if (!sema.LookupName(lookupResult, /*Scope=*/nullptr)) {
return nullptr;
}
for (auto decl : lookupResult) {
if (auto swiftDecl =
importDecl(decl->getUnderlyingDecl(), CurrentVersion)) {
return swiftDecl;
}
}
return nullptr;
}
Type ClangImporter::Implementation::getNSObjectType() {
if (NSObjectTy)
return NSObjectTy;
if (auto decl = dyn_cast_or_null<ClassDecl>(importDeclByName("NSObject"))) {
NSObjectTy = decl->getDeclaredType();
return NSObjectTy;
}
return Type();
}
bool ClangImporter::Implementation::matchesHashableBound(Type type) {
Type NSObjectType = getNSObjectType();
if (!NSObjectType)
return false;
// Match generic parameters against their bounds.
if (auto *genericTy = type->getAs<GenericTypeParamType>()) {
if (auto *generic = genericTy->getDecl()) {
auto genericSig =
generic->getDeclContext()->getGenericSignatureOfContext();
if (genericSig && genericSig->getConformsTo(type).empty()) {
type = genericSig->getSuperclassBound(type);
if (!type)
return false;
}
}
}
// Existentials cannot match the Hashable bound.
if (type->isAnyExistentialType())
return false;
// Class type that inherits from NSObject.
if (NSObjectType->isExactSuperclassOf(type))
return true;
// Struct or enum type must have been bridged.
// TODO: Check that the bridged type is Hashable?
if (type->getStructOrBoundGenericStruct() ||
type->getEnumOrBoundGenericEnum()) {
auto nominal = type->getAnyNominal();
auto hashable = SwiftContext.getProtocol(KnownProtocolKind::Hashable);
SmallVector<ProtocolConformance *, 2> conformances;
return hashable &&
nominal->lookupConformance(nominal->getParentModule(), hashable,
conformances);
}
return false;
}
static Type getNamedProtocolType(ClangImporter::Implementation &impl,
StringRef name) {
auto &sema = impl.getClangSema();
auto clangName = &sema.getASTContext().Idents.get(name);
assert(clangName);
// Perform name lookup into the global scope.
clang::LookupResult lookupResult(sema, clangName, clang::SourceLocation(),
clang::Sema::LookupObjCProtocolName);
lookupResult.setAllowHidden(true);
if (!sema.LookupName(lookupResult, /*Scope=*/nullptr))
return Type();
for (auto decl : lookupResult) {
if (auto swiftDecl =
impl.importDecl(decl->getUnderlyingDecl(), impl.CurrentVersion)) {
if (auto protoDecl =
dynCastIgnoringCompatibilityAlias<ProtocolDecl>(swiftDecl)) {
return protoDecl->getDeclaredType();
}
}
}
return Type();
}
Type ClangImporter::Implementation::getNSObjectProtocolType() {
return getNamedProtocolType(*this, "NSObject");
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r15
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x13320, %rdx
nop
dec %rax
movl $0x61626364, (%rdx)
nop
nop
and $33202, %rdx
lea addresses_UC_ht+0x112e0, %r10
nop
nop
nop
xor $15242, %r11
mov $0x6162636465666768, %r12
movq %r12, %xmm1
vmovups %ymm1, (%r10)
cmp $10111, %r11
lea addresses_WC_ht+0x149e0, %r10
inc %r15
mov $0x6162636465666768, %r8
movq %r8, (%r10)
nop
nop
nop
nop
and $42989, %r10
lea addresses_WT_ht+0x1600, %rsi
lea addresses_WC_ht+0xabe0, %rdi
nop
nop
nop
nop
add $53392, %r11
mov $63, %rcx
rep movsq
nop
nop
add $29729, %r8
lea addresses_WC_ht+0xd298, %rdi
nop
nop
nop
nop
nop
cmp $64113, %r12
movl $0x61626364, (%rdi)
nop
inc %rdi
lea addresses_UC_ht+0x153e0, %rsi
nop
sub $17504, %r15
movups (%rsi), %xmm0
vpextrq $1, %xmm0, %rax
nop
dec %r8
lea addresses_WC_ht+0xb380, %rax
nop
and %rdi, %rdi
movb (%rax), %r11b
nop
cmp $6159, %r12
lea addresses_WT_ht+0x177e0, %rsi
lea addresses_WT_ht+0x4ce0, %rdi
nop
nop
nop
nop
and %r12, %r12
mov $35, %rcx
rep movsl
nop
sub $53454, %r11
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r15
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r15
push %r8
push %rdi
// Faulty Load
mov $0x7ff2f30000000be0, %r13
clflush (%r13)
nop
nop
nop
nop
nop
add $39194, %r8
vmovntdqa (%r13), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $1, %xmm6, %r15
lea oracles, %rdi
and $0xff, %r15
shlq $12, %r15
mov (%rdi,%r15,1), %r15
pop %rdi
pop %r8
pop %r15
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 32, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC_ht', 'same': True, 'size': 16, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'48': 1, '49': 4372, '00': 55, '47': 11, '6b': 1}
49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 47 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 00 49 49 49 49 49 49 49 00 49 49 49 47 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 00 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 00 49 49 49 49 49 49 49 49 49 49
*/
|
; A092041: Decimal expansion of cube root of e.
; 1,3,9,5,6,1,2,4,2,5,0,8,6,0,8,9,5,2,8,6,2,8,1,2,5,3,1,9,6,0,2,5,8,6,8,3,7,5,9,7,9,0,6,5,1,5,1,9,9,4,0,6,9,8,2,6,1,7,5,1,6,7,0,6,0,3,1,7,3,9,0,1,5,6,4,5,9,5,1,8,4,6,9,6,9,7,8,8,8,1,7,2,9,5,8,3,0,2,2,4
mov $2,1
mov $3,$0
mul $3,5
lpb $3
mul $2,$3
mul $2,3
add $1,$2
cmp $4,0
add $5,$4
div $1,$5
div $2,$5
sub $3,1
lpe
mov $6,10
pow $6,$0
div $2,$6
div $1,$2
add $1,$6
mod $1,10
mov $0,$1
|
; A maphack for Warcraft 3 1.24d. WC3 sets the visibility of the map every frame via a call to memset that
; looks like:
; 6F40B446 . 52 PUSH EDX
; 6F40B447 6A 00 PUSH 0
; 6F40B449 . 50 PUSH EAX
; 6F40B44A . E8 73643D00 CALL <JMP.&MSVCR80.memset>
;
; By changing the push 0 instruction to push 0fh, we reveal all the squares on the map. This method will
; cause a desync in multiplayer games.
;
; Originally written 2010/02/16 by attilathedud.
; System descriptors
.386
.model flat,stdcall
option casemap:none
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib
.data
dllname db "Game.dll"
toggle db 0
on db "Maphack on",0
off db "Maphack off",0
.data?
hookbase dd ?
ori_chat_out dd ?
ori_map_draw dd ?
ori_globalWC3class dd ?
.code
main:
; Save the base pointer and load in the stack pointer
push ebp
mov ebp,esp
; Check to see if the dll is being loaded validly.
mov eax,dword ptr ss:[ebp+0ch]
cmp eax,1
jnz @returnf
; Save eax on the stack for restoring after we create our thread.
push eax
; All of our functions reside in Game.dll which is dynamically loaded. Because of this, we
; have to get the base address of it and then add the offsets of the functions we need.
lea eax,dllname
push eax
call GetModuleHandle
; Load our functions with their values. Note that eax is adjusted with each add, i.e.
; hookbase's offset is 40b444h.
add eax,2fbf60h
mov ori_chat_out,eax
add eax,10f4e4h
mov hookbase,eax
add eax,5h
mov ori_map_draw,eax
add eax,6c098fh
mov ori_globalWC3class,eax
; Allocate a section of memory to hold the old protection type for when we unprotect code.
; Store this memory in ebx.
push 40h
push 1000h
push 4h
push 0
call VirtualAlloc
mov ebx,eax
; Unprotect the code that we intend to modify so that we can make changes to it.
push ebx
push 40h
push 5h
push hookbase
call VirtualProtect
; Before the call to memset, create a codecave that will jmp to our hook function.
; e9h is the opcode to jmp, with the address of the jump being calculated by subtracting
; the address of the function to jump to from our current location.
mov eax,hookbase
mov byte ptr ds:[eax],0e9h
lea ecx,@hook
sub ecx,ori_map_draw
mov dword ptr ds:[eax+1],ecx
; Reprotect the code we just modified.
push ebx
push 40h
push 5h
push hookbase
call VirtualProtect
; Free the memory we allocated to hold the protection type.
push 4000h
push 4h
push ebx
call VirtualFree
; Create a thread that will check for us pressing a hotkey
push 0
push 0
push 0
push @hotkey
push 0
push 0
call CreateThread
; Restore the stack and exit dllmain
pop eax
@returnf:
leave
retn 0ch
; The hotkey thread will scan for F5 being pressed and then checks 6fae54d3h to see if
; we are currently in a game or not. The value of toggle is switched between 0 and 0fh.
; Depending on the value of toggle, the chat out function is called with either an on or off
; value.
;
; @@ sets up a temporary label. @B jumps back to the last defined temporary label.
@hotkey:
@@:
push 74h
call GetAsyncKeyState
and eax,1
test eax,eax
jz @b
cmp dword ptr ds:[6fae54d3h],09h
jl @b
cmp toggle,0
jnz @toggle_off
mov toggle,0fh
lea edx,on
call @chat_out
jmp @b
@toggle_off:
mov toggle,0
lea edx,off
call @chat_out
jmp @b
retn
; Our hook function.
@hook:
; The instructions that we replaced with our codecave up in dll main.
add edx,edx
push edx
; Clear out edx and set its value to toggle's value.
xor edx,edx
mov dl,byte ptr ds:[toggle]
push edx
; Jump back to the original code.
jmp ori_map_draw
; Function that calls WC3's internal chat out function to display messages. Expects
; edx to hold the address of the text you want displayed.
@chat_out:
push 1fh
push 0
push edx
push 0
mov ecx,dword ptr ds:[ori_globalWC3class]
mov ecx,dword ptr ds:[ecx]
call ori_chat_out
retn
end main
|
; A109794: a(2n) = A001906(n+1), a(2n+1) = A002878(n).
; Submitted by Jamie Morken(s3)
; 1,1,3,4,8,11,21,29,55,76,144,199,377,521,987,1364,2584,3571,6765,9349,17711,24476,46368,64079,121393,167761,317811,439204,832040,1149851,2178309,3010349,5702887,7881196,14930352,20633239,39088169,54018521,102334155,141422324,267914296,370248451,701408733,969323029,1836311903,2537720636,4807526976,6643838879,12586269025,17393796001,32951280099,45537549124,86267571272,119218851371,225851433717,312119004989,591286729879,817138163596,1548008755920,2139295485799,4052739537881,5600748293801
mov $2,1
lpb $0
sub $0,2
add $1,$2
add $2,$1
lpe
lpb $0
sub $0,1
add $2,$1
lpe
mov $0,$2
add $0,$1
|
//===-- XCoreFrameLowering.cpp - Frame info for XCore Target --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains XCore frame information that doesn't fit anywhere else
// cleanly...
//
//===----------------------------------------------------------------------===//
#include "XCoreFrameLowering.h"
#include "XCore.h"
#include "XCoreInstrInfo.h"
#include "XCoreMachineFunctionInfo.h"
#include "XCoreSubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm> // std::sort
using namespace llvm;
static const unsigned FramePtr = XCore::R10;
static const int MaxImmU16 = (1<<16) - 1;
// helper functions. FIXME: Eliminate.
static inline bool isImmU6(unsigned val) {
return val < (1 << 6);
}
static inline bool isImmU16(unsigned val) {
return val < (1 << 16);
}
// Helper structure with compare function for handling stack slots.
namespace {
struct StackSlotInfo {
int FI;
int Offset;
unsigned Reg;
StackSlotInfo(int f, int o, int r) : FI(f), Offset(o), Reg(r){};
};
} // end anonymous namespace
static bool CompareSSIOffset(const StackSlotInfo& a, const StackSlotInfo& b) {
return a.Offset < b.Offset;
}
static void EmitDefCfaRegister(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
const DebugLoc &dl, const TargetInstrInfo &TII,
MachineFunction &MF, unsigned DRegNum) {
unsigned CFIIndex = MF.addFrameInst(
MCCFIInstruction::createDefCfaRegister(nullptr, DRegNum));
BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
}
static void EmitDefCfaOffset(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
const DebugLoc &dl, const TargetInstrInfo &TII,
int Offset) {
MachineFunction &MF = *MBB.getParent();
unsigned CFIIndex =
MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
}
static void EmitCfiOffset(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI, const DebugLoc &dl,
const TargetInstrInfo &TII, unsigned DRegNum,
int Offset) {
MachineFunction &MF = *MBB.getParent();
unsigned CFIIndex = MF.addFrameInst(
MCCFIInstruction::createOffset(nullptr, DRegNum, Offset));
BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
}
/// The SP register is moved in steps of 'MaxImmU16' towards the bottom of the
/// frame. During these steps, it may be necessary to spill registers.
/// IfNeededExtSP emits the necessary EXTSP instructions to move the SP only
/// as far as to make 'OffsetFromBottom' reachable using an STWSP_lru6.
/// \param OffsetFromTop the spill offset from the top of the frame.
/// \param [in,out] Adjusted the current SP offset from the top of the frame.
static void IfNeededExtSP(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI, const DebugLoc &dl,
const TargetInstrInfo &TII, int OffsetFromTop,
int &Adjusted, int FrameSize, bool emitFrameMoves) {
while (OffsetFromTop > Adjusted) {
assert(Adjusted < FrameSize && "OffsetFromTop is beyond FrameSize");
int remaining = FrameSize - Adjusted;
int OpImm = (remaining > MaxImmU16) ? MaxImmU16 : remaining;
int Opcode = isImmU6(OpImm) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(OpImm);
Adjusted += OpImm;
if (emitFrameMoves)
EmitDefCfaOffset(MBB, MBBI, dl, TII, Adjusted*4);
}
}
/// The SP register is moved in steps of 'MaxImmU16' towards the top of the
/// frame. During these steps, it may be necessary to re-load registers.
/// IfNeededLDAWSP emits the necessary LDAWSP instructions to move the SP only
/// as far as to make 'OffsetFromTop' reachable using an LDAWSP_lru6.
/// \param OffsetFromTop the spill offset from the top of the frame.
/// \param [in,out] RemainingAdj the current SP offset from the top of the
/// frame.
static void IfNeededLDAWSP(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI, const DebugLoc &dl,
const TargetInstrInfo &TII, int OffsetFromTop,
int &RemainingAdj) {
while (OffsetFromTop < RemainingAdj - MaxImmU16) {
assert(RemainingAdj && "OffsetFromTop is beyond FrameSize");
int OpImm = (RemainingAdj > MaxImmU16) ? MaxImmU16 : RemainingAdj;
int Opcode = isImmU6(OpImm) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(OpImm);
RemainingAdj -= OpImm;
}
}
/// Creates an ordered list of registers that are spilled
/// during the emitPrologue/emitEpilogue.
/// Registers are ordered according to their frame offset.
/// As offsets are negative, the largest offsets will be first.
static void GetSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
MachineFrameInfo &MFI, XCoreFunctionInfo *XFI,
bool fetchLR, bool fetchFP) {
if (fetchLR) {
int Offset = MFI.getObjectOffset(XFI->getLRSpillSlot());
SpillList.push_back(StackSlotInfo(XFI->getLRSpillSlot(),
Offset,
XCore::LR));
}
if (fetchFP) {
int Offset = MFI.getObjectOffset(XFI->getFPSpillSlot());
SpillList.push_back(StackSlotInfo(XFI->getFPSpillSlot(),
Offset,
FramePtr));
}
llvm::sort(SpillList, CompareSSIOffset);
}
/// Creates an ordered list of EH info register 'spills'.
/// These slots are only used by the unwinder and calls to llvm.eh.return().
/// Registers are ordered according to their frame offset.
/// As offsets are negative, the largest offsets will be first.
static void GetEHSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
MachineFrameInfo &MFI, XCoreFunctionInfo *XFI,
const Constant *PersonalityFn,
const TargetLowering *TL) {
assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
const int *EHSlot = XFI->getEHSpillSlot();
SpillList.push_back(
StackSlotInfo(EHSlot[0], MFI.getObjectOffset(EHSlot[0]),
TL->getExceptionPointerRegister(PersonalityFn)));
SpillList.push_back(
StackSlotInfo(EHSlot[0], MFI.getObjectOffset(EHSlot[1]),
TL->getExceptionSelectorRegister(PersonalityFn)));
llvm::sort(SpillList, CompareSSIOffset);
}
static MachineMemOperand *getFrameIndexMMO(MachineBasicBlock &MBB,
int FrameIndex,
MachineMemOperand::Flags flags) {
MachineFunction *MF = MBB.getParent();
const MachineFrameInfo &MFI = MF->getFrameInfo();
MachineMemOperand *MMO = MF->getMachineMemOperand(
MachinePointerInfo::getFixedStack(*MF, FrameIndex), flags,
MFI.getObjectSize(FrameIndex), MFI.getObjectAlignment(FrameIndex));
return MMO;
}
/// Restore clobbered registers with their spill slot value.
/// The SP will be adjusted at the same time, thus the SpillList must be ordered
/// with the largest (negative) offsets first.
static void RestoreSpillList(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
const DebugLoc &dl, const TargetInstrInfo &TII,
int &RemainingAdj,
SmallVectorImpl<StackSlotInfo> &SpillList) {
for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
int OffsetFromTop = - SpillList[i].Offset/4;
IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
int Offset = RemainingAdj - OffsetFromTop;
int Opcode = isImmU6(Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
BuildMI(MBB, MBBI, dl, TII.get(Opcode), SpillList[i].Reg)
.addImm(Offset)
.addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
MachineMemOperand::MOLoad));
}
}
//===----------------------------------------------------------------------===//
// XCoreFrameLowering:
//===----------------------------------------------------------------------===//
XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
: TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 4, 0) {
// Do nothing
}
bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
return MF.getTarget().Options.DisableFramePointerElim(MF) ||
MF.getFrameInfo().hasVarSizedObjects();
}
void XCoreFrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo &MFI = MF.getFrameInfo();
MachineModuleInfo *MMI = &MF.getMMI();
const MCRegisterInfo *MRI = MMI->getContext().getRegisterInfo();
const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
// Debug location must be unknown since the first debug location is used
// to determine the end of the prologue.
DebugLoc dl;
if (MFI.getMaxAlignment() > getStackAlignment())
report_fatal_error("emitPrologue unsupported alignment: "
+ Twine(MFI.getMaxAlignment()));
const AttributeList &PAL = MF.getFunction().getAttributes();
if (PAL.hasAttrSomewhere(Attribute::Nest))
BuildMI(MBB, MBBI, dl, TII.get(XCore::LDWSP_ru6), XCore::R11).addImm(0);
// FIX: Needs addMemOperand() but can't use getFixedStack() or getStack().
// Work out frame sizes.
// We will adjust the SP in stages towards the final FrameSize.
assert(MFI.getStackSize()%4 == 0 && "Misaligned frame size");
const int FrameSize = MFI.getStackSize() / 4;
int Adjusted = 0;
bool saveLR = XFI->hasLRSpillSlot();
bool UseENTSP = saveLR && FrameSize
&& (MFI.getObjectOffset(XFI->getLRSpillSlot()) == 0);
if (UseENTSP)
saveLR = false;
bool FP = hasFP(MF);
bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
if (UseENTSP) {
// Allocate space on the stack at the same time as saving LR.
Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
int Opcode = isImmU6(Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
MBB.addLiveIn(XCore::LR);
MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode));
MIB.addImm(Adjusted);
MIB->addRegisterKilled(XCore::LR, MF.getSubtarget().getRegisterInfo(),
true);
if (emitFrameMoves) {
EmitDefCfaOffset(MBB, MBBI, dl, TII, Adjusted*4);
unsigned DRegNum = MRI->getDwarfRegNum(XCore::LR, true);
EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, 0);
}
}
// If necessary, save LR and FP to the stack, as we EXTSP.
SmallVector<StackSlotInfo,2> SpillList;
GetSpillList(SpillList, MFI, XFI, saveLR, FP);
// We want the nearest (negative) offsets first, so reverse list.
std::reverse(SpillList.begin(), SpillList.end());
for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
int OffsetFromTop = - SpillList[i].Offset/4;
IfNeededExtSP(MBB, MBBI, dl, TII, OffsetFromTop, Adjusted, FrameSize,
emitFrameMoves);
int Offset = Adjusted - OffsetFromTop;
int Opcode = isImmU6(Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
MBB.addLiveIn(SpillList[i].Reg);
BuildMI(MBB, MBBI, dl, TII.get(Opcode))
.addReg(SpillList[i].Reg, RegState::Kill)
.addImm(Offset)
.addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
MachineMemOperand::MOStore));
if (emitFrameMoves) {
unsigned DRegNum = MRI->getDwarfRegNum(SpillList[i].Reg, true);
EmitCfiOffset(MBB, MBBI, dl, TII, DRegNum, SpillList[i].Offset);
}
}
// Complete any remaining Stack adjustment.
IfNeededExtSP(MBB, MBBI, dl, TII, FrameSize, Adjusted, FrameSize,
emitFrameMoves);
assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
if (FP) {
// Set the FP from the SP.
BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr).addImm(0);
if (emitFrameMoves)
EmitDefCfaRegister(MBB, MBBI, dl, TII, MF,
MRI->getDwarfRegNum(FramePtr, true));
}
if (emitFrameMoves) {
// Frame moves for callee saved.
for (const auto &SpillLabel : XFI->getSpillLabels()) {
MachineBasicBlock::iterator Pos = SpillLabel.first;
++Pos;
const CalleeSavedInfo &CSI = SpillLabel.second;
int Offset = MFI.getObjectOffset(CSI.getFrameIdx());
unsigned DRegNum = MRI->getDwarfRegNum(CSI.getReg(), true);
EmitCfiOffset(MBB, Pos, dl, TII, DRegNum, Offset);
}
if (XFI->hasEHSpillSlot()) {
// The unwinder requires stack slot & CFI offsets for the exception info.
// We do not save/spill these registers.
const Function *Fn = &MF.getFunction();
const Constant *PersonalityFn =
Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
SmallVector<StackSlotInfo, 2> SpillList;
GetEHSpillList(SpillList, MFI, XFI, PersonalityFn,
MF.getSubtarget().getTargetLowering());
assert(SpillList.size()==2 && "Unexpected SpillList size");
EmitCfiOffset(MBB, MBBI, dl, TII,
MRI->getDwarfRegNum(SpillList[0].Reg, true),
SpillList[0].Offset);
EmitCfiOffset(MBB, MBBI, dl, TII,
MRI->getDwarfRegNum(SpillList[1].Reg, true),
SpillList[1].Offset);
}
}
}
void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineFrameInfo &MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
DebugLoc dl = MBBI->getDebugLoc();
unsigned RetOpcode = MBBI->getOpcode();
// Work out frame sizes.
// We will adjust the SP in stages towards the final FrameSize.
int RemainingAdj = MFI.getStackSize();
assert(RemainingAdj%4 == 0 && "Misaligned frame size");
RemainingAdj /= 4;
if (RetOpcode == XCore::EH_RETURN) {
// 'Restore' the exception info the unwinder has placed into the stack
// slots.
const Function *Fn = &MF.getFunction();
const Constant *PersonalityFn =
Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr;
SmallVector<StackSlotInfo, 2> SpillList;
GetEHSpillList(SpillList, MFI, XFI, PersonalityFn,
MF.getSubtarget().getTargetLowering());
RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
// Return to the landing pad.
unsigned EhStackReg = MBBI->getOperand(0).getReg();
unsigned EhHandlerReg = MBBI->getOperand(1).getReg();
BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(EhStackReg);
BuildMI(MBB, MBBI, dl, TII.get(XCore::BAU_1r)).addReg(EhHandlerReg);
MBB.erase(MBBI); // Erase the previous return instruction.
return;
}
bool restoreLR = XFI->hasLRSpillSlot();
bool UseRETSP = restoreLR && RemainingAdj
&& (MFI.getObjectOffset(XFI->getLRSpillSlot()) == 0);
if (UseRETSP)
restoreLR = false;
bool FP = hasFP(MF);
if (FP) // Restore the stack pointer.
BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(FramePtr);
// If necessary, restore LR and FP from the stack, as we EXTSP.
SmallVector<StackSlotInfo,2> SpillList;
GetSpillList(SpillList, MFI, XFI, restoreLR, FP);
RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
if (RemainingAdj) {
// Complete all but one of the remaining Stack adjustments.
IfNeededLDAWSP(MBB, MBBI, dl, TII, 0, RemainingAdj);
if (UseRETSP) {
// Fold prologue into return instruction
assert(RetOpcode == XCore::RETSP_u6
|| RetOpcode == XCore::RETSP_lu6);
int Opcode = isImmU6(RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode))
.addImm(RemainingAdj);
for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
MIB->addOperand(MBBI->getOperand(i)); // copy any variadic operands
MBB.erase(MBBI); // Erase the previous return instruction.
} else {
int Opcode = isImmU6(RemainingAdj) ? XCore::LDAWSP_ru6 :
XCore::LDAWSP_lru6;
BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(RemainingAdj);
// Don't erase the return instruction.
}
} // else Don't erase the return instruction.
}
bool XCoreFrameLowering::
spillCalleeSavedRegisters(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const std::vector<CalleeSavedInfo> &CSI,
const TargetRegisterInfo *TRI) const {
if (CSI.empty())
return true;
MachineFunction *MF = MBB.getParent();
const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
DebugLoc DL;
if (MI != MBB.end() && !MI->isDebugInstr())
DL = MI->getDebugLoc();
for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
it != CSI.end(); ++it) {
unsigned Reg = it->getReg();
assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
"LR & FP are always handled in emitPrologue");
// Add the callee-saved register as live-in. It's killed at the spill.
MBB.addLiveIn(Reg);
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
TII.storeRegToStackSlot(MBB, MI, Reg, true, it->getFrameIdx(), RC, TRI);
if (emitFrameMoves) {
auto Store = MI;
--Store;
XFI->getSpillLabels().push_back(std::make_pair(Store, *it));
}
}
return true;
}
bool XCoreFrameLowering::
restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
std::vector<CalleeSavedInfo> &CSI,
const TargetRegisterInfo *TRI) const{
MachineFunction *MF = MBB.getParent();
const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
bool AtStart = MI == MBB.begin();
MachineBasicBlock::iterator BeforeI = MI;
if (!AtStart)
--BeforeI;
for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
it != CSI.end(); ++it) {
unsigned Reg = it->getReg();
assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
"LR & FP are always handled in emitEpilogue");
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
TII.loadRegFromStackSlot(MBB, MI, Reg, it->getFrameIdx(), RC, TRI);
assert(MI != MBB.begin() &&
"loadRegFromStackSlot didn't insert any code!");
// Insert in reverse order. loadRegFromStackSlot can insert multiple
// instructions.
if (AtStart)
MI = MBB.begin();
else {
MI = BeforeI;
++MI;
}
}
return true;
}
// This function eliminates ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
MachineBasicBlock::iterator XCoreFrameLowering::eliminateCallFramePseudoInstr(
MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
if (!hasReservedCallFrame(MF)) {
// Turn the adjcallstackdown instruction into 'extsp <amt>' and the
// adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
MachineInstr &Old = *I;
uint64_t Amount = Old.getOperand(0).getImm();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
assert(Amount%4 == 0);
Amount /= 4;
bool isU6 = isImmU6(Amount);
if (!isU6 && !isImmU16(Amount)) {
// FIX could emit multiple instructions in this case.
#ifndef NDEBUG
errs() << "eliminateCallFramePseudoInstr size too big: "
<< Amount << "\n";
#endif
llvm_unreachable(nullptr);
}
MachineInstr *New;
if (Old.getOpcode() == XCore::ADJCALLSTACKDOWN) {
int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
New = BuildMI(MF, Old.getDebugLoc(), TII.get(Opcode)).addImm(Amount);
} else {
assert(Old.getOpcode() == XCore::ADJCALLSTACKUP);
int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
New = BuildMI(MF, Old.getDebugLoc(), TII.get(Opcode), XCore::SP)
.addImm(Amount);
}
// Replace the pseudo instruction with a new instruction...
MBB.insert(I, New);
}
}
return MBB.erase(I);
}
void XCoreFrameLowering::determineCalleeSaves(MachineFunction &MF,
BitVector &SavedRegs,
RegScavenger *RS) const {
TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
const MachineRegisterInfo &MRI = MF.getRegInfo();
bool LRUsed = MRI.isPhysRegModified(XCore::LR);
if (!LRUsed && !MF.getFunction().isVarArg() &&
MF.getFrameInfo().estimateStackSize(MF))
// If we need to extend the stack it is more efficient to use entsp / retsp.
// We force the LR to be saved so these instructions are used.
LRUsed = true;
if (MF.callsUnwindInit() || MF.callsEHReturn()) {
// The unwinder expects to find spill slots for the exception info regs R0
// & R1. These are used during llvm.eh.return() to 'restore' the exception
// info. N.B. we do not spill or restore R0, R1 during normal operation.
XFI->createEHSpillSlot(MF);
// As we will have a stack, we force the LR to be saved.
LRUsed = true;
}
if (LRUsed) {
// We will handle the LR in the prologue/epilogue
// and allocate space on the stack ourselves.
SavedRegs.reset(XCore::LR);
XFI->createLRSpillSlot(MF);
}
if (hasFP(MF))
// A callee save register is used to hold the FP.
// This needs saving / restoring in the epilogue / prologue.
XFI->createFPSpillSlot(MF);
}
void XCoreFrameLowering::
processFunctionBeforeFrameFinalized(MachineFunction &MF,
RegScavenger *RS) const {
assert(RS && "requiresRegisterScavenging failed");
MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterClass &RC = XCore::GRRegsRegClass;
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
// Reserve slots close to SP or frame pointer for Scavenging spills.
// When using SP for small frames, we don't need any scratch registers.
// When using SP for large frames, we may need 2 scratch registers.
// When using FP, for large or small frames, we may need 1 scratch register.
unsigned Size = TRI.getSpillSize(RC);
unsigned Align = TRI.getSpillAlignment(RC);
if (XFI->isLargeFrame(MF) || hasFP(MF))
RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
if (XFI->isLargeFrame(MF) && !hasFP(MF))
RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
}
|
; A221957: Number of n X n rook placements avoiding the pattern 012.
; Submitted by Jon Maiga
; 1,2,7,31,159,921,5988,43632,355491,3223729,32329668,355979064,4273100846,55555511298,777797216472,11667035805840,186672873433635,3173440015174905,57121924810715940,1085316589076234760,21706331850447959610,455832969128536089030,10028325321879843440520,230651482407353114495760,5535635577792598549739790,138390889444878169046713626,3598163125567080354481028328,97150404390312143040700588912,2720211322928743829484916869756,78886128364933586088695838993444,2366583850948007641793165952234032
mov $3,2
lpb $0
sub $0,1
add $1,1
mov $2,$1
mul $2,2
bin $2,$1
mul $3,$1
add $3,$2
lpe
mov $0,$3
div $0,2
|
; A196593: Number of fixed tree-like convex polyominoes.
; 1,2,6,18,51,134,328,758,1677,3594,7530,15530,31687,64190,129420,260142,521889,1045730,2093806,4190402,8384091,16772022,33548496,67102118,134210101,268426874,536861298,1073731098,2147471727,4294954094,8589920020,17179853150,34359720777,68719457490,137438932470,274877884082,549755789059,1099511600870,2199023226456,4398046479702,8796092988381,17592186008042,35184372049786,70368744135818,140737488310551,281474976662814,562949953370268,1125899906788238,2251799813627377,4503599627308994
mov $5,2
mov $6,$0
lpb $0
sub $0,1
add $4,$5
add $2,$4
sub $2,1
add $3,$6
mul $5,2
add $6,$2
lpe
add $3,1
add $1,$3
mov $0,$1
|
; A143433: Expansion of f(-x, x^3) in powers of x where f(,) is Ramanujan's general theta function.
; Submitted by Jamie Morken(s3)
; 1,-1,0,1,0,0,-1,0,0,0,-1,0,0,0,0,1,0,0,0,0,0,-1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0
mov $2,$0
lpb $0
mov $0,$2
seq $0,25682 ; Exponent of 9 (value of j) in n-th number of form 8^i*9^j.
lpe
sub $0,1
sub $2,$0
div $2,2
bin $0,$2
|
; A127069: Number of lines in a Pauli graph of order n.
; 15,45,153,561,2145,8385,33153,131841,525825,2100225,8394753,33566721,134242305,536920065,2147581953,8590131201,34360131585,137439739905,549757386753,2199026401281,8796099313665,35184384671745
add $0,2
mov $1,2
pow $1,$0
add $1,2
bin $1,2
mov $0,$1
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbRGBAPixelConverter_hxx
#define otbRGBAPixelConverter_hxx
#include "otbRGBAPixelConverter.h"
namespace otb
{
//Base
template <class TInternalInputPixelType, class TOutputPixelType>
typename RGBAPixelConverter<TInternalInputPixelType,
TOutputPixelType>
::OutputPixelType
RGBAPixelConverter<TInternalInputPixelType,
TOutputPixelType>
::Convert(InputPixelType input)
{
double result;
result = (
( 2125.0 * static_cast<double>(input[0]) +
7154.0 * static_cast<double>(input[1]) +
0721.0 * static_cast<double>(input[2])) / 10000.0); //alpha not supported yet
return (static_cast<OutputPixelType>(result));
}
//RGBA to RGBA
template <class TInternalInputPixelType, class TInternalOutputPixelType>
typename RGBAPixelConverter<TInternalInputPixelType,
typename itk::RGBAPixel<TInternalOutputPixelType> >
::OutputPixelType
RGBAPixelConverter<TInternalInputPixelType,
typename itk::RGBAPixel<TInternalOutputPixelType> >
::Convert(InputPixelType input)
{
OutputPixelType result;
result[0] = static_cast<TInternalOutputPixelType>(input[0]);
result[1] = static_cast<TInternalOutputPixelType>(input[1]);
result[2] = static_cast<TInternalOutputPixelType>(input[2]);
result[3] = static_cast<TInternalOutputPixelType>(input[3]);
return result;
}
//RGBA to RGB
template <class TInternalInputPixelType, class TInternalOutputPixelType>
typename RGBAPixelConverter<TInternalInputPixelType,
typename itk::RGBPixel<TInternalOutputPixelType> >
::OutputPixelType
RGBAPixelConverter<TInternalInputPixelType,
typename itk::RGBPixel<TInternalOutputPixelType> >
::Convert(InputPixelType input)
{
OutputPixelType result;
result[0] = static_cast<TInternalOutputPixelType>(input[0]);
result[1] = static_cast<TInternalOutputPixelType>(input[1]);
result[2] = static_cast<TInternalOutputPixelType>(input[2]);
return result;
}
} // end namespace otb
#endif
|
TITLE Assignment Three (Assign3.asm)
; Name: Abhijeet Chopra
; CWID: 50180612
; Date: 17 Nov,16
; Due : 11:59pm, Wednesday, 30 Nov
; Program Description:
;
; Step1: Write an assembly procedure which computes the following:
; int f(n) /* n is a positive integer */
; if (n<=3) return 1;
; /* else */
; return 3*f(n-1)+2*f(n-2)+f(n-3);
;
; Step 2: After completing Step 1, write an assembly program that computes and displays in a separate line the following:
; i f(i)
; for all integers i, from i=1 to 15.
; The initial part of the output will look as the following:
;
; 1 1
; 2 1
; 3 1
; 4 6
; 5 21
; 6 76
; 7 276
; . . .
;
INCLUDE Irvine32.inc
INCLUDE Macros.inc
.DATA
.CODE
main PROC
call Clrscr ; clears console
;call Crlf ; writes end of line sequence to standard output
mWriteLn "---------------------"
mWriteLn "Name: Abhijeet Chopra"
mWriteLn "CWID: 50180612"
mWriteLn "Desc: Assignment #3"
mWriteLn "Date: 17 Nov,16"
mWriteLn "---------------------"
mWriteLn " "
call ClearRegs
mov eax,6
;call DumpRegs ; for testing
;call DumpRegsInt
call abhi
;call DumpRegsInt ; for testing
;call DumpRegs
call PrintResult
exit
main ENDP
;------------------------
abhi PROC USES eax ecx edx
;
; Description : Recursive procedure receives n in EAX and calculates and returns f(n) in EBX
; Receives : EAX
; Returns : EBX
; Requires :
;mWriteLn "Procedure abhi called!"
;mov edx,0
.IF eax <= 3
;mWriteLn "IF"
; return 1
mov ebx,1
;call DumpRegsInt
.ELSE
;mWriteLn "ELSE"
; return 3*f(n-1)+2*f(n-2)+f(n-3)
; 3*f(n-1)
sub eax,1 ; eax = n-1
call abhi ; ebx = f(n-1)
push eax
mov eax,3
mul ebx ; ebx = 3*f(n-1)
mov ebx,eax
pop eax
push ebx ; stack = 3*f(n-1)
; 2*f(n-2)
sub eax,1 ; eax = n-2
call abhi ; ebx = f(n-2)
push eax
mov eax,2
mul ebx ; ebx = 2*f(n-2)
mov ebx,eax
pop eax
push ebx ; stack = 2*f(n-2)
; f(n-3)
sub eax,1 ; eax = n-3
call abhi ; ebx = f(n-3)
pop edx ; edx = 2*f(n-2)
add ebx,edx ; ebx = 2*f(n-2)+f(n-3)
pop edx ; edx = 3*f(n-3)
add ebx,edx ; ebx = 3*f(n-1)+2*f(n-2)+f(n-3)
;call DumpRegsInt
.ENDIF
ret
abhi ENDP
;------------------------
DumpRegsInt PROC
;
; Description : Prints integer value of registers on console
; Receives : EAX,EBX,ECX,EDX,ESI,EDI
; Returns : nothing
; Requires :
push eax
call crlf
mWrite " EAX = "
call WriteInt
call crlf
mWrite " EBX = "
mov eax,ebx
call WriteInt
call crlf
mWrite " ECX = "
mov eax,ecx
call WriteInt
call crlf
mWrite " EDX = "
mov eax,edx
call WriteInt
call crlf
mWrite " ESI = "
mov eax,esi
call WriteInt
call crlf
mWrite " EDI = "
mov eax,edi
call WriteInt
call crlf
call crlf
pop eax
ret
DumpRegsInt ENDP
;------------------------
ClearRegs PROC
;
; Description : Clears all registers
; Receives : nothing
; Returns : nothing
; Requires : EAX,EBX,ECX,EDX,ESI,EDI
mov eax,0
mov ebx,0
mov ecx,0
mov edx,0
mov esi,0
mov edi,0
ret
ClearRegs ENDP
;------------------------
PrintResult PROC uses EAX EBX ECX EDX ESI EDI
;
; Description : Prints n and f(n) from n = 1 to 15
; Receives :
; Returns :
; Requires : abhi
call ClearRegs
mWriteLn "n f(n)"
mWriteLn "------------"
L1:
inc ecx ; incrementing ECX
cmp ecx,15 ; compare ECX with 15
jg L2 ; jump to L2 if ECX > 15
mov eax,ecx ; EAX = ECX
call WriteDec ; print EAX = ECX = n
call abhi ; call procedure abhi and evaluate f(ECX)
mWrite " "
mov eax,ebx ; EAX = EBX
call WriteDec ; print EAX = EBX = f(ECX) = f(n)
call crlf
jmp L1 ; unconditional jump to L1
L2:
ret
PrintResult ENDP
END main
|
; A127262: a(0)=2, a(1)=2, a(n) = 2*a(n-1) + 12*a(n-2).
; 2,2,28,80,496,1952,9856,43136,204544,926720,4307968,19736576,91168768,419176448,1932378112,8894873600,40978284544,188695052288,869129519104,4002599665664,18434753560576,84900703109120
mov $4,$0
mov $5,$0
add $5,1
lpb $5,1
mov $0,$4
sub $5,1
sub $0,$5
mov $13,$0
mov $15,2
lpb $15,1
mov $0,$13
sub $15,1
add $0,$15
sub $0,1
mov $9,$0
mov $11,2
lpb $11,1
mov $0,$9
sub $11,1
add $0,$11
mov $2,0
mov $3,0
mov $8,2
lpb $0,1
sub $0,1
mov $7,$3
mov $3,$2
mul $3,6
add $8,$7
mul $8,2
mov $2,$8
lpe
mov $7,$2
mov $12,$11
lpb $12,1
mov $10,$7
sub $12,1
lpe
lpe
lpb $9,1
mov $9,0
sub $10,$7
lpe
mov $6,$15
mov $7,$10
lpb $6,1
sub $6,1
mov $14,$7
lpe
lpe
lpb $13,1
mov $13,0
sub $14,$7
lpe
mov $7,$14
div $7,4
mul $7,2
add $1,$7
lpe
|
; A026608: a(n) = number of 2's between n-th 1 and (n+1)st 1 in A026600.
; 2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,2,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,0,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,2,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,0,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,1,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,2,0,1,1,1,2,0,2,0,1,1,2,0,2,0,2,0,1,1,2,0,2,0,1,1,1,2,1,0,1,1,1,2,0,2
mov $3,2
mov $4,$0
lpb $3
mov $0,$4
sub $3,1
add $0,$3
cal $0,26601 ; a(n) is the n-th number k such that s(k) = 1, where s = A026600.
div $0,3
mov $2,$3
mov $5,$0
lpb $2
mov $1,$5
sub $2,1
lpe
lpe
lpb $4
sub $1,$5
mov $4,0
lpe
|
#include "stdafx.h"
#include "../xrRender/du_sphere.h"
#include "../xrRenderDX10/dx10BufferUtils.h"
void CRenderTarget::accum_point_geom_create()
{
// vertices
{
u32 vCount = DU_SPHERE_NUMVERTEX;
u32 vSize = 3*4;
R_CHK( dx10BufferUtils::CreateVertexBuffer( &g_accum_point_vb, du_sphere_vertices, vCount*vSize ) );
}
// Indices
{
u32 iCount = DU_SPHERE_NUMFACES*3;
R_CHK( dx10BufferUtils::CreateIndexBuffer( &g_accum_point_ib, du_sphere_faces, iCount*2) );
}
}
void CRenderTarget::accum_point_geom_destroy()
{
#ifdef DEBUG
_SHOW_REF("g_accum_point_ib",g_accum_point_ib);
#endif // DEBUG
_RELEASE(g_accum_point_ib);
#ifdef DEBUG
_SHOW_REF("g_accum_point_vb",g_accum_point_vb);
#endif // DEBUG
_RELEASE(g_accum_point_vb);
}
|
.const BASIC = $0401
.const GLOBALS = $0470
.const PETSCIITABLE = $04f0
.const MAIN = $0539 // 1337
.const ZP_BACKUP = $7d00
.const VVRAM = $7e00
.const VRAM = $8000
.const VVRAM_SIZE = $0160
.const VVRAM_END = VVRAM + VVRAM_SIZE
.const VVRAM_TEMP = $7000
// VVRAM IS 88x32 pixel (80x32 + padding left and right 4px)
// which is 22x16 bytes = #352 ($0160)
// we dont need floating point kernal stuff, so we can use this area of the zero page
.const ZP1 = $54
.const ZP2 = $56
.const ZP3 = $58
.const ZP4 = $5a
.const ZP5 = $5c
.const ZP6 = $5e
.const ZP7 = $60
.const ZP8 = $62 // PRNG 16
.const ZP10 = $66
.const ZP11 = $67
.const ZP12 = $68
.const ZP13 = $69 // PRNG 8
.const ZP14 = $6a
.const ZP15 = $6b
.const ZP_ISR = $90 // Hardware interrupt
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r15
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x471c, %r9
clflush (%r9)
nop
nop
nop
nop
cmp %rcx, %rcx
mov $0x6162636465666768, %r15
movq %r15, (%r9)
nop
and $35442, %r12
lea addresses_A_ht+0x1be1c, %rsi
nop
sub %rbp, %rbp
mov (%rsi), %ebx
sub $21045, %r12
lea addresses_D_ht+0x1ba24, %rbx
nop
nop
xor %rbp, %rbp
movb (%rbx), %r9b
nop
add %rbp, %rbp
lea addresses_D_ht+0x201c, %rsi
lea addresses_normal_ht+0xef1c, %rdi
nop
xor %r15, %r15
mov $27, %rcx
rep movsq
nop
nop
nop
nop
sub $47697, %r15
lea addresses_normal_ht+0x1519c, %rsi
lea addresses_UC_ht+0x1b02d, %rdi
nop
cmp $3018, %r9
mov $74, %rcx
rep movsw
nop
nop
nop
nop
sub $44397, %r9
lea addresses_WC_ht+0x2164, %r15
nop
nop
nop
nop
nop
sub %r12, %r12
movw $0x6162, (%r15)
dec %r12
lea addresses_normal_ht+0x1b71c, %rbx
nop
nop
nop
and $22715, %r12
movl $0x61626364, (%rbx)
nop
nop
nop
nop
nop
xor $38938, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r15
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r8
push %rax
push %rbx
push %rcx
push %rsi
// Load
lea addresses_PSE+0x1ab1c, %rax
nop
nop
nop
nop
xor %rsi, %rsi
movb (%rax), %r8b
cmp %rbx, %rbx
// Store
mov $0x35474e0000000be4, %r10
clflush (%r10)
nop
nop
nop
nop
xor %r15, %r15
mov $0x5152535455565758, %rsi
movq %rsi, %xmm1
movups %xmm1, (%r10)
// Exception!!!
mov (0), %r10
nop
nop
add %r8, %r8
// Store
lea addresses_UC+0x12640, %rsi
nop
nop
xor $37890, %r15
mov $0x5152535455565758, %rcx
movq %rcx, %xmm0
movups %xmm0, (%rsi)
nop
cmp %rax, %rax
// Store
lea addresses_UC+0x10bc, %r8
nop
nop
and $59593, %r15
mov $0x5152535455565758, %r10
movq %r10, %xmm5
movups %xmm5, (%r8)
nop
nop
nop
sub $55940, %r8
// Faulty Load
lea addresses_normal+0x1671c, %rax
nop
nop
inc %rcx
movups (%rax), %xmm4
vpextrq $1, %xmm4, %rbx
lea oracles, %rax
and $0xff, %rbx
shlq $12, %rbx
mov (%rax,%rbx,1), %rbx
pop %rsi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_PSE', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_NC', 'size': 16, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_UC', 'size': 16, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_UC', 'size': 16, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_D_ht', 'size': 1, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}}
{'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': True, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': True, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False}}
{'34': 184}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
#include "Cmdline.h"
#include "Disk.h"
#include "FoldMask.h"
#include "ImageIO.h"
#include "Maths.h"
#include "Geometry.h"
#include "CPicBase.h"
#include "Memory.h"
#include "numerical_recipes.h"
/* --------------------------------------------------------------- */
/* CArgs_tiny ---------------------------------------------------- */
/* --------------------------------------------------------------- */
class CArgs_tiny {
public:
double fmTOverride;
const char *infile,
*nmrc,
*fm,
*fmd;
int Z,
ID,
D,
minarea;
bool nomasks,
oneregion,
transpose,
dumphist;
public:
CArgs_tiny()
{
fmTOverride = 0.0;
infile = NULL;
nmrc = NULL;
fm = NULL;
fmd = NULL;
Z = -1;
ID = -1;
D = -1;
minarea = 90000;
nomasks = false;
oneregion = false;
transpose = false;
dumphist = false;
};
void SetCmdLine( int argc, char* argv[] );
};
/* --------------------------------------------------------------- */
/* Statics ------------------------------------------------------- */
/* --------------------------------------------------------------- */
static CArgs_tiny gArgs;
/* --------------------------------------------------------------- */
/* SetCmdLine ---------------------------------------------------- */
/* --------------------------------------------------------------- */
void CArgs_tiny::SetCmdLine( int argc, char* argv[] )
{
// parse command line args
if( argc < 5 ) {
printf(
"Usage: tiny <z> <id> <tif-file> <fold-mask-file> [option]\n" );
exit( 42 );
}
for( int i = 1; i < argc; ++i ) {
if( argv[i][0] != '-' ) {
if( Z == -1 )
Z = atoi( argv[i] );
else if( ID == -1 )
ID = atoi( argv[i] );
else
infile = argv[i];
}
else if( GetArgStr( nmrc, "-nmrc=", argv[i] ) )
;
else if( GetArgStr( fm, "-fm=", argv[i] ) )
;
else if( GetArgStr( fmd, "-fmd=", argv[i] ) )
;
else if( GetArg( &fmTOverride, "-fmto=%lf", argv[i] ) ) {
printf( "Fold Mask Threshold overridden, now %f.\n",
fmTOverride );
}
else if( GetArg( &D, "-D=%d", argv[i] ) ) {
printf( "Fold radius overridden, now %d.\n", D );
}
else if( GetArg( &minarea, "-minarea=%d", argv[i] ) )
;
else if( IsArg( "-nf", argv[i] ) ) {
nomasks = true;
printf( "Not generating mask files.\n" );
}
else if( IsArg( "-one", argv[i] ) ) {
oneregion = true;
printf( "Using just one region.\n" );
}
else if( IsArg( "-h", argv[i] ) ) {
dumphist = true;
printf( "Dumping a histogram.\n" );
}
else {
printf( "Did not understand option '%s'.\n", argv[i] );
exit( 42 );
}
}
if( nomasks ) {
fm = NULL;
fmd = NULL;
}
else if( !fm && !fmd )
nomasks = true;
// For backwards compatibility, also accept the env. variable
const char *pe = getenv( "FoldMaskThreshold" );
if( pe ) {
fmTOverride = atof( pe );
printf(
"Environment variable over-ride of threshold to %f\n",
fmTOverride );
printf(
"--- This is obsolete --- Use the -fmto option instead\n" );
}
}
/* --------------------------------------------------------------- */
/* WriteFOLDMAP2Entry -------------------------------------------- */
/* --------------------------------------------------------------- */
static void WriteFOLDMAP2Entry( int ncr )
{
CMutex M;
char name[256];
sprintf( name, "fm_%d", gArgs.Z );
if( M.Get( name ) ) {
FILE *f = fopen( "fm.same", "a" );
if( f ) {
fprintf( f,
"FOLDMAP2 %d.%d %d\n", gArgs.Z, gArgs.ID, ncr );
fflush( f );
fclose( f );
}
}
M.Release();
}
/* --------------------------------------------------------------- */
/* SingleValueDominates ------------------------------------------ */
/* --------------------------------------------------------------- */
// Tells if a single pixel value dominates the histogram.
//
static bool SingleValueDominates( const vector<int> &histo )
{
int total = 0, nh = histo.size();
for( int i = 0; i < nh; ++i )
total += histo[i];
for( int i = 0; i < nh; ++i ) {
if( histo[i] > total/2 ) {
printf(
"Dominant value %d, %d occurences in %d pixels\n",
i, histo[i], total );
return true;
}
}
return false;
}
/* --------------------------------------------------------------- */
/* IsTooGaussian ------------------------------------------------- */
/* --------------------------------------------------------------- */
// Tells whether a histogram is too well explained by a gaussian.
//
static bool IsTooGaussian( const vector<int> &histo )
{
int nhist = histo.size();
// Mean and std deviation.
MeanStd mh;
double mean, std;
int ndv = 0; // number of different values
for( int i = 0; i < nhist; ++i ) {
mh.Run( i, histo[i] );
ndv += (histo[i] > 0);
}
mh.Stats( mean, std );
printf( "\nMean %f, std %f, # different values %d\n",
mean, std, ndv );
// Unusual case; print them
if( ndv <= 20 ) {
for( int i = 0; i < nhist; ++i ) {
if( histo[i] > 0 )
printf( "[%d %d] ", i, histo[i] );
}
printf( "\n" );
}
// Now do a least squares fit. Should yield little diff, in theory.
// Create y array (same data as double); s array (const std dev).
VecDoub x( nhist ), y( nhist ), s( nhist );
MeanStd orig;
for( int i = 0; i < nhist; ++i ) {
x[i] = i;
y[i] = histo[i];
s[i] = 1.0;
orig.Element( histo[i] );
}
double omean, ostd;
orig.Stats( omean, ostd );
printf( "Histogram values: mean %f rms %f\n", omean, ostd );
// Now try a 1 gaussian fit
VecDoub a( 3 );
double sum = 0.0;
double cnt = 0;
int ilo = max( 0, int(mean-std) ),
ihi = min( 255, int(mean+std) );
for( int i = ilo; i <= ihi; ++i ) {
sum += histo[i];
++cnt;
printf( "%d ", histo[i] );
}
printf( "\n" );
printf( "Boxcar average is %f\n", sum/cnt );
a[0] = 1.5 * sum/cnt; // estimated peak value
a[1] = mean; // where it is
a[2] = std * sqrt( 2 ); // and the divisor term
printf( "Before fit fit: height %f, loc %f, width %f\n",
a[0], mean, std );
Fitmrq f( x, y, s, a, fgauss );
try {
f.fit();
}
catch(int) { // if the fitting procedure blows up
return false; // it's safe to assume it's not very gaussian
}
printf( "After fit: height %f, loc %f, width %f\n",
f.a[0], f.a[1], f.a[2]/sqrt(2) );
// Now look at residuals
MeanStd m;
for( int i = 0; i < nhist; ++i )
m.Element( y[i] - ygauss( x[i], f.a ) );
m.Stats( mean, std );
printf( "Residuals: mean %f, RMS about mean %f\n", mean, std );
return std < ostd/8; // a guess
}
/* --------------------------------------------------------------- */
/* RemoveTooGaussian --------------------------------------------- */
/* --------------------------------------------------------------- */
// March a sampling window of size SxS across raster in steps of
// size D < S, so windows overlap. Within each window get a value
// histogram and remove all pixels (in that window) from goodp if
// they look homogeneous in intensity. Homogeneous regions either
// are dominated by one value, or have a gaussian-like intensity
// distribution (narrow).
//
static void RemoveTooGaussian(
vector<uint8> &goodp,
const uint8 *raster,
int w,
int h )
{
vector<int> histo( 256 );
const int D = 128;
const int S = 256;
int ymax = (int)ceil( (double(h) - S) / D ),
xmax = (int)ceil( (double(w) - S) / D );
for( int iy = 0; iy <= ymax; ++iy ) {
int yhi = min( h, iy*D + S ),
ylo = yhi - S;
for( int ix = 0; ix <= xmax; ++ix ) {
int xhi = min( w, ix*D + S ),
xlo = xhi - S;
memset( &histo[0], 0, 256*sizeof(int) );
for( int jy = ylo; jy < yhi; ++jy ) {
for( int jx = xlo; jx < xhi; ++jx )
++histo[raster[jx + w*jy]];
}
if( SingleValueDominates( histo ) ||
IsTooGaussian( histo ) ) {
for( int jy = ylo; jy < yhi; ++jy ) {
for( int jx = xlo; jx < xhi; ++jx )
goodp[jx + w*jy] = 0;
}
}
}
}
}
/* --------------------------------------------------------------- */
/* AccumNonSaturated --------------------------------------------- */
/* --------------------------------------------------------------- */
static double AccumNonSaturated(
MeanStd &m,
const vector<uint8> &goodp,
const uint8 *raster,
int np,
int SAT )
{
double fracReal;
int ngood = 0;
m.Reset();
for( int i = 0; i < np; ++i ) {
if( goodp[i] ) {
int pix = raster[i];
++ngood;
if( pix >= SAT && pix <= 255-SAT )
m.Element( pix );
}
}
fracReal = (double)m.HowMany() / ngood;
printf( "SAT=%d: %d non-sat, %f percent non-sat\n",
SAT, m.HowMany(), fracReal * 100.0 );
return fracReal;
}
/* --------------------------------------------------------------- */
/* StatsForNonSaturated ------------------------------------------ */
/* --------------------------------------------------------------- */
// Get stats for pixels within SAT of 0, 255.
//
static int StatsForNonSaturated(
double &mean,
double &std,
const vector<uint8> &goodp,
const uint8 *raster,
int w,
int h )
{
MeanStd m;
double fracReal;
int np = w * h, SAT;
fracReal = AccumNonSaturated( m, goodp, raster, np, SAT = 3 );
if( fracReal < 0.9 ) {
printf( "Saturated image! Retrying with SAT = 1\n");
AccumNonSaturated( m, goodp, raster, np, SAT = 1 );
}
m.Stats( mean, std );
printf( "Non-sat pixels: mean = %f stddev = %f\n", mean, std );
return SAT;
}
/* --------------------------------------------------------------- */
/* StatsForRealPixels -------------------------------------------- */
/* --------------------------------------------------------------- */
// Calculate mean, std for those pixels that look real.
//
// 'Unreal' data suffer one or more of these faults:
// - Value histogram dominated by one value (very narrow).
// - Value histogram described by single gaussian (too narrow).
// - Value too close to saturation (within SAT of 0 or 255).
//
static int StatsForRealPixels (
double &mean,
double &std,
const uint8 *raster,
int w,
int h )
{
vector<uint8> goodp( w * h, 1 );
RemoveTooGaussian( goodp, raster, w, h );
return StatsForNonSaturated( mean, std, goodp, raster, w, h );
}
/* --------------------------------------------------------------- */
/* ZeroWhitePixels ----------------------------------------------- */
/* --------------------------------------------------------------- */
// Zero white pixels in raster iff white (near SAT) value is
// outside useful range, that is, if brighter than 2.5 sigma
// from mean.
//
static void ZeroWhitePixels(
uint8 *raster,
int np,
double mean,
double std,
int SAT )
{
if( mean + 2.5 * std < 255 ) {
printf( "Removing white pixels\n" );
for( int i = 0; i < np; ++i ) {
if( raster[i] > 255 - SAT )
raster[i] = 0;
}
}
}
/* --------------------------------------------------------------- */
/* SelectThreshAndD ---------------------------------------------- */
/* --------------------------------------------------------------- */
// Choose value thresh such that normalized values > -thresh are
// real rather than folds. That's the test used in compiling cr's.
// The stats calculation calls 'good' pixels in range [SAT,255-SAT].
// So the highest fold value is SAT-1.
//
// Also select radius D such that all pixels within D of a fold
// are ignored.
//
static void SelectThreshAndD(
double &thresh,
int &D,
double mean,
double std,
int SAT )
{
thresh = 4.0; // try 4 stddevs and shrink as needed
D = 10;
if( (SAT-1 - mean) / std > -thresh ) {
// 4 stddevs too wide...
// Set 95% of exact range.
thresh = 0.95 * (mean - (SAT-1)) / std;
printf( "Thresh forced down to %g\n", thresh );
if( thresh < 2.0 ) {
// Black area too expansive -> fragmentation...
// Set as wide as possible, out to value = 0.5
thresh = (mean - 0.5) / std;
D = 0;
printf(
"Desparate action: Thresh = %g excluding only v = 0...\n"
"...And setting D = 0\n", thresh );
}
}
if( gArgs.fmTOverride != 0 ) {
thresh = gArgs.fmTOverride;
printf( "Explicit override of thresh %g\n", thresh );
}
if( gArgs.D > -1 ) {
D = gArgs.D;
printf( "Explicit override of D %d\n", D );
}
}
/* --------------------------------------------------------------- */
/* RemoveLowContrast --------------------------------------------- */
/* --------------------------------------------------------------- */
// March a sampling window of size SxS across image in steps of
// size D < S, so windows overlap. Within each window evaluate
// contrast and if low, force those v-pixels below threshold.
//
static void RemoveLowContrast(
vector<double> &v,
int w,
int h,
double std,
double thresh )
{
const int D = 32;
const int S = 128;
vector<double> window( S*S );
vector<int> remove;
// Evaluate
int ymax = (int)ceil( (double(h) - S) / D ),
xmax = (int)ceil( (double(w) - S) / D );
for( int iy = 0; iy <= ymax; ++iy ) {
int yhi = min( h, iy*D + S ),
ylo = yhi - S;
for( int ix = 0; ix <= xmax; ++ix ) {
int xhi = min( w, ix*D + S ),
xlo = xhi - S;
for( int jy = ylo; jy < yhi; ++jy ) {
memcpy(
&window[S*(jy-ylo)],
&v[xlo + w*jy],
S*sizeof(double) );
}
if( IsLowContrast( window, std ) ) {
for( int jy = ylo; jy < yhi; ++jy ) {
for( int jx = xlo; jx < xhi; ++jx )
remove.push_back( jx + w*jy );
}
}
}
}
// Remove
int nr = remove.size();
printf( "Low contrast pixels = %d\n", nr );
if( nr ) {
thresh = -thresh - 1.0;
for( int i = 0; i < nr; ++i )
v[remove[i]] = thresh;
}
}
/* --------------------------------------------------------------- */
/* Widen --------------------------------------------------------- */
/* --------------------------------------------------------------- */
// Remove pixels within radius D of any fold pixel.
//
static void Widen(
vector<double> &v,
int w,
int h,
double thresh,
int D )
{
int nr, np = w * h;
vector<int> remove;
thresh = -thresh;
for( int i = 0; i < np; ++i ) {
if( v[i] <= thresh )
remove.push_back( i );
}
if( nr = remove.size() ) {
thresh -= 1.0;
for( int ir = 0; ir < nr; ++ir ) {
int i = remove[ir],
y = i / w,
x = i - w * y,
ylo = max( 0, y - D ),
yhi = min( h-1, y + D ),
xlo = max( 0, x - D ),
xhi = min( w-1, x + D );
for( y = ylo; y <= yhi; ++y ) {
for( x = xlo; x <= xhi; ++x )
v[x + w*y] = thresh;
}
}
}
}
/* --------------------------------------------------------------- */
/* ImageToFoldMap ------------------------------------------------ */
/* --------------------------------------------------------------- */
// Here we convert an input image to a map where 0 = on fold,
// 1 = region 1, 2 = region 2, etc.
//
// Return maximal region id.
//
static int ImageToFoldMap(
uint8* FoldMask,
const PicBase &pic,
bool remove_low_contrast = false )
{
double mean, std, thresh;
uint8 *raster = pic.raster;
int w = pic.w,
h = pic.h,
npixels = w * h,
SAT, D;
// Calc fold thresh and width extension D
SAT = StatsForRealPixels( mean, std, raster, w, h );
ZeroWhitePixels( raster, npixels, mean, std, SAT );
SelectThreshAndD( thresh, D, mean, std, SAT );
// Make normalized images
vector<double> v(npixels);
for( int i = 0; i < npixels; ++i )
v[i] = (raster[i] - mean) / std;
vector<double> vorig = v;
// Remove low contrast
if( remove_low_contrast )
RemoveLowContrast( v, w, h, std, thresh );
// Widen folds
Widen( v, w, h, thresh, D );
// Propagate connected regions
vector<ConnRegion> cr;
for( int i = 0; i < npixels; ++i ) {
if( v[i] > -thresh ) {
ConnRegion c;
int npts;
npts = Propagate( c.pts, v, w, h, i,
-thresh, -thresh - 1.0 );
printf(
"ImageToFoldMap: ConnRegion with %d pixels\n", npts );
if( npts > gArgs.minarea )
cr.push_back( c );
}
}
// Final accounting
SetBoundsAndColors( cr, FoldMask, vorig, w, h, -thresh, D );
return cr.size();
}
/* --------------------------------------------------------------- */
/* MakeDrawingMask ----------------------------------------------- */
/* --------------------------------------------------------------- */
// Create optimized drawing mask.
//
// Notes:
// For alignment, we remove/ignore low contrast areas to avoid poor
// alignment results. However, for drawing, once the transforms are
// already determined, we want to assign as many image pixels (hence
// map pixels) as possible to some appropriate transform ID, that is,
// to a map pixel value.
//
// The drawing mask typically has more non-zero pixels in it than
// the alignment mask and that's sufficient to cause the raster
// scanner that finds connected regions to find them in a different
// order, and so give them different ID's. Moreover, the extra
// pixels in the drawing map may bridge regions that are separate
// in the alignment map giving the two maps different region counts
// AND different labels.
//
// Getting the labels adjusted correctly has an easy part and a
// hard part. First, for a given pixel coordinate, if the alignment
// map has a non-zero value there, that's the value we want in the
// drawing map--easy. But if there is a (non-zero) pixel in the
// drawing map that has no (non-zero) pixel in the alignment map,
// what ID shall we use? There are several possible procedures, but
// what we elect to do here is to examine the drawing map (before
// it is relabeled) and for every non-zero region in it, determine
// which non-zero alignment region it has the largest area overlap
// with. This gives a mapping from any drawing label to an alignment
// label. This is simple to implement and probably good enough since
// low contrast cases are few.
//
static uint8* MakeDrawingMask(
PicBase &pic,
const uint8 *FoldMaskAlign,
int np )
{
// First we generate the drawing mask in pretty much the same way
// as the alignment mask, except that low contrast regions are
// not removed for the drawing version.
uint8 *FoldMaskDraw = (uint8*)malloc( np );
ImageToFoldMap( FoldMaskDraw, pic, false );
// Next create the mapping from labels in the drawing map to
// that label/region in the alignment map with which there is
// greatest overlap.
vector<int> map( 256, 0 );
// Get a mapping for each label value used in the drawing map.
// Since region labels are assigned consecutively, as soon as
// we advance to a label that isn't used we are done.
int used = true;
for( int drawlabel = 1; drawlabel < 256 && used; ++drawlabel ) {
vector<int> alnarea( 256, 0 );
used = false;
for( int i = 0; i < np; ++i ) {
if( FoldMaskDraw[i] == drawlabel ) {
++alnarea[FoldMaskAlign[i]];
used = true;
}
}
if( used ) {
// Find largest overlapped area, if any.
int max_A = 0;
int max_j = 0;
for( int j = 1; j < 256; ++j ) {
if( alnarea[j] > max_A ) {
max_A = alnarea[j];
max_j = j;
}
}
printf(
"Mapping drawing region %d to alignment region %d\n",
drawlabel, max_j );
map[drawlabel] = max_j;
}
}
// Now relabel drawing map pixels
for( int i = 0; i < np; ++i ) {
if( FoldMaskAlign[i] )
FoldMaskDraw[i] = FoldMaskAlign[i];
else if( FoldMaskDraw[i] )
FoldMaskDraw[i] = map[FoldMaskDraw[i]];
}
return FoldMaskDraw;
}
/* --------------------------------------------------------------- */
/* main ---------------------------------------------------------- */
/* --------------------------------------------------------------- */
int main( int argc, char **argv )
{
/* ------------------ */
/* Parse command line */
/* ------------------ */
gArgs.SetCmdLine( argc, argv );
/* -------- */
/* Load src */
/* -------- */
PicBase p;
p.LoadOriginal( gArgs.infile, stdout, gArgs.transpose );
/* ---------------- */
/* Save src as nmrc */
/* ---------------- */
if( strstr( gArgs.infile, ".mrc" ) && gArgs.nmrc )
Raster8ToPng8( gArgs.nmrc, p.original, p.w, p.h );
/* ------------ */
/* Create masks */
/* ------------ */
if( gArgs.nomasks ) {
WriteFOLDMAP2Entry( 1 );
return 0;
}
// Create two different fold masks - one optimized for alignment,
// with all low contrast regions removed, and one optimized for
// drawing, with regions as big as possible.
int ncr, np = p.w * p.h;
uint8 *FoldMaskAlign = (uint8*)malloc( np );
uint8 *FoldMaskDraw;
if( gArgs.oneregion ) {
// Efficiently handle the '-one' option. In this case
// the drawing and alignment masks are identical.
ncr = 1;
FoldMaskDraw = FoldMaskAlign;
memset( FoldMaskAlign, 1, np );
}
else {
// Otherwise, calculate real foldmasks
ncr = ImageToFoldMap( FoldMaskAlign, p, true );
if( gArgs.fmd )
FoldMaskDraw = MakeDrawingMask( p, FoldMaskAlign, np );
}
/* ------------------------------- */
/* Write masks and FOLDMAP entries */
/* ------------------------------- */
if( gArgs.fm )
Raster8ToPng8( gArgs.fm, FoldMaskAlign, p.w, p.h );
if( gArgs.fmd )
Raster8ToPng8( gArgs.fmd, FoldMaskDraw, p.w, p.h );
WriteFOLDMAP2Entry( ncr );
VMStats( stdout );
return 0;
}
|
; A121956: a(n) = a(n-1) + (n-2)*a(n-2) + a(n-3) starting a(0)=0, a(1)=a(2)=1.
; Submitted by Jon Maiga
; 0,1,1,2,5,12,34,99,315,1042,3661,13354,51006,201561,826987,3498286,15277665,68578942,316519868,1497639547,7263576113,36035247374,182804409181,946808180148,5004540429504,26963932982089,148019711470333,827122576452062,4702599007662809,27182928283338816,159682823074349530,952690342298838003,5770357962812662719,35463441397150990342,221067586549455035353,1397131510618250379358,8948892894696872571702,58069563352885090884585,381626839072590753845215,2539149576024035989146562,17099039024135369726149317
mov $3,1
lpb $0
mul $2,$0
sub $0,1
sub $2,$1
mov $1,$3
add $4,$3
mov $3,$2
mov $2,$4
lpe
mov $0,$2
|
; A021983: Decimal expansion of 1/979.
; Submitted by Jon Maiga
; 0,0,1,0,2,1,4,5,0,4,5,9,6,5,2,7,0,6,8,4,3,7,1,8,0,7,9,6,7,3,1,3,5,8,5,2,9,1,1,1,3,3,8,1,0,0,1,0,2,1,4,5,0,4,5,9,6,5,2,7,0,6,8,4,3,7,1,8,0,7,9,6,7,3,1,3,5,8,5,2,9,1,1,1,3,3,8,1,0,0,1,0,2,1,4,5,0,4,5
seq $0,83811 ; Numbers n such that 2n+1 is the digit reversal of n+1.
div $0,3916
mod $0,10
|
; A017340: a(n) = (10*n + 5)^12.
; 244140625,129746337890625,59604644775390625,3379220508056640625,68952523554931640625,766217865410400390625,5688009063105712890625,31676352024078369140625,142241757136172119140625,540360087662636962890625,1795856326022129150390625,5350250105473711181640625,14551915228366851806640625,36644198070556426025390625,86380562306022715087890625,192300484323376406494140625,407199588611568593994140625,825005006849765777587890625,1607166017050789863525390625,3022841224505963164306640625
mul $0,10
add $0,5
pow $0,12
|
;
; Copyright (c) 2016, Alliance for Open Media. All rights reserved
;
; This source code is subject to the terms of the BSD 2 Clause License and
; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
; was not distributed with this source code in the LICENSE file, you can
; obtain it at www.aomedia.org/license/software. If the Alliance for Open
; Media Patent License 1.0 was not distributed with this source code in the
; PATENTS file, you can obtain it at www.aomedia.org/license/patent.
;
;
%include "third_party/x86inc/x86inc.asm"
SECTION_RODATA
pw_8: times 8 dw 8
bilin_filter_m_sse2: times 8 dw 16
times 8 dw 0
times 8 dw 14
times 8 dw 2
times 8 dw 12
times 8 dw 4
times 8 dw 10
times 8 dw 6
times 16 dw 8
times 8 dw 6
times 8 dw 10
times 8 dw 4
times 8 dw 12
times 8 dw 2
times 8 dw 14
SECTION .text
; int aom_sub_pixel_varianceNxh(const uint8_t *src, ptrdiff_t src_stride,
; int x_offset, int y_offset,
; const uint8_t *dst, ptrdiff_t dst_stride,
; int height, unsigned int *sse);
;
; This function returns the SE and stores SSE in the given pointer.
%macro SUM_SSE 6 ; src1, dst1, src2, dst2, sum, sse
psubw %3, %4
psubw %1, %2
mova %4, %3 ; make copies to manipulate to calc sum
mova %2, %1 ; use originals for calc sse
pmaddwd %3, %3
paddw %4, %2
pmaddwd %1, %1
movhlps %2, %4
paddd %6, %3
paddw %4, %2
pxor %2, %2
pcmpgtw %2, %4 ; mask for 0 > %4 (sum)
punpcklwd %4, %2 ; sign-extend word to dword
paddd %6, %1
paddd %5, %4
%endmacro
%macro STORE_AND_RET 0
%if mmsize == 16
; if H=64 and W=16, we have 8 words of each 2(1bit)x64(6bit)x9bit=16bit
; in m6, i.e. it _exactly_ fits in a signed word per word in the xmm reg.
; We have to sign-extend it before adding the words within the register
; and outputing to a dword.
movhlps m3, m7
movhlps m4, m6
paddd m7, m3
paddd m6, m4
pshufd m3, m7, 0x1
pshufd m4, m6, 0x1
paddd m7, m3
paddd m6, m4
mov r1, ssem ; r1 = unsigned int *sse
movd [r1], m7 ; store sse
movd rax, m6 ; store sum as return value
%endif
RET
%endmacro
%macro INC_SRC_BY_SRC_STRIDE 0
%if ARCH_X86=1 && CONFIG_PIC=1
add srcq, src_stridemp
add srcq, src_stridemp
%else
lea srcq, [srcq + src_strideq*2]
%endif
%endmacro
%macro SUBPEL_VARIANCE 1-2 0 ; W
%define bilin_filter_m bilin_filter_m_sse2
%define filter_idx_shift 5
%ifdef PIC ; 64bit PIC
%if %2 == 1 ; avg
cglobal highbd_sub_pixel_avg_variance%1xh, 9, 10, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, height, sse
%define sec_str sec_strideq
%else
cglobal highbd_sub_pixel_variance%1xh, 7, 8, 13, src, src_stride, x_offset, \
y_offset, dst, dst_stride, height, sse
%endif
%define block_height heightd
%define bilin_filter sseq
%else
%if ARCH_X86=1 && CONFIG_PIC=1
%if %2 == 1 ; avg
cglobal highbd_sub_pixel_avg_variance%1xh, 7, 7, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, \
height, sse, g_bilin_filter, g_pw_8
%define block_height dword heightm
%define sec_str sec_stridemp
; Store bilin_filter and pw_8 location in stack
%if GET_GOT_DEFINED == 1
GET_GOT eax
add esp, 4 ; restore esp
%endif
lea ecx, [GLOBAL(bilin_filter_m)]
mov g_bilin_filterm, ecx
lea ecx, [GLOBAL(pw_8)]
mov g_pw_8m, ecx
LOAD_IF_USED 0, 1 ; load eax, ecx back
%else
cglobal highbd_sub_pixel_variance%1xh, 7, 7, 13, src, src_stride, \
x_offset, y_offset, dst, dst_stride, height, \
sse, g_bilin_filter, g_pw_8
%define block_height heightd
; Store bilin_filter and pw_8 location in stack
%if GET_GOT_DEFINED == 1
GET_GOT eax
add esp, 4 ; restore esp
%endif
lea ecx, [GLOBAL(bilin_filter_m)]
mov g_bilin_filterm, ecx
lea ecx, [GLOBAL(pw_8)]
mov g_pw_8m, ecx
LOAD_IF_USED 0, 1 ; load eax, ecx back
%endif
%else
%if %2 == 1 ; avg
cglobal highbd_sub_pixel_avg_variance%1xh, 7 + 2 * ARCH_X86_64, \
7 + 2 * ARCH_X86_64, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, \
height, sse
%if ARCH_X86_64
%define block_height heightd
%define sec_str sec_strideq
%else
%define block_height dword heightm
%define sec_str sec_stridemp
%endif
%else
cglobal highbd_sub_pixel_variance%1xh, 7, 7, 13, src, src_stride, \
x_offset, y_offset, dst, dst_stride, height, sse
%define block_height heightd
%endif
%define bilin_filter bilin_filter_m
%endif
%endif
ASSERT %1 <= 16 ; m6 overflows if w > 16
pxor m6, m6 ; sum
pxor m7, m7 ; sse
%if %1 < 16
sar block_height, 1
%endif
%if %2 == 1 ; avg
shl sec_str, 1
%endif
; FIXME(rbultje) replace by jumptable?
test x_offsetd, x_offsetd
jnz .x_nonzero
; x_offset == 0
test y_offsetd, y_offsetd
jnz .x_zero_y_nonzero
; x_offset == 0 && y_offset == 0
.x_zero_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
movu m2, [srcq + 16]
mova m1, [dstq]
mova m3, [dstq + 16]
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m2, [secq+16]
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m2, [srcq + src_strideq*2]
mova m1, [dstq]
mova m3, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m2, [secq]
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_zero_y_zero_loop
STORE_AND_RET
.x_zero_y_nonzero:
cmp y_offsetd, 8
jne .x_zero_y_nonhalf
; x_offset == 0 && y_offset == 0.5
.x_zero_y_half_loop:
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+16]
movu m4, [srcq+src_strideq*2]
movu m5, [srcq+src_strideq*2+16]
mova m2, [dstq]
mova m3, [dstq+16]
pavgw m0, m4
pavgw m1, m5
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m1, [srcq+src_strideq*2]
movu m5, [srcq+src_strideq*4]
mova m2, [dstq]
mova m3, [dstq+dst_strideq*2]
pavgw m0, m1
pavgw m1, m5
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m1, [secq]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_zero_y_half_loop
STORE_AND_RET
.x_zero_y_nonhalf:
; x_offset == 0 && y_offset == bilin interpolation
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && mmsize == 16
mova m8, [bilin_filter+y_offsetq]
mova m9, [bilin_filter+y_offsetq+16]
mova m10, [pw_8]
%define filter_y_a m8
%define filter_y_b m9
%define filter_rnd m10
%else ; x86-32 or mmx
%if ARCH_X86=1 && CONFIG_PIC=1
; x_offset == 0, reuse x_offset reg
%define tempq x_offsetq
add y_offsetq, g_bilin_filterm
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add y_offsetq, bilin_filter
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
.x_zero_y_other_loop:
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq + 16]
movu m4, [srcq+src_strideq*2]
movu m5, [srcq+src_strideq*2+16]
mova m2, [dstq]
mova m3, [dstq+16]
; FIXME(rbultje) instead of out=((num-x)*in1+x*in2+rnd)>>log2(num), we can
; also do out=in1+(((num-x)*(in2-in1)+rnd)>>log2(num)). Total number of
; instructions is the same (5), but it is 1 mul instead of 2, so might be
; slightly faster because of pmullw latency. It would also cut our rodata
; tables in half for this function, and save 1-2 registers on x86-64.
pmullw m1, filter_y_a
pmullw m5, filter_y_b
paddw m1, filter_rnd
pmullw m0, filter_y_a
pmullw m4, filter_y_b
paddw m0, filter_rnd
paddw m1, m5
paddw m0, m4
psrlw m1, 4
psrlw m0, 4
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m1, [srcq+src_strideq*2]
movu m5, [srcq+src_strideq*4]
mova m4, m1
mova m2, [dstq]
mova m3, [dstq+dst_strideq*2]
pmullw m1, filter_y_a
pmullw m5, filter_y_b
paddw m1, filter_rnd
pmullw m0, filter_y_a
pmullw m4, filter_y_b
paddw m0, filter_rnd
paddw m1, m5
paddw m0, m4
psrlw m1, 4
psrlw m0, 4
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m1, [secq]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_zero_y_other_loop
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
STORE_AND_RET
.x_nonzero:
cmp x_offsetd, 8
jne .x_nonhalf
; x_offset == 0.5
test y_offsetd, y_offsetd
jnz .x_half_y_nonzero
; x_offset == 0.5 && y_offset == 0
.x_half_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq + 16]
movu m4, [srcq + 2]
movu m5, [srcq + 18]
mova m2, [dstq]
mova m3, [dstq + 16]
pavgw m0, m4
pavgw m1, m5
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m1, [srcq + src_strideq*2]
movu m4, [srcq + 2]
movu m5, [srcq + src_strideq*2 + 2]
mova m2, [dstq]
mova m3, [dstq + dst_strideq*2]
pavgw m0, m4
pavgw m1, m5
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m1, [secq]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_half_y_zero_loop
STORE_AND_RET
.x_half_y_nonzero:
cmp y_offsetd, 8
jne .x_half_y_nonhalf
; x_offset == 0.5 && y_offset == 0.5
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+16]
movu m2, [srcq+2]
movu m3, [srcq+18]
lea srcq, [srcq + src_strideq*2]
pavgw m0, m2
pavgw m1, m3
.x_half_y_half_loop:
movu m2, [srcq]
movu m3, [srcq + 16]
movu m4, [srcq + 2]
movu m5, [srcq + 18]
pavgw m2, m4
pavgw m3, m5
pavgw m0, m2
pavgw m1, m3
mova m4, [dstq]
mova m5, [dstq + 16]
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m4, m1, m5, m6, m7
mova m0, m2
mova m1, m3
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m2, [srcq+2]
lea srcq, [srcq + src_strideq*2]
pavgw m0, m2
.x_half_y_half_loop:
movu m2, [srcq]
movu m3, [srcq + src_strideq*2]
movu m4, [srcq + 2]
movu m5, [srcq + src_strideq*2 + 2]
pavgw m2, m4
pavgw m3, m5
pavgw m0, m2
pavgw m2, m3
mova m4, [dstq]
mova m5, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m2, [secq]
%endif
SUM_SSE m0, m4, m2, m5, m6, m7
mova m0, m3
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_half_y_half_loop
STORE_AND_RET
.x_half_y_nonhalf:
; x_offset == 0.5 && y_offset == bilin interpolation
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && mmsize == 16
mova m8, [bilin_filter+y_offsetq]
mova m9, [bilin_filter+y_offsetq+16]
mova m10, [pw_8]
%define filter_y_a m8
%define filter_y_b m9
%define filter_rnd m10
%else ; x86_32
%if ARCH_X86=1 && CONFIG_PIC=1
; x_offset == 0.5. We can reuse x_offset reg
%define tempq x_offsetq
add y_offsetq, g_bilin_filterm
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add y_offsetq, bilin_filter
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+16]
movu m2, [srcq+2]
movu m3, [srcq+18]
lea srcq, [srcq + src_strideq*2]
pavgw m0, m2
pavgw m1, m3
.x_half_y_other_loop:
movu m2, [srcq]
movu m3, [srcq+16]
movu m4, [srcq+2]
movu m5, [srcq+18]
pavgw m2, m4
pavgw m3, m5
mova m4, m2
mova m5, m3
pmullw m1, filter_y_a
pmullw m3, filter_y_b
paddw m1, filter_rnd
paddw m1, m3
pmullw m0, filter_y_a
pmullw m2, filter_y_b
paddw m0, filter_rnd
psrlw m1, 4
paddw m0, m2
mova m2, [dstq]
psrlw m0, 4
mova m3, [dstq+16]
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
mova m0, m4
mova m1, m5
lea srcq, [srcq + src_strideq*2]
lea dstq, [dstq + dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m2, [srcq+2]
lea srcq, [srcq + src_strideq*2]
pavgw m0, m2
.x_half_y_other_loop:
movu m2, [srcq]
movu m3, [srcq+src_strideq*2]
movu m4, [srcq+2]
movu m5, [srcq+src_strideq*2+2]
pavgw m2, m4
pavgw m3, m5
mova m4, m2
mova m5, m3
pmullw m4, filter_y_a
pmullw m3, filter_y_b
paddw m4, filter_rnd
paddw m4, m3
pmullw m0, filter_y_a
pmullw m2, filter_y_b
paddw m0, filter_rnd
psrlw m4, 4
paddw m0, m2
mova m2, [dstq]
psrlw m0, 4
mova m3, [dstq+dst_strideq*2]
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m4, [secq]
%endif
SUM_SSE m0, m2, m4, m3, m6, m7
mova m0, m5
lea srcq, [srcq + src_strideq*4]
lea dstq, [dstq + dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_half_y_other_loop
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
STORE_AND_RET
.x_nonhalf:
test y_offsetd, y_offsetd
jnz .x_nonhalf_y_nonzero
; x_offset == bilin interpolation && y_offset == 0
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift
%if ARCH_X86_64 && mmsize == 16
mova m8, [bilin_filter+x_offsetq]
mova m9, [bilin_filter+x_offsetq+16]
mova m10, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_rnd m10
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
; y_offset == 0. We can reuse y_offset reg.
%define tempq y_offsetq
add x_offsetq, g_bilin_filterm
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
.x_other_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+16]
movu m2, [srcq+2]
movu m3, [srcq+18]
mova m4, [dstq]
mova m5, [dstq+16]
pmullw m1, filter_x_a
pmullw m3, filter_x_b
paddw m1, filter_rnd
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
paddw m1, m3
paddw m0, m2
psrlw m1, 4
psrlw m0, 4
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m4, m1, m5, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m1, [srcq+src_strideq*2]
movu m2, [srcq+2]
movu m3, [srcq+src_strideq*2+2]
mova m4, [dstq]
mova m5, [dstq+dst_strideq*2]
pmullw m1, filter_x_a
pmullw m3, filter_x_b
paddw m1, filter_rnd
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
paddw m1, m3
paddw m0, m2
psrlw m1, 4
psrlw m0, 4
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m1, [secq]
%endif
SUM_SSE m0, m4, m1, m5, m6, m7
lea srcq, [srcq+src_strideq*4]
lea dstq, [dstq+dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_other_y_zero_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_rnd
STORE_AND_RET
.x_nonhalf_y_nonzero:
cmp y_offsetd, 8
jne .x_nonhalf_y_nonhalf
; x_offset == bilin interpolation && y_offset == 0.5
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift
%if ARCH_X86_64 && mmsize == 16
mova m8, [bilin_filter+x_offsetq]
mova m9, [bilin_filter+x_offsetq+16]
mova m10, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_rnd m10
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
; y_offset == 0.5. We can reuse y_offset reg.
%define tempq y_offsetq
add x_offsetq, g_bilin_filterm
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+16]
movu m2, [srcq+2]
movu m3, [srcq+18]
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
pmullw m1, filter_x_a
pmullw m3, filter_x_b
paddw m1, filter_rnd
paddw m0, m2
paddw m1, m3
psrlw m0, 4
psrlw m1, 4
lea srcq, [srcq+src_strideq*2]
.x_other_y_half_loop:
movu m2, [srcq]
movu m3, [srcq+16]
movu m4, [srcq+2]
movu m5, [srcq+18]
pmullw m2, filter_x_a
pmullw m4, filter_x_b
paddw m2, filter_rnd
pmullw m3, filter_x_a
pmullw m5, filter_x_b
paddw m3, filter_rnd
paddw m2, m4
paddw m3, m5
mova m4, [dstq]
mova m5, [dstq+16]
psrlw m2, 4
psrlw m3, 4
pavgw m0, m2
pavgw m1, m3
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m4, m1, m5, m6, m7
mova m0, m2
mova m1, m3
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m2, [srcq+2]
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
paddw m0, m2
psrlw m0, 4
lea srcq, [srcq+src_strideq*2]
.x_other_y_half_loop:
movu m2, [srcq]
movu m3, [srcq+src_strideq*2]
movu m4, [srcq+2]
movu m5, [srcq+src_strideq*2+2]
pmullw m2, filter_x_a
pmullw m4, filter_x_b
paddw m2, filter_rnd
pmullw m3, filter_x_a
pmullw m5, filter_x_b
paddw m3, filter_rnd
paddw m2, m4
paddw m3, m5
mova m4, [dstq]
mova m5, [dstq+dst_strideq*2]
psrlw m2, 4
psrlw m3, 4
pavgw m0, m2
pavgw m2, m3
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m2, [secq]
%endif
SUM_SSE m0, m4, m2, m5, m6, m7
mova m0, m3
lea srcq, [srcq+src_strideq*4]
lea dstq, [dstq+dst_strideq*4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_other_y_half_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_rnd
STORE_AND_RET
.x_nonhalf_y_nonhalf:
; loading filter - this is same as in 8-bit depth
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift ; filter_idx_shift = 5
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && mmsize == 16
mova m8, [bilin_filter+x_offsetq]
mova m9, [bilin_filter+x_offsetq+16]
mova m10, [bilin_filter+y_offsetq]
mova m11, [bilin_filter+y_offsetq+16]
mova m12, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_y_a m10
%define filter_y_b m11
%define filter_rnd m12
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
; In this case, there is NO unused register. Used src_stride register. Later,
; src_stride has to be loaded from stack when it is needed.
%define tempq src_strideq
mov tempq, g_bilin_filterm
add x_offsetq, tempq
add y_offsetq, tempq
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
add y_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
; end of load filter
; x_offset == bilin interpolation && y_offset == bilin interpolation
%if %1 == 16
movu m0, [srcq]
movu m2, [srcq+2]
movu m1, [srcq+16]
movu m3, [srcq+18]
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
pmullw m1, filter_x_a
pmullw m3, filter_x_b
paddw m1, filter_rnd
paddw m0, m2
paddw m1, m3
psrlw m0, 4
psrlw m1, 4
INC_SRC_BY_SRC_STRIDE
.x_other_y_other_loop:
movu m2, [srcq]
movu m4, [srcq+2]
movu m3, [srcq+16]
movu m5, [srcq+18]
pmullw m2, filter_x_a
pmullw m4, filter_x_b
paddw m2, filter_rnd
pmullw m3, filter_x_a
pmullw m5, filter_x_b
paddw m3, filter_rnd
paddw m2, m4
paddw m3, m5
psrlw m2, 4
psrlw m3, 4
mova m4, m2
mova m5, m3
pmullw m0, filter_y_a
pmullw m2, filter_y_b
paddw m0, filter_rnd
pmullw m1, filter_y_a
pmullw m3, filter_y_b
paddw m0, m2
paddw m1, filter_rnd
mova m2, [dstq]
paddw m1, m3
psrlw m0, 4
psrlw m1, 4
mova m3, [dstq+16]
%if %2 == 1 ; avg
pavgw m0, [secq]
pavgw m1, [secq+16]
%endif
SUM_SSE m0, m2, m1, m3, m6, m7
mova m0, m4
mova m1, m5
INC_SRC_BY_SRC_STRIDE
lea dstq, [dstq + dst_strideq * 2]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%else ; %1 < 16
movu m0, [srcq]
movu m2, [srcq+2]
pmullw m0, filter_x_a
pmullw m2, filter_x_b
paddw m0, filter_rnd
paddw m0, m2
psrlw m0, 4
INC_SRC_BY_SRC_STRIDE
.x_other_y_other_loop:
movu m2, [srcq]
movu m4, [srcq+2]
INC_SRC_BY_SRC_STRIDE
movu m3, [srcq]
movu m5, [srcq+2]
pmullw m2, filter_x_a
pmullw m4, filter_x_b
paddw m2, filter_rnd
pmullw m3, filter_x_a
pmullw m5, filter_x_b
paddw m3, filter_rnd
paddw m2, m4
paddw m3, m5
psrlw m2, 4
psrlw m3, 4
mova m4, m2
mova m5, m3
pmullw m0, filter_y_a
pmullw m2, filter_y_b
paddw m0, filter_rnd
pmullw m4, filter_y_a
pmullw m3, filter_y_b
paddw m0, m2
paddw m4, filter_rnd
mova m2, [dstq]
paddw m4, m3
psrlw m0, 4
psrlw m4, 4
mova m3, [dstq+dst_strideq*2]
%if %2 == 1 ; avg
pavgw m0, [secq]
add secq, sec_str
pavgw m4, [secq]
%endif
SUM_SSE m0, m2, m4, m3, m6, m7
mova m0, m5
INC_SRC_BY_SRC_STRIDE
lea dstq, [dstq + dst_strideq * 4]
%if %2 == 1 ; avg
add secq, sec_str
%endif
%endif
dec block_height
jg .x_other_y_other_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
STORE_AND_RET
%endmacro
INIT_XMM sse2
SUBPEL_VARIANCE 8
SUBPEL_VARIANCE 16
INIT_XMM sse2
SUBPEL_VARIANCE 8, 1
SUBPEL_VARIANCE 16, 1
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
namespace xla {
Status KernelSupportLibrary::For(
absl::string_view name, llvm::Value* start, llvm::Value* end,
llvm::Value* step,
const std::function<Status(llvm::Value*, bool)>& for_body_generator) {
return If(b_->CreateICmpSLT(start, end), [&]() -> Status {
TF_RETURN_IF_ERROR(for_body_generator(start, /*is_first_iteration=*/true));
return For(name, b_->CreateAdd(start, step), end, step,
[&](llvm::Value* iv) { return for_body_generator(iv, false); });
});
}
Status KernelSupportLibrary::For(
absl::string_view name, llvm::Value* start, llvm::Value* end,
llvm::Value* step, bool peel_first_iteration,
const std::function<Status(llvm::Value*, llvm::Value*)>&
for_body_generator) {
if (peel_first_iteration) {
return For(name, start, end, step, true,
[&](llvm::Value* indvar, bool is_first_iteration) -> Status {
return for_body_generator(indvar,
b_->getInt1(is_first_iteration));
});
} else {
std::unique_ptr<llvm_ir::ForLoop> loop = llvm_ir::ForLoop::EmitForLoop(
name, start, end, step, b_,
/*unroll_mode=*/unroll_mode_,
/*prevent_vectorization=*/prevent_vectorization_);
b_->SetInsertPoint(&loop->GetBodyBasicBlock()->back());
TF_RETURN_IF_ERROR(
for_body_generator(loop->GetIndVarValue(),
/*is_first_iteration=*/b_->CreateICmpEQ(
loop->GetIndVarValue(), start)));
llvm_ir::SetToLastInsertPoint(loop->GetExitBasicBlock(), b_);
return Status::OK();
}
}
Status KernelSupportLibrary::If(
absl::string_view name, llvm::Value* condition,
const std::function<Status()>& true_block_generator,
const std::function<Status()>& false_block_generator) {
llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse(condition, name, b_);
b_->SetInsertPoint(&if_data.true_block->back());
TF_RETURN_IF_ERROR(true_block_generator());
b_->SetInsertPoint(&if_data.false_block->back());
TF_RETURN_IF_ERROR(false_block_generator());
llvm_ir::SetToLastInsertPoint(if_data.after_block, b_);
return Status::OK();
}
void KernelSupportLibrary::EmitAndCallOutlinedKernel(
const HloModuleConfig& module_config, llvm::IRBuilder<>* b,
absl::string_view kernel_name,
KernelSupportLibrary::ArgumentVector arguments,
const std::function<void(KernelSupportLibrary::ArgumentVector)>&
kernel_body_generator) {
llvm::Module* module = b->GetInsertBlock()->getModule();
llvm::Function* function =
module->getFunction(llvm_ir::AsStringRef(kernel_name));
int64 null_arg_idx = -1;
std::vector<llvm::Value*> sanitized_args;
sanitized_args.reserve(arguments.size());
for (int64 i = 0, e = arguments.size(); i < e; i++) {
if (arguments[i]) {
sanitized_args.push_back(arguments[i]);
} else {
CHECK_EQ(null_arg_idx, -1);
null_arg_idx = i;
}
}
if (!function) {
VLOG(2) << "Generating kernel for " << kernel_name;
std::vector<llvm::Type*> arg_types;
std::transform(sanitized_args.begin(), sanitized_args.end(),
std::back_inserter(arg_types),
[](llvm::Value* arg) { return arg->getType(); });
auto* function_type =
llvm::FunctionType::get(b->getVoidTy(), arg_types, /*isVarArg=*/false);
function = llvm_ir::CreateCpuFunction(function_type,
llvm::GlobalValue::InternalLinkage,
module_config, kernel_name, module);
llvm::IRBuilder<>::InsertPointGuard guard(*b);
auto* entry_bb =
llvm::BasicBlock::Create(b->getContext(), "entry", function);
auto* return_inst = llvm::ReturnInst::Create(b->getContext(),
/*retVal=*/nullptr, entry_bb);
// Set the insert point to before return_inst.
b->SetInsertPoint(return_inst);
std::vector<llvm::Value*> arg_values;
/*
* clang on OSX doesn't like std::transform or range for loop here.
* See https://github.com/tensorflow/tensorflow/issues/15196
*/
for (llvm::Function::arg_iterator arg = function->arg_begin(),
arg_e = function->arg_end();
arg != arg_e; ++arg) {
arg_values.push_back(arg);
}
if (null_arg_idx != -1) {
arg_values.insert(arg_values.begin() + null_arg_idx, nullptr);
}
kernel_body_generator(arg_values);
} else {
VLOG(3) << "Re-using kernel for " << kernel_name;
}
b->CreateCall(function, llvm_ir::AsArrayRef(sanitized_args));
}
} // namespace xla
|
;===============================================================================
; Copyright 2015-2021 Intel Corporation
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;===============================================================================
;
;
; Purpose: Cryptography Primitive.
; ARCFour
;
; Content:
; ARCFourKernel()
;
;
%include "asmdefs.inc"
%include "ia_32e.inc"
%if (_IPP32E >= _IPP32E_M7)
segment .text align=IPP_ALIGN_FACTOR
;***************************************************************
;* Purpose: RC4 kernel
;*
;* void ARCFourProcessData(const Ipp8u *pSrc, Ipp8u *pDst, int len,
;* IppsARCFourState* pCtx)
;*
;***************************************************************
;;
;; Lib = M7
;;
;; Caller = ippsARCFourEncrypt
;; Caller = ippsARCFourDecrypt
;;
align IPP_ALIGN_FACTOR
IPPASM ARCFourProcessData,PUBLIC
USES_GPR rsi,rdi,rbx,rbp
USES_XMM
COMP_ABI 4
;; rdi: pSrc: BYTE, ; input stream
;; rsi: pDst: BYTE, ; output stream
;; rdx: len: DWORD, ; stream length
;; rcx: pCtx: BYTE ; context
movsxd r8, edx
test r8, r8 ; test length
mov rbp, rcx ; copy pointer context
jz .quit
movzx rax, byte [rbp+4] ; extract x
movzx rbx, byte [rbp+8] ; extract y
lea rbp, [rbp+12] ; sbox
add rax,1 ; x = (x+1)&0xFF
movzx rax, al
movzx rcx, byte [rbp+rax*4] ; tx = S[x]
;;
;; main code
;;
align IPP_ALIGN_FACTOR
.main_loop:
add rbx, rcx ; y = (x+tx)&0xFF
movzx rbx, bl
add rdi, 1
add rsi, 1
movzx rdx, byte [rbp+rbx*4] ; ty = S[y]
mov dword [rbp+rbx*4],ecx ; S[y] = tx
add rcx, rdx ; tmp_idx = (tx+ty)&0xFF
movzx rcx, cl
mov dword [rbp+rax*4],edx ; S[x] = ty
mov dl, byte [rbp+rcx*4] ; byte of gamma
add rax, 1 ; next x = (x+1)&0xFF
movzx rax, al
xor dl,byte [rdi-1] ; gamma ^= src
sub r8, 1
movzx rcx, byte [rbp+rax*4] ; next tx = S[x]
mov byte [rsi-1],dl ; store result
jne .main_loop
lea rbp, [rbp-12] ; pointer to context
sub rax, 1 ; actual new x counter
movzx rax, al
mov dword [rbp+4], eax ; update x conter
mov dword [rbp+8], ebx ; updtae y counter
.quit:
REST_XMM
REST_GPR
ret
ENDFUNC ARCFourProcessData
%endif
|
; A040133: Continued fraction for sqrt(146).
; Submitted by Christian Krause
; 12,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12,24,12
trn $0,1
mod $0,2
mul $0,12
add $0,12
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <string>
#include <unordered_set>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_init_params.h"
#include "chrome/browser/profiles/profile_avatar_downloader.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/account_id/account_id.h"
#include "components/profile_metrics/state.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/native_theme/native_theme.h"
#if !defined(OS_ANDROID)
#include "chrome/browser/ui/signin/profile_colors_util.h"
#endif
using ::testing::Mock;
using ::testing::_;
namespace {
// The ProfileMetadataEntry accessors aren't just plain old accessors to local
// members so they'll be tested. The following helpers will make the testing
// code less verbose.
#define TEST_ACCESSORS(entry_type, entry, member, first_value, second_value) \
TestAccessors(&entry, \
&entry_type::Get ## member, \
&entry_type::Set ## member, \
first_value, \
second_value);
#define TEST_STRING16_ACCESSORS(entry_type, entry, member) \
TEST_ACCESSORS(entry_type, entry, member, \
std::u16string(u"first_" #member "_value"), \
std::u16string(u"second_" #member "_value"));
#define TEST_STRING_ACCESSORS(entry_type, entry, member) \
TEST_ACCESSORS(entry_type, entry, member, \
std::string("first_" #member "_value"), \
std::string("second_" #member "_value"));
#define TEST_BOOL_ACCESSORS(entry_type, entry, member) \
TestAccessors(&entry, &entry_type::member, &entry_type::Set##member, true, \
false);
template<typename TValue, typename TGetter, typename TSetter>
void TestAccessors(ProfileAttributesEntry** entry,
TGetter getter_func,
TSetter setter_func,
TValue first_value,
TValue second_value) {
(*entry->*setter_func)(first_value);
EXPECT_EQ(first_value, (*entry->*getter_func)());
(*entry->*setter_func)(second_value);
EXPECT_EQ(second_value, (*entry->*getter_func)());
}
void VerifyInitialValues(ProfileAttributesEntry* entry,
const base::FilePath& profile_path,
const std::u16string& profile_name,
const std::string& gaia_id,
const std::u16string& user_name,
bool is_consented_primary_account,
size_t icon_index,
const std::string& supervised_user_id,
bool is_guest,
bool is_ephemeral,
bool is_omitted,
bool is_signed_in_with_credential_provider) {
ASSERT_NE(entry, nullptr);
EXPECT_EQ(profile_path, entry->GetPath());
EXPECT_EQ(profile_name, entry->GetName());
EXPECT_EQ(gaia_id, entry->GetGAIAId());
EXPECT_EQ(user_name, entry->GetUserName());
EXPECT_EQ(is_consented_primary_account, entry->IsAuthenticated());
EXPECT_EQ(icon_index, entry->GetAvatarIconIndex());
EXPECT_EQ(supervised_user_id, entry->GetSupervisedUserId());
EXPECT_EQ(is_guest, entry->IsGuest());
EXPECT_EQ(is_ephemeral, entry->IsEphemeral());
EXPECT_EQ(is_omitted, entry->IsOmitted());
EXPECT_EQ(is_signed_in_with_credential_provider,
entry->IsSignedInWithCredentialProvider());
EXPECT_EQ(std::string(), entry->GetHostedDomain());
}
class ProfileAttributesTestObserver
: public ProfileAttributesStorage::Observer {
public:
MOCK_METHOD1(OnProfileAdded, void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileWillBeRemoved,
void(const base::FilePath& profile_path));
MOCK_METHOD2(OnProfileWasRemoved,
void(const base::FilePath& profile_path,
const std::u16string& profile_name));
MOCK_METHOD2(OnProfileNameChanged,
void(const base::FilePath& profile_path,
const std::u16string& old_profile_name));
MOCK_METHOD1(OnProfileAuthInfoChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileAvatarChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileHighResAvatarLoaded,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileSigninRequiredChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileSupervisedUserIdChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileIsOmittedChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileThemeColorsChanged,
void(const base::FilePath& profile_path));
MOCK_METHOD1(OnProfileHostedDomainChanged,
void(const base::FilePath& profile_path));
};
} // namespace
class ProfileAttributesStorageTest : public testing::Test {
public:
ProfileAttributesStorageTest()
: testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {}
~ProfileAttributesStorageTest() override {}
protected:
void SetUp() override {
ASSERT_TRUE(testing_profile_manager_.SetUp());
VerifyAndResetCallExpectations();
EnableObserver();
}
void TearDown() override {
}
base::FilePath GetProfilePath(const std::string& base_name) {
return testing_profile_manager_.profile_manager()->user_data_dir().
AppendASCII(base_name);
}
void VerifyAndResetCallExpectations() {
Mock::VerifyAndClear(&observer_);
EXPECT_CALL(observer_, OnProfileAdded(_)).Times(0);
EXPECT_CALL(observer_, OnProfileWillBeRemoved(_)).Times(0);
EXPECT_CALL(observer_, OnProfileWasRemoved(_, _)).Times(0);
EXPECT_CALL(observer_, OnProfileNameChanged(_, _)).Times(0);
EXPECT_CALL(observer_, OnProfileAuthInfoChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileAvatarChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileHighResAvatarLoaded(_)).Times(0);
EXPECT_CALL(observer_, OnProfileSigninRequiredChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileSupervisedUserIdChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileIsOmittedChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileThemeColorsChanged(_)).Times(0);
EXPECT_CALL(observer_, OnProfileHostedDomainChanged(_)).Times(0);
}
void EnableObserver() { storage()->AddObserver(&observer_); }
void DisableObserver() { storage()->RemoveObserver(&observer_); }
void AddCallExpectationsForRemoveProfile(size_t profile_number) {
base::FilePath profile_path = GetProfilePath(
base::StringPrintf("testing_profile_path%" PRIuS, profile_number));
std::u16string profile_name = base::ASCIIToUTF16(
base::StringPrintf("testing_profile_name%" PRIuS, profile_number));
::testing::InSequence dummy;
EXPECT_CALL(observer(), OnProfileWillBeRemoved(profile_path)).Times(1);
EXPECT_CALL(observer(), OnProfileWasRemoved(profile_path, profile_name))
.Times(1);
}
ProfileAttributesStorage* storage() {
return profile_info_cache();
}
ProfileInfoCache* profile_info_cache() {
return testing_profile_manager_.profile_info_cache();
}
ProfileAttributesTestObserver& observer() { return observer_; }
void AddTestingProfile() {
size_t number_of_profiles = storage()->GetNumberOfProfiles();
base::FilePath profile_path = GetProfilePath(
base::StringPrintf("testing_profile_path%" PRIuS, number_of_profiles));
EXPECT_CALL(observer(), OnProfileAdded(profile_path))
.Times(1)
.RetiresOnSaturation();
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = base::ASCIIToUTF16(
base::StringPrintf("testing_profile_name%" PRIuS, number_of_profiles));
params.gaia_id =
base::StringPrintf("testing_profile_gaia%" PRIuS, number_of_profiles);
params.user_name = base::ASCIIToUTF16(
base::StringPrintf("testing_profile_user%" PRIuS, number_of_profiles));
params.is_consented_primary_account = true;
params.icon_index = number_of_profiles;
storage()->AddProfile(std::move(params));
EXPECT_EQ(number_of_profiles + 1, storage()->GetNumberOfProfiles());
}
TestingProfileManager testing_profile_manager_;
private:
content::BrowserTaskEnvironment task_environment_;
ProfileAttributesTestObserver observer_;
};
TEST_F(ProfileAttributesStorageTest, ProfileNotFound) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
ASSERT_EQ(storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0")),
nullptr);
AddTestingProfile();
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
ASSERT_NE(storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0")),
nullptr);
ASSERT_EQ(storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path1")),
nullptr);
}
TEST_F(ProfileAttributesStorageTest, AddProfile) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
EXPECT_CALL(observer(), OnProfileAdded(GetProfilePath("new_profile_path_1")))
.Times(1);
ProfileAttributesInitParams params;
params.profile_path = GetProfilePath("new_profile_path_1");
params.profile_name = u"new_profile_name_1";
params.gaia_id = "new_profile_gaia_1";
params.user_name = u"new_profile_username_1";
params.is_consented_primary_account = true;
params.icon_index = 1;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("new_profile_path_1"));
ASSERT_NE(entry, nullptr);
EXPECT_EQ(u"new_profile_name_1", entry->GetName());
}
TEST_F(ProfileAttributesStorageTest, RemoveProfile) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_EQ(entry, nullptr);
AddTestingProfile();
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(entry, nullptr);
EXPECT_EQ(u"testing_profile_name0", entry->GetName());
// Deleting an existing profile. This should call observers and make the entry
// un-retrievable.
AddCallExpectationsForRemoveProfile(0);
storage()->RemoveProfile(GetProfilePath("testing_profile_path0"));
VerifyAndResetCallExpectations();
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
EXPECT_EQ(entry, nullptr);
}
TEST_F(ProfileAttributesStorageTest, MultipleProfiles) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
for (size_t i = 0; i < 5; ++i) {
AddTestingProfile();
EXPECT_EQ(i + 1, storage()->GetNumberOfProfiles());
EXPECT_EQ(i + 1, storage()->GetAllProfilesAttributes().size());
EXPECT_EQ(i + 1, storage()->GetAllProfilesAttributesSortedByName().size());
}
EXPECT_EQ(5U, storage()->GetNumberOfProfiles());
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(entry, nullptr);
EXPECT_EQ(u"testing_profile_name0", entry->GetName());
AddCallExpectationsForRemoveProfile(0);
storage()->RemoveProfile(GetProfilePath("testing_profile_path0"));
VerifyAndResetCallExpectations();
entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_EQ(entry, nullptr);
EXPECT_EQ(4U, storage()->GetNumberOfProfiles());
std::vector<ProfileAttributesEntry*> entries =
storage()->GetAllProfilesAttributes();
for (auto* entry : entries) {
EXPECT_NE(GetProfilePath("testing_profile_path0"), entry->GetPath());
}
}
TEST_F(ProfileAttributesStorageTest, InitialValues) {
#if defined(OS_ANDROID)
// Android has only one default avatar.
size_t kIconIndex = 0;
#else
size_t kIconIndex = 1;
#endif
base::FilePath profile_path = GetProfilePath("testing_profile_path");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"testing_profile_name";
params.gaia_id = "testing_profile_gaia";
params.user_name = u"testing_profile_username";
params.is_consented_primary_account = true;
params.icon_index = kIconIndex;
params.supervised_user_id = "testing_supervised_user_id";
params.account_id = AccountId::FromUserEmailGaiaId(
base::UTF16ToUTF8(params.user_name), params.gaia_id);
params.is_guest = true;
params.is_ephemeral = true;
params.is_omitted = true;
params.is_signed_in_with_credential_provider = true;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
VerifyInitialValues(
entry, profile_path, /*profile_name=*/u"testing_profile_name",
/*gaia_id=*/"testing_profile_gaia",
/*user_name=*/u"testing_profile_username",
/*is_consented_primary_account=*/true, /*icon_index=*/kIconIndex,
/*supervised_user_id=*/"testing_supervised_user_id", /*is_guest=*/true,
/*is_ephemeral=*/true, /*is_omitted=*/true,
/*is_signed_in_with_credential_provider=*/true);
}
TEST_F(ProfileAttributesStorageTest, InitialValues_Defaults) {
base::FilePath profile_path = GetProfilePath("testing_profile_path");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
// Verify defaults of ProfileAttributesInitParams.
EXPECT_TRUE(params.profile_name.empty());
EXPECT_TRUE(params.gaia_id.empty());
EXPECT_TRUE(params.user_name.empty());
EXPECT_FALSE(params.is_consented_primary_account);
EXPECT_EQ(0U, params.icon_index);
EXPECT_TRUE(params.supervised_user_id.empty());
EXPECT_TRUE(params.account_id.empty());
EXPECT_FALSE(params.is_guest);
EXPECT_FALSE(params.is_ephemeral);
EXPECT_FALSE(params.is_omitted);
EXPECT_FALSE(params.is_signed_in_with_credential_provider);
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
VerifyInitialValues(entry, profile_path, /*profile_name=*/std::u16string(),
/*gaia_id=*/std::string(), /*user_name=*/std::u16string(),
/*is_consented_primary_account=*/false, /*icon_index=*/0,
/*supervised_user_id=*/std::string(), /*is_guest=*/false,
/*is_ephemeral=*/false, /*is_omitted=*/false,
/*is_signed_in_with_credential_provider=*/false);
}
TEST_F(ProfileAttributesStorageTest, EntryAccessors) {
AddTestingProfile();
base::FilePath path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(path);
ASSERT_NE(entry, nullptr);
EXPECT_EQ(path, entry->GetPath());
EXPECT_CALL(observer(), OnProfileNameChanged(path, _)).Times(2);
entry->SetLocalProfileName(u"first_value", true);
EXPECT_EQ(u"first_value", entry->GetLocalProfileName());
EXPECT_TRUE(entry->IsUsingDefaultName());
entry->SetLocalProfileName(u"second_value", false);
EXPECT_EQ(u"second_value", entry->GetLocalProfileName());
EXPECT_FALSE(entry->IsUsingDefaultName());
VerifyAndResetCallExpectations();
TEST_STRING16_ACCESSORS(ProfileAttributesEntry, entry, ShortcutName);
TEST_ACCESSORS(ProfileAttributesEntry, entry, BackgroundStatus, true, false);
EXPECT_CALL(observer(), OnProfileNameChanged(path, _)).Times(4);
TEST_STRING16_ACCESSORS(ProfileAttributesEntry, entry, GAIAName);
TEST_STRING16_ACCESSORS(ProfileAttributesEntry, entry, GAIAGivenName);
VerifyAndResetCallExpectations();
EXPECT_CALL(observer(), OnProfileAvatarChanged(path)).Times(2);
TEST_BOOL_ACCESSORS(ProfileAttributesEntry, entry, IsUsingGAIAPicture);
VerifyAndResetCallExpectations();
// IsOmitted() should be set only on ephemeral profiles.
entry->SetIsEphemeral(true);
EXPECT_CALL(observer(), OnProfileIsOmittedChanged(path)).Times(2);
TEST_BOOL_ACCESSORS(ProfileAttributesEntry, entry, IsOmitted);
VerifyAndResetCallExpectations();
entry->SetIsEphemeral(false);
EXPECT_CALL(observer(), OnProfileHostedDomainChanged(path)).Times(2);
TEST_STRING_ACCESSORS(ProfileAttributesEntry, entry, HostedDomain);
VerifyAndResetCallExpectations();
TEST_BOOL_ACCESSORS(ProfileAttributesEntry, entry, IsEphemeral);
EXPECT_CALL(observer(), OnProfileNameChanged(path, _)).Times(2);
TEST_BOOL_ACCESSORS(ProfileAttributesEntry, entry, IsUsingDefaultName);
VerifyAndResetCallExpectations();
TEST_BOOL_ACCESSORS(ProfileAttributesEntry, entry, IsUsingDefaultAvatar);
}
TEST_F(ProfileAttributesStorageTest, EntryInternalAccessors) {
AddTestingProfile();
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(entry, nullptr);
EXPECT_EQ(GetProfilePath("testing_profile_path0"), entry->GetPath());
const char key[] = "test";
// Tests whether the accessors store and retrieve values correctly.
EXPECT_TRUE(entry->SetString(key, std::string("abcd")));
ASSERT_TRUE(entry->GetValue(key));
EXPECT_EQ(base::Value::Type::STRING, entry->GetValue(key)->type());
EXPECT_EQ(std::string("abcd"), entry->GetString(key));
EXPECT_EQ(u"abcd", entry->GetString16(key));
EXPECT_EQ(0.0, entry->GetDouble(key));
EXPECT_FALSE(entry->GetBool(key));
EXPECT_FALSE(entry->IsDouble(key));
EXPECT_TRUE(entry->SetString16(key, u"efgh"));
ASSERT_TRUE(entry->GetValue(key));
EXPECT_EQ(base::Value::Type::STRING, entry->GetValue(key)->type());
EXPECT_EQ(std::string("efgh"), entry->GetString(key));
EXPECT_EQ(u"efgh", entry->GetString16(key));
EXPECT_EQ(0.0, entry->GetDouble(key));
EXPECT_FALSE(entry->GetBool(key));
EXPECT_FALSE(entry->IsDouble(key));
EXPECT_TRUE(entry->SetDouble(key, 12.5));
ASSERT_TRUE(entry->GetValue(key));
EXPECT_EQ(base::Value::Type::DOUBLE, entry->GetValue(key)->type());
EXPECT_EQ(std::string(), entry->GetString(key));
EXPECT_EQ(u"", entry->GetString16(key));
EXPECT_EQ(12.5, entry->GetDouble(key));
EXPECT_FALSE(entry->GetBool(key));
EXPECT_TRUE(entry->IsDouble(key));
EXPECT_TRUE(entry->SetBool(key, true));
ASSERT_TRUE(entry->GetValue(key));
EXPECT_EQ(base::Value::Type::BOOLEAN, entry->GetValue(key)->type());
EXPECT_EQ(std::string(), entry->GetString(key));
EXPECT_EQ(u"", entry->GetString16(key));
EXPECT_EQ(0.0, entry->GetDouble(key));
EXPECT_TRUE(entry->GetBool(key));
EXPECT_FALSE(entry->IsDouble(key));
// Test whether the setters returns correctly. Setters should return true if
// the previously stored value is different from the new value.
entry->SetBool(key, true);
EXPECT_TRUE(entry->SetString(key, std::string("abcd")));
EXPECT_FALSE(entry->SetString(key, std::string("abcd")));
EXPECT_FALSE(entry->SetString16(key, u"abcd"));
EXPECT_TRUE(entry->SetString16(key, u"efgh"));
EXPECT_FALSE(entry->SetString16(key, u"efgh"));
EXPECT_FALSE(entry->SetString(key, std::string("efgh")));
EXPECT_TRUE(entry->SetDouble(key, 12.5));
EXPECT_FALSE(entry->SetDouble(key, 12.5));
EXPECT_TRUE(entry->SetDouble(key, 15.0));
EXPECT_TRUE(entry->SetString(key, std::string("abcd")));
EXPECT_TRUE(entry->SetBool(key, true));
EXPECT_FALSE(entry->SetBool(key, true));
EXPECT_TRUE(entry->SetBool(key, false));
EXPECT_TRUE(entry->SetString16(key, u"efgh"));
// If previous data is not there, setters should returns true even if the
// defaults (empty string, 0.0, or false) are written.
EXPECT_TRUE(entry->SetString("test1", std::string()));
EXPECT_TRUE(entry->SetString16("test2", std::u16string()));
EXPECT_TRUE(entry->SetDouble("test3", 0.0));
EXPECT_TRUE(entry->SetBool("test4", false));
// If previous data is in a wrong type, setters should returns true even if
// the defaults (empty string, 0.0, or false) are written.
EXPECT_TRUE(entry->SetString("test3", std::string()));
EXPECT_TRUE(entry->SetString16("test4", std::u16string()));
EXPECT_TRUE(entry->SetDouble("test1", 0.0));
EXPECT_TRUE(entry->SetBool("test2", false));
}
TEST_F(ProfileAttributesStorageTest, ProfileActiveTime) {
AddTestingProfile();
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(entry, nullptr);
// Check the state before active time is stored.
const char kActiveTimeKey[] = "active_time";
EXPECT_FALSE(entry->IsDouble(kActiveTimeKey));
EXPECT_EQ(base::Time(), entry->GetActiveTime());
// Store the time and check for the result. Allow for a difference one second
// because the 64-bit integral representation in base::Time is rounded off to
// a double, which is what base::Value stores. http://crbug.com/346827
base::Time lower_bound = base::Time::Now() - base::TimeDelta::FromSeconds(1);
entry->SetActiveTimeToNow();
base::Time upper_bound = base::Time::Now() + base::TimeDelta::FromSeconds(1);
EXPECT_TRUE(entry->IsDouble(kActiveTimeKey));
EXPECT_LE(lower_bound, entry->GetActiveTime());
EXPECT_GE(upper_bound, entry->GetActiveTime());
// If the active time was less than one hour ago, SetActiveTimeToNow should do
// nothing.
base::Time past = base::Time::Now() - base::TimeDelta::FromMinutes(10);
lower_bound = past - base::TimeDelta::FromSeconds(1);
upper_bound = past + base::TimeDelta::FromSeconds(1);
ASSERT_TRUE(entry->SetDouble(kActiveTimeKey, past.ToDoubleT()));
base::Time stored_time = entry->GetActiveTime();
ASSERT_LE(lower_bound, stored_time);
ASSERT_GE(upper_bound, stored_time);
entry->SetActiveTimeToNow();
EXPECT_EQ(stored_time, entry->GetActiveTime());
}
TEST_F(ProfileAttributesStorageTest, AuthInfo) {
AddTestingProfile();
base::FilePath path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(path);
ASSERT_NE(entry, nullptr);
EXPECT_CALL(observer(), OnProfileAuthInfoChanged(path)).Times(1);
entry->SetAuthInfo("", std::u16string(), false);
VerifyAndResetCallExpectations();
ASSERT_EQ(entry->GetSigninState(), SigninState::kNotSignedIn);
EXPECT_EQ(std::u16string(), entry->GetUserName());
EXPECT_EQ("", entry->GetGAIAId());
EXPECT_CALL(observer(), OnProfileAuthInfoChanged(path)).Times(1);
entry->SetAuthInfo("foo", u"bar", true);
VerifyAndResetCallExpectations();
ASSERT_TRUE(entry->IsAuthenticated());
EXPECT_EQ(u"bar", entry->GetUserName());
EXPECT_EQ("foo", entry->GetGAIAId());
}
TEST_F(ProfileAttributesStorageTest, SupervisedUsersAccessors) {
AddTestingProfile();
base::FilePath path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(entry, nullptr);
entry->SetSupervisedUserId("");
ASSERT_FALSE(entry->IsSupervised());
ASSERT_FALSE(entry->IsChild());
EXPECT_CALL(observer(), OnProfileSupervisedUserIdChanged(path)).Times(1);
entry->SetSupervisedUserId("some_supervised_user_id");
VerifyAndResetCallExpectations();
ASSERT_TRUE(entry->IsSupervised());
ASSERT_FALSE(entry->IsChild());
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
EXPECT_CALL(observer(), OnProfileSupervisedUserIdChanged(path)).Times(1);
entry->SetSupervisedUserId(supervised_users::kChildAccountSUID);
VerifyAndResetCallExpectations();
ASSERT_TRUE(entry->IsSupervised());
ASSERT_TRUE(entry->IsChild());
#endif // BUILDFLAG(ENABLE_SUPERVISED_USERS)
}
TEST_F(ProfileAttributesStorageTest, ReSortTriggered) {
DisableObserver(); // No need to test observers in this test.
ProfileAttributesInitParams alpha_params;
alpha_params.profile_path = GetProfilePath("alpha_path");
alpha_params.profile_name = u"alpha";
alpha_params.gaia_id = "alpha_gaia";
alpha_params.user_name = u"alpha_username";
alpha_params.is_consented_primary_account = true;
alpha_params.icon_index = 1;
storage()->AddProfile(std::move(alpha_params));
ProfileAttributesInitParams lima_params;
lima_params.profile_path = GetProfilePath("lime_path");
lima_params.profile_name = u"lima";
lima_params.gaia_id = "lima_gaia";
lima_params.user_name = u"lima_username";
lima_params.is_consented_primary_account = true;
lima_params.icon_index = 1;
storage()->AddProfile(std::move(lima_params));
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(GetProfilePath("alpha_path"));
ASSERT_NE(entry, nullptr);
// Trigger a ProfileInfoCache re-sort.
entry->SetLocalProfileName(u"zulu_name",
/*is_default_name=*/false);
EXPECT_EQ(GetProfilePath("alpha_path"), entry->GetPath());
}
TEST_F(ProfileAttributesStorageTest, RemoveOtherProfile) {
AddTestingProfile();
AddTestingProfile();
AddTestingProfile();
EXPECT_EQ(3U, storage()->GetNumberOfProfiles());
ProfileAttributesEntry* first_entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(first_entry, nullptr);
ProfileAttributesEntry* second_entry =
storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path1"));
ASSERT_NE(second_entry, nullptr);
EXPECT_EQ(u"testing_profile_name0", first_entry->GetName());
AddCallExpectationsForRemoveProfile(1);
storage()->RemoveProfile(GetProfilePath("testing_profile_path1"));
VerifyAndResetCallExpectations();
second_entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path1"));
ASSERT_EQ(second_entry, nullptr);
EXPECT_EQ(GetProfilePath("testing_profile_path0"), first_entry->GetPath());
EXPECT_EQ(u"testing_profile_name0", first_entry->GetName());
// Deleting through the ProfileInfoCache should be reflected in the
// ProfileAttributesStorage as well.
AddCallExpectationsForRemoveProfile(2);
profile_info_cache()->RemoveProfile(
GetProfilePath("testing_profile_path2"));
VerifyAndResetCallExpectations();
second_entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path2"));
ASSERT_EQ(second_entry, nullptr);
}
TEST_F(ProfileAttributesStorageTest, AccessFromElsewhere) {
AddTestingProfile();
DisableObserver(); // No need to test observers in this test.
ProfileAttributesEntry* first_entry = storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(first_entry, nullptr);
ProfileAttributesEntry* second_entry =
storage()->GetProfileAttributesWithPath(
GetProfilePath("testing_profile_path0"));
ASSERT_NE(second_entry, nullptr);
first_entry->SetLocalProfileName(u"NewName",
/*is_default_name=*/false);
EXPECT_EQ(u"NewName", second_entry->GetName());
EXPECT_EQ(first_entry, second_entry);
// The ProfileInfoCache should also reflect the changes and its changes
// should be reflected by the ProfileAttributesStorage.
EXPECT_EQ(u"NewName", second_entry->GetName());
second_entry->SetLocalProfileName(u"OtherNewName",
/*is_default_name=*/false);
EXPECT_EQ(u"OtherNewName", first_entry->GetName());
}
TEST_F(ProfileAttributesStorageTest, ChooseAvatarIconIndexForNewProfile) {
size_t total_icon_count = profiles::GetDefaultAvatarIconCount() -
profiles::GetModernAvatarIconStartIndex();
// Run ChooseAvatarIconIndexForNewProfile |num_iterations| times before using
// the final |icon_index| to add a profile. Multiple checks are needed because
// ChooseAvatarIconIndexForNewProfile is non-deterministic.
const int num_iterations = 10;
std::unordered_set<int> used_icon_indices;
for (size_t i = 0; i < total_icon_count; ++i) {
EXPECT_EQ(i, storage()->GetNumberOfProfiles());
size_t icon_index = 0;
for (int iter = 0; iter < num_iterations; ++iter) {
icon_index = storage()->ChooseAvatarIconIndexForNewProfile();
// Icon must not be used.
ASSERT_EQ(0u, used_icon_indices.count(icon_index));
ASSERT_TRUE(profiles::IsModernAvatarIconIndex(icon_index));
}
used_icon_indices.insert(icon_index);
base::FilePath profile_path =
GetProfilePath(base::StringPrintf("testing_profile_path%" PRIuS, i));
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.icon_index = icon_index;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
}
for (int iter = 0; iter < num_iterations; ++iter) {
// All icons are used up, expect any valid icon.
ASSERT_TRUE(profiles::IsModernAvatarIconIndex(
storage()->ChooseAvatarIconIndexForNewProfile()));
}
}
TEST_F(ProfileAttributesStorageTest, IsSigninRequiredOnInit_NotAuthenticated) {
signin_util::ScopedForceSigninSetterForTesting force_signin_setter(true);
base::FilePath profile_path = GetProfilePath("testing_profile_path");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"testing_profile_name";
params.is_consented_primary_account = false;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
EXPECT_FALSE(entry->IsAuthenticated());
EXPECT_TRUE(entry->IsSigninRequired());
}
TEST_F(ProfileAttributesStorageTest, IsSigninRequiredOnInit_Authenticated) {
signin_util::ScopedForceSigninSetterForTesting force_signin_setter(true);
base::FilePath profile_path = GetProfilePath("testing_profile_path");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"testing_profile_name";
params.gaia_id = "testing_profile_gaia";
params.user_name = u"testing_profile_username";
params.is_consented_primary_account = true;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
EXPECT_TRUE(entry->IsAuthenticated());
EXPECT_FALSE(entry->IsSigninRequired());
}
TEST_F(ProfileAttributesStorageTest,
IsSigninRequiredOnInit_FromPreviousSession) {
base::FilePath profile_path = GetProfilePath("testing_profile_path");
{
signin_util::ScopedForceSigninSetterForTesting force_signin_setter(true);
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"testing_profile_name";
params.gaia_id = "testing_profile_gaia";
params.user_name = u"testing_profile_username";
params.is_consented_primary_account = true;
storage()->AddProfile(std::move(params));
VerifyAndResetCallExpectations();
// IsSigninRequired() cannot be set as an init parameter. Set it after an
// entry is initialized and reset the cache to reinitialize an entry from
// prefs.
EXPECT_CALL(observer(), OnProfileSigninRequiredChanged(profile_path))
.Times(1);
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
entry->LockForceSigninProfile(true);
VerifyAndResetCallExpectations();
testing_profile_manager_.DeleteProfileInfoCache();
entry = storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
EXPECT_TRUE(entry->IsAuthenticated());
EXPECT_TRUE(entry->IsSigninRequired());
}
// Reset the cache once more after the policy has been disabled and check that
// sign-in is no longer required.
testing_profile_manager_.DeleteProfileInfoCache();
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
EXPECT_TRUE(entry->IsAuthenticated());
EXPECT_FALSE(entry->IsSigninRequired());
}
TEST_F(ProfileAttributesStorageTest, ProfileForceSigninLock) {
signin_util::ScopedForceSigninSetterForTesting force_signin_setter(true);
AddTestingProfile();
base::FilePath path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry = storage()->GetProfileAttributesWithPath(path);
ASSERT_NE(entry, nullptr);
ASSERT_FALSE(entry->IsSigninRequired());
entry->LockForceSigninProfile(false);
ASSERT_FALSE(entry->IsSigninRequired());
EXPECT_CALL(observer(), OnProfileSigninRequiredChanged(path)).Times(1);
entry->LockForceSigninProfile(true);
VerifyAndResetCallExpectations();
ASSERT_TRUE(entry->IsSigninRequired());
EXPECT_CALL(observer(), OnProfileSigninRequiredChanged(path)).Times(1);
entry->LockForceSigninProfile(false);
VerifyAndResetCallExpectations();
ASSERT_FALSE(entry->IsSigninRequired());
}
// Avatar icons not used on Android.
#if !defined(OS_ANDROID)
TEST_F(ProfileAttributesStorageTest, AvatarIconIndex) {
AddTestingProfile();
base::FilePath profile_path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
ASSERT_EQ(0U, entry->GetAvatarIconIndex());
EXPECT_CALL(observer(), OnProfileAvatarChanged(profile_path)).Times(1);
entry->SetAvatarIconIndex(2U);
VerifyAndResetCallExpectations();
ASSERT_EQ(2U, entry->GetAvatarIconIndex());
EXPECT_CALL(observer(), OnProfileAvatarChanged(profile_path)).Times(1);
entry->SetAvatarIconIndex(3U);
VerifyAndResetCallExpectations();
ASSERT_EQ(3U, entry->GetAvatarIconIndex());
}
#endif
// High res avatar downloading is only supported on desktop.
#if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(ProfileAttributesStorageTest, DownloadHighResAvatarTest) {
storage()->set_disable_avatar_download_for_testing(false);
const size_t kIconIndex = 0;
base::FilePath icon_path =
profiles::GetPathOfHighResAvatarAtIndex(kIconIndex);
ASSERT_EQ(0U, storage()->GetNumberOfProfiles());
base::FilePath profile_path = GetProfilePath("path_1");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"name_1";
params.icon_index = kIconIndex;
storage()->AddProfile(std::move(params));
ASSERT_EQ(1U, storage()->GetNumberOfProfiles());
VerifyAndResetCallExpectations();
// Make sure there are no avatars already on disk.
content::RunAllTasksUntilIdle();
ASSERT_FALSE(base::PathExists(icon_path));
// We haven't downloaded any high-res avatars yet.
EXPECT_EQ(0U, storage()->cached_avatar_images_.size());
// After adding a new profile, the download of high-res avatar will be
// triggered. But the downloader won't ever call OnFetchComplete in the test.
EXPECT_EQ(1U, storage()->avatar_images_downloads_in_progress_.size());
// |GetHighResAvater| does not contain a cached avatar, so it should return
// null.
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
EXPECT_FALSE(entry->GetHighResAvatar());
// The previous |GetHighResAvater| starts |LoadAvatarPictureFromPath| async.
// The async code will end up at |OnAvatarPictureLoaded| storing an empty
// image in the cache.
EXPECT_CALL(observer(), OnProfileHighResAvatarLoaded(profile_path)).Times(1);
content::RunAllTasksUntilIdle();
VerifyAndResetCallExpectations();
std::string icon_filename =
profiles::GetDefaultAvatarIconFileNameAtIndex(kIconIndex);
EXPECT_EQ(1U, storage()->cached_avatar_images_.size());
EXPECT_TRUE(storage()->cached_avatar_images_[icon_filename].IsEmpty());
// Simulate downloading a high-res avatar.
ProfileAvatarDownloader avatar_downloader(
kIconIndex,
base::BindOnce(&ProfileAttributesStorage::SaveAvatarImageAtPathNoCallback,
base::Unretained(storage()), entry->GetPath()));
// Put a real bitmap into "bitmap": a 2x2 bitmap of green 32 bit pixels.
SkBitmap bitmap;
bitmap.allocN32Pixels(2, 2);
bitmap.eraseColor(SK_ColorGREEN);
avatar_downloader.OnFetchComplete(GURL("http://www.google.com/avatar.png"),
&bitmap);
// Now the download should not be in progress anymore.
EXPECT_EQ(0U, storage()->avatar_images_downloads_in_progress_.size());
// The image should have been cached.
EXPECT_EQ(1U, storage()->cached_avatar_images_.size());
EXPECT_FALSE(storage()->cached_avatar_images_[icon_filename].IsEmpty());
EXPECT_EQ(&storage()->cached_avatar_images_[icon_filename],
entry->GetHighResAvatar());
// Since we are not using GAIA image, |GetAvatarIcon| should return the same
// image as |GetHighResAvatar| in desktop. Since it returns a copy, the
// backing object needs to get checked.
const gfx::ImageSkia* avatar_icon = entry->GetAvatarIcon().ToImageSkia();
const gfx::ImageSkia* cached_icon =
storage()->cached_avatar_images_[icon_filename].ToImageSkia();
EXPECT_TRUE(avatar_icon->BackedBySameObjectAs(*cached_icon));
// Finish the async calls that save the image to the disk.
EXPECT_CALL(observer(), OnProfileHighResAvatarLoaded(profile_path)).Times(1);
content::RunAllTasksUntilIdle();
VerifyAndResetCallExpectations();
// Clean up.
EXPECT_NE(std::string::npos, icon_path.MaybeAsASCII().find(icon_filename));
ASSERT_TRUE(base::PathExists(icon_path));
EXPECT_TRUE(base::DeleteFile(icon_path));
EXPECT_FALSE(base::PathExists(icon_path));
}
TEST_F(ProfileAttributesStorageTest, NothingToDownloadHighResAvatarTest) {
storage()->set_disable_avatar_download_for_testing(false);
const size_t kIconIndex = profiles::GetPlaceholderAvatarIndex();
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
base::FilePath profile_path = GetProfilePath("path_1");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"name_1";
params.icon_index = kIconIndex;
storage()->AddProfile(std::move(params));
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
content::RunAllTasksUntilIdle();
// We haven't tried to download any high-res avatars as the specified icon is
// just a placeholder.
EXPECT_EQ(0U, storage()->cached_avatar_images_.size());
EXPECT_EQ(0U, storage()->avatar_images_downloads_in_progress_.size());
}
TEST_F(ProfileAttributesStorageTest, LoadAvatarFromDiskTest) {
const size_t kIconIndex = 0;
base::FilePath icon_path =
profiles::GetPathOfHighResAvatarAtIndex(kIconIndex);
// Create the avatar on the disk, which is a valid 1x1 transparent png.
base::FilePath dir = icon_path.DirName();
ASSERT_FALSE(base::DirectoryExists(dir));
ASSERT_TRUE(base::CreateDirectory(dir));
ASSERT_FALSE(base::PathExists(icon_path));
const char bitmap[] =
"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A\x00\x00\x00\x0D\x49\x48\x44\x52"
"\x00\x00\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00\x00\x37\x6E\xF9"
"\x24\x00\x00\x00\x0A\x49\x44\x41\x54\x08\x1D\x63\x60\x00\x00\x00"
"\x02\x00\x01\xCF\xC8\x35\xE5\x00\x00\x00\x00\x49\x45\x4E\x44\xAE"
"\x42\x60\x82";
base::WriteFile(icon_path, bitmap, sizeof(bitmap));
ASSERT_TRUE(base::PathExists(icon_path));
// Add a new profile.
ASSERT_EQ(0U, storage()->GetNumberOfProfiles());
base::FilePath profile_path = GetProfilePath("path_1");
EXPECT_CALL(observer(), OnProfileAdded(profile_path)).Times(1);
ProfileAttributesInitParams params;
params.profile_path = profile_path;
params.profile_name = u"name_1";
params.icon_index = kIconIndex;
storage()->AddProfile(std::move(params));
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
VerifyAndResetCallExpectations();
// Load the avatar image.
storage()->set_disable_avatar_download_for_testing(false);
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
ASSERT_FALSE(entry->IsUsingGAIAPicture());
EXPECT_CALL(observer(), OnProfileHighResAvatarLoaded(profile_path)).Times(1);
entry->GetAvatarIcon();
// Wait until the avatar image finish loading.
content::RunAllTasksUntilIdle();
VerifyAndResetCallExpectations();
// Clean up.
EXPECT_TRUE(base::DeleteFile(icon_path));
EXPECT_FALSE(base::PathExists(icon_path));
}
#endif
TEST_F(ProfileAttributesStorageTest, ProfilesState_ActiveMultiProfile) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
for (size_t i = 0; i < 5; ++i)
AddTestingProfile();
EXPECT_EQ(5U, storage()->GetNumberOfProfiles());
std::vector<ProfileAttributesEntry*> entries =
storage()->GetAllProfilesAttributes();
entries[0]->SetActiveTimeToNow();
entries[1]->SetActiveTimeToNow();
base::HistogramTester histogram_tester;
storage()->RecordProfilesState();
// There are 5 profiles all together.
histogram_tester.ExpectTotalCount("Profile.State.Avatar_All", 5);
histogram_tester.ExpectTotalCount("Profile.State.Avatar_ActiveMultiProfile",
5);
// Other user segments get 0 records.
histogram_tester.ExpectTotalCount("Profile.State.Avatar_SingleProfile", 0);
histogram_tester.ExpectTotalCount("Profile.State.Avatar_LatentMultiProfile",
0);
histogram_tester.ExpectTotalCount(
"Profile.State.Avatar_LatentMultiProfileActive", 0);
histogram_tester.ExpectTotalCount(
"Profile.State.Avatar_LatentMultiProfileOthers", 0);
}
// On Android (at least on KitKat), all profiles are considered active (because
// ActiveTime is not set in production). Thus, these test does not work.
#if !defined(OS_ANDROID)
TEST_F(ProfileAttributesStorageTest, ProfilesState_LatentMultiProfile) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
for (size_t i = 0; i < 5; ++i)
AddTestingProfile();
EXPECT_EQ(5U, storage()->GetNumberOfProfiles());
std::vector<ProfileAttributesEntry*> entries =
storage()->GetAllProfilesAttributes();
entries[0]->SetActiveTimeToNow();
base::HistogramTester histogram_tester;
storage()->RecordProfilesState();
// There are 5 profiles all together.
histogram_tester.ExpectTotalCount("Profile.State.Name_All", 5);
histogram_tester.ExpectTotalCount("Profile.State.Name_LatentMultiProfile", 5);
histogram_tester.ExpectTotalCount(
"Profile.State.Name_LatentMultiProfileActive", 1);
histogram_tester.ExpectTotalCount(
"Profile.State.Name_LatentMultiProfileOthers", 4);
// Other user segments get 0 records.
histogram_tester.ExpectTotalCount("Profile.State.Name_SingleProfile", 0);
histogram_tester.ExpectTotalCount("Profile.State.Name_ActiveMultiProfile", 0);
}
#endif
TEST_F(ProfileAttributesStorageTest, ProfilesState_SingleProfile) {
EXPECT_EQ(0U, storage()->GetNumberOfProfiles());
AddTestingProfile();
EXPECT_EQ(1U, storage()->GetNumberOfProfiles());
base::HistogramTester histogram_tester;
storage()->RecordProfilesState();
// There is 1 profile all together.
histogram_tester.ExpectTotalCount("Profile.State.LastUsed_All", 1);
histogram_tester.ExpectTotalCount("Profile.State.LastUsed_SingleProfile", 1);
// Other user segments get 0 records.
histogram_tester.ExpectTotalCount("Profile.State.LastUsed_ActiveMultiProfile",
0);
histogram_tester.ExpectTotalCount("Profile.State.LastUsed_LatentMultiProfile",
0);
histogram_tester.ExpectTotalCount(
"Profile.State.LastUsed_LatentMultiProfileActive", 0);
histogram_tester.ExpectTotalCount(
"Profile.State.LastUsed_LatentMultiProfileOthers", 0);
}
// Themes aren't used on Android
#if !defined(OS_ANDROID)
TEST_F(ProfileAttributesStorageTest, ProfileThemeColors) {
AddTestingProfile();
base::FilePath profile_path = GetProfilePath("testing_profile_path0");
ProfileAttributesEntry* entry =
storage()->GetProfileAttributesWithPath(profile_path);
ASSERT_NE(entry, nullptr);
EXPECT_CALL(observer(), OnProfileAvatarChanged(profile_path)).Times(1);
entry->SetAvatarIconIndex(profiles::GetPlaceholderAvatarIndex());
VerifyAndResetCallExpectations();
EXPECT_EQ(entry->GetProfileThemeColors(),
GetDefaultProfileThemeColors(false));
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(true);
EXPECT_EQ(entry->GetProfileThemeColors(), GetDefaultProfileThemeColors(true));
EXPECT_NE(entry->GetProfileThemeColors(),
GetDefaultProfileThemeColors(false));
ProfileThemeColors colors = {SK_ColorTRANSPARENT, SK_ColorBLACK,
SK_ColorWHITE};
EXPECT_CALL(observer(), OnProfileAvatarChanged(profile_path)).Times(1);
EXPECT_CALL(observer(), OnProfileThemeColorsChanged(profile_path)).Times(1);
entry->SetProfileThemeColors(colors);
EXPECT_EQ(entry->GetProfileThemeColors(), colors);
VerifyAndResetCallExpectations();
// Colors shouldn't change after switching back to the light mode.
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(false);
EXPECT_EQ(entry->GetProfileThemeColors(), colors);
// absl::nullopt resets the colors to default.
EXPECT_CALL(observer(), OnProfileAvatarChanged(profile_path)).Times(1);
EXPECT_CALL(observer(), OnProfileThemeColorsChanged(profile_path)).Times(1);
entry->SetProfileThemeColors(absl::nullopt);
EXPECT_EQ(entry->GetProfileThemeColors(),
GetDefaultProfileThemeColors(false));
VerifyAndResetCallExpectations();
}
#endif
|
;
; Old School Computer Architecture - interfacing FLOS
; Stefano Bodrato, 2012
;
; void set_load_length(unsigned long length);
;
; Forces the read length of the file transfer to a certain value (use after find file)
;
; Input Registers :
; IX:IY = Bytes to load
;
;
; $Id: set_load_length.asm,v 1.2 2012/03/08 07:16:46 stefano Exp $
;
INCLUDE "flos.def"
XLIB set_load_length
set_load_length:
;__FASTCALL__
;pop hl ; sector ptr
;pop iy
;pop ix
;push ix
;push iy
;push hl
push hl
pop iy
push de
pop ix
jp kjt_set_load_length
|
; You may customize this and other start-up templates;
; The location of this template is c:\emu8086\inc\0_com_template.txt
org 100h
main proc
mov ah,02h
mov cx,256 ;c=256
mov dx,0
int 21h
label:
int 21h
inc dx
dec cx
jnz label
label1:
int 21h
inc dx
;cx auto decrement
loop label
mov ah,4ch
int 21h
main endp
end main
ret
|
; A073089: a(n) = (1/2)*(4n - 3 - Sum_{k=1..n} A007400(k)).
; 0,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1,0,0,1,1,1,0,0,1,0,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,0,0,1,0,0,1,1
lpb $0
add $1,1
sub $2,$0
trn $0,2
dif $0,$1
mod $2,2
bin $1,$2
lpe
mov $0,$1
|
segment .data
a: dq 10
b: dq 11
mul: dw "Product" ,10 , 0
fmt: dq "%s %lld\n", 10, 0
segment .text
global main
extern printf
main:
push RBP
mov RAX , [a]
mov RDX, [b]
mul RDX
mov RDI, fmt
mov RSI, mul
mov RDX, RAX
mov RAX , 0
call printf
pop RBP
ret
|
/* The following code example is taken from the book
* "C++ Templates - The Complete Guide"
* by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
*
* (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include "stack7.hpp"
int main()
{
try {
Stack<int> intStack; // stack of ints
Stack<float> floatStack; // stack of floats
// manipulate int stack
intStack.push(42);
intStack.push(7);
// manipulate float stack
floatStack.push(7.7);
// print float stack
std::cout << floatStack.top() << std::endl;
floatStack.pop();
std::cout << floatStack.top() << std::endl;
floatStack.pop();
std::cout << floatStack.top() << std::endl;
floatStack.pop();
}
catch (std::exception const& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
}
// stack for ints using a vector as an internal container
Stack<int,std::vector> vStack;
//...
vStack.push(42);
vStack.push(7);
std::cout << vStack.top() << std::endl;
vStack.pop();
}
|
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1991
; * All Rights Reserved.
; */
PAGE ,132
TITLE PRINTER.SYS INT2FH Code
;****************** START OF SPECIFICATIONS **************************
;
; MODULE NAME: PRTINT2F.ASM
;
; DESCRIPTIVE NAME: PERFORM THE INT2FH FUNCTION OF PRINTER.SYS
;
; FUNCTION: THE INT2FH FUNCTION OF PRINTER.SYS WILL LOCK THE PRINTER
; DEVICE AND LOAD THE CODE PAGE SPECIFIED. WHEN AN UNLOCK
; IS ENCOUNTERED, THE SAVED CODE PAGE WILL BE ACTIVATED.
; ATTACHED.
;
; ENTRY POINT: INT2F_COM
;
; INPUT: AX = AD40H (CALL IDENTIFIER)
; BX = REQUESTED CODE PAGE (-1 FOR UNLOCK)
; DX = 0 - LPT1
; 1 - LPT2
; 2 - LPT3
;
; AT EXIT:
; NORMAL: CARRY CLEAR
;
; ERROR: CARRY SET - CODE PAGE NOT AVAILABLE OR DEVICE IS NOT CPSW.
;
; INTERNAL REFERENCES:
;
; ROUTINES: CHECK_FOR_CP - CHECKS TO SEE IF CODE PAGE REQUESTED IS
; AVAILABLE ON DEVICE REQUESTED.
; FIND_ACTIVE_CP - FINDS THE ACTIVE CODE PAGE ON SPECIFIED
; DEVICE; IF AVAILABLE.
; LOCK_CP - VERIFIES, LOADS, AND LOCKS DEVICE CODE PAGE.
; UNLOCK_CP - UNLOCKS DEVICE.
;
; DATA AREAS: INVOKE_BLOCK - PARAMETER BLOCK PASSED TO INVOKE PROC.
;
;
; EXTERNAL REFERENCES:
;
; ROUTINES: INVOKE - ACTIVATES FONT REQUESTED.
;
; DATA AREAS: BUF1 - BUFFER FOR LPT1
; BUF2 - BUFFER FOR LPT2
; BUF3 - BUFFER FOR LPT3
;
; NOTES:
;
; REVISION HISTORY:
; A000 - DOS Version 4.00
;
; Label: "DOS PRINTER.SYS Device Driver"
; "Licensed Material - Program Property of Microsoft"
;
;****************** END OF SPECIFICATIONS ****************************
.XLIST
INCLUDE STRUC.INC ;AN000;
.LIST
INCLUDE CPSPEQU.INC ;AN000;
PRIV_LK_CP EQU 0AD40H ; multiplex number and function ;AN000;
LPT1 EQU 0 ; ;AN000;
LPT2 EQU 1 ; ;AN000;
LPT3 EQU 2 ; ;AN000;
UNLOCK EQU -1 ; unlock the device ;AN000;
UNDEFINED EQU -1 ; undefined code page ;AN000;
NOT_CY EQU 0FFFEH ; clear the carry in flag register ;AN000;
CY EQU 1 ; set the carry in flag register ;AN000;
FOUND EQU 1 ; search flag ;AN000;
NOT_FOUND EQU 0 ; ;AN000;
PUBLIC INT2F_COM ;AN000;
PUBLIC ROM_INT2F ;AN000;
PUBLIC ABORT ;AN000;
CSEG SEGMENT PARA PUBLIC 'CODE' ;AN000;
ASSUME CS:CSEG ;AN000;
EXTRN INVOKE:NEAR ;AN000;
EXTRN BUF0:BYTE ;AN000;
EXTRN BUF1:BYTE ;AN000;
EXTRN BUF2:BYTE ;AN000;
EXTRN BUF3:BYTE ;AN000;
ROM_INT2F DW ? ; chaining point for INT2FH ;AN000;
DW ? ;AN000;
COPY_BUF0 DW 0 ;AN000;
PREV_LOCK DB OFF ;AN000;
INVOKE_BLOCK LABEL BYTE ; parameter block passed to INVOKE ;AN000;
DB 3 DUP(0) ; ;AN000;
RET_STAT DW 0 ; returned status from INVOKE ;AN000;
DQ 0 ; ;AN000;
DB 6 DUP(0) ; ;AN000;
DW OFFSET PARA_BLOCK ; ;AN000;
CODE_SEGB DW SEG CSEG ; ;AN000;
;
PARA_BLOCK LABEL WORD ; ;AN000;
DW TWO ; ;AN000;
REQ_CP DW ? ; requested code page to load ;AN000;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; PROCEDURE_NAME: INT2F_COM
;
; FUNCTION:
; THIS IS THE INTERRUPT 2FH HANDLER TO CAPTURE THE FOLLOWING FUNCTIONS:
;
; AX=AD40H PRIVELEGED LOCK CP SWITCHING
;
; AT ENTRY: AX = AD40H
; BX = CODEPAGE REQUESTED DURING LOCK.
; -1 = UNLOCK
; DX = 0 - LPT1
; 1 - LPT2
; 2 - LPT3
;
;
; AT EXIT:
; NORMAL: CARRY CLEAR - DEVICE LOADED AND LOCKED
;
; ERROR: CARRY SET - CODE PAGE NOT AVAILABLE OR DEVICE NOT CPSW.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
INT2F_COM PROC NEAR ;AN000;
STI ;AN000;
.IF <AX NE PRIV_LK_CP> ; is this for PRINTER? ;AN000;
JMP DWORD PTR CS:ROM_INT2F ; no....jump to old INT2F ;AN000;
.ENDIF ; ;AN000;
PUSH AX ; ;AN000;
PUSH BP ; ;AN000;
PUSH BX ; s r ;AN000;
PUSH CX ; a e ;AN000;
PUSH DX ; v g ;AN000;
PUSH DI ; e s ;AN000;
PUSH SI ; ;AN000;
PUSH DS ; ;AN000;
PUSH ES ; ;AN000;
MOV CS:COPY_BUF0,ZERO ; ;AN000;
MOV CS:CODE_SEGB,CS ; ;AN000;
MOV BP,BX ; move req. cp to bp ;AN000;
.SELECT ; depending on the lptx.. ;AN000;
.WHEN <DX EQ LPT1> ; point to the appropriate ;AN000;
LEA BX,BUF1 ; buffer.. ;AN000;
LEA SI,BUF0 ; ;AN000;
MOV CS:COPY_BUF0,SI ; ;AN000;
.WHEN <DX EQ LPT2> ; ;AN000;
LEA BX,BUF2 ; ;AN000;
.WHEN <DX EQ LPT3> ; ;AN000;
LEA BX,BUF3 ; ;AN000;
.OTHERWISE ; ;AN000;
STC ; not a valid lptx..set flag ;AN000;
.ENDSELECT ; ;AN000;
.IF NC ; process ;AN000;
.IF <BP EQ UNLOCK> ; if unlock requested ;AN000;
CALL UNLOCK_CP ; unlock code page. ;AN000;
.ELSE ; must be a lock request.. ;AN000;
CALL LOCK_CP ; ;AN000;
.ENDIF ; ;AN000;
.ENDIF ; ;AN000;
MOV SI,CS:COPY_BUF0 ; ;AN000;
PUSHF ; ;AN000;
.IF <SI NE ZERO> ; if this is lpt1... ;AN000;
MOV AX,CS:[BX].STATE ; copy data into prn ;AN000;
MOV CS:[SI].STATE,AX ; buffer as well. ;AN000;
MOV AX,CS:[BX].SAVED_CP ; ;AN000;
MOV CS:[SI].SAVED_CP,AX ; ;AN000;
.ENDIF ; ;AN000;
POPF ; ;AN000;
POP ES ; ;AN000;
POP DS ; restore ;AN000;
POP SI ; ;AN000;
POP DI ; registers ;AN000;
POP DX ; ;AN000;
POP CX ; ;AN000;
POP BX ; ;AN000;
MOV BP,SP ; ;AN000;
MOV AX,[BP+8] ; load flag onto.. ;AN000;
.IF NC ; ;AN000;
AND AX,NOT_CY ; ;AN000;
.ELSE ; stack flags ;AN000;
OR AX,CY ; ;AN000;
.ENDIF ; ;AN000;
MOV [BP+8],AX ; ;AN000;
POP BP ; ;AN000;
POP AX ; ;AN000;
XCHG AH,AL ; exchange ah and al to show that.. ;AN000;
ABORT: IRET ; printer.sys is present. ;AN000;
INT2F_COM ENDP ;AN000;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; PROCEDURE_NAME: UNLOCK_CP
;
; FUNCTION:
; THIS FUNCTION UNLOCKS THE DEVICE THAT IS LOCKED.
;
; AT ENTRY:
; BX - POINTS TO LPTx BUFFER
;
;
; AT EXIT:
; NORMAL: CARRY CLEAR - DEVICE UNLOCKED.
;
; ERROR: CARRY SET - ERROR DURING UNLOCK, ACTIVE CODE PAGE SET TO INACTIVE
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
UNLOCK_CP PROC NEAR ;AN000;
.IF <CS:[BX].STATE EQ LOCKED> NEAR ; is device locked? ;AN000;
MOV CS:[BX].STATE,CPSW ; change status to unlocked.. ;AN000;
MOV BP,CS:[BX].SAVED_CP ; get saved code page ;AN000;
.IF <BP NE UNDEFINED> ; valid?..... ;AN000;
XOR AX,AX ; ;AN000;
CALL FIND_ACTIVE_CP ; find the active code page. ;AN000;
.IF <BP NE DX> ; are they the same..? ;AN000;
MOV CS:REQ_CP,BP ; no...invoke the saved code page ;AN000;
PUSH CS ; ;AN000;
POP ES ; ;AN000;
LEA DI,INVOKE_BLOCK ; ;AN000;
MOV CS:[BX].RH_PTRO,DI ; ;AN000;
MOV CS:[BX].RH_PTRS,ES ; ;AN000;
CALL INVOKE ; ;AN000;
.IF <AL NE ZERO> ; error on invoke? ;AN000;
MOV AX,ONE ; yes...change the active.. ;AN000;
CALL FIND_ACTIVE_CP ; to inactive. ;AN000;
.IF <CS:COPY_BUF0 NE ZERO> ; do likewise to PRN if this ;AN000;
PUSH BX ; is lpt1. ;AN000;
MOV BX,CS:COPY_BUF0 ; ;AN000;
CALL FIND_ACTIVE_CP ; ;AN000;
POP BX ; ;AN000;
.ENDIF ; ;AN000;
STC ; set error flag. ;AN000;
.ELSE ; ;AN000;
CLC ; invoke ok...clear error flag ;AN000;
.ENDIF ; ;AN000;
.ELSE ; ;AN000;
CLC ; active = saved ..no invoke... ;AN000;
.ENDIF ; clear error ;AN000;
.ELSE ; ;AN000;
MOV AX,ONE ; saved cp was inactive...change..;AN000;
CALL FIND_ACTIVE_CP ; active to inactive. ;AN000;
.IF <CS:COPY_BUF0 NE ZERO> ; do likewise to PRN if this ;AN000;
PUSH BX ; is lpt1. ;AN000;
MOV BX,CS:COPY_BUF0 ; ;AN000;
CALL FIND_ACTIVE_CP ; ;AN000;
POP BX ; ;AN000;
.ENDIF ; ;AN000;
CLC ; ;AN000;
.ENDIF ; ;AN000;
MOV CS:[BX].SAVED_CP,UNDEFINED; reset the saved cp ;AN000;
.ENDIF ; ;AN000;
RET ;AN000;
UNLOCK_CP ENDP ;AN000;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; PROCEDURE_NAME: LOCK_CP
;
; FUNCTION:
; THIS FUNCTION LOCKS THE DEVICE WITH THE CODE PAGE REQUESTED.
;
; AT ENTRY: BP - REQUESTED CODE PAGE
; BX - POINTS TO LPTx BUFFER
;
;
; AT EXIT:
; NORMAL: CARRY CLEAR - DEVICE LOCKED.
;
; ERROR: CARRY SET - ERROR, CODE PAGE NOT LOCKED.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LOCK_CP PROC NEAR ;AN000;
.IF <CS:[BX].STATE EQ LOCKED> ; if this was previously locked.. ;AN000;
MOV CS:PREV_LOCK,ON ; then...set flag and... ;AN000;
MOV CS:[BX].STATE,CPSW ; change to unlock for this proc ;AN000;
.ELSEIF <CS:[BX].STATE EQ CPSW> ; if this is unlocked... ;AN000;
MOV CS:PREV_LOCK,OFF ; then set flag off. ;AN000;
.ELSE ; ;AN000;
STC ; neither...set error ;AN000;
.ENDIF ; ;AN000;
.IF NC ; ;AN000;
CALL CHECK_FOR_CP ; yes..see if req cp is available. ;AN000;
.IF NC ; yes... ;AN000;
XOR AX,AX ; ;AN000;
CALL FIND_ACTIVE_CP ; find the active code page ;AN000;
.IF <BP NE DX> ; is it the same as requested?.. ;AN000;
MOV CS:REQ_CP,BP ; no..invoke the requested cp ;AN000;
PUSH CS ; ;AN000;
POP ES ; ;AN000;
LEA DI,INVOKE_BLOCK ; ;AN000;
MOV CS:[BX].RH_PTRO,DI ; ;AN000;
MOV CS:[BX].RH_PTRS,ES ; ;AN000;
PUSH DX ; ;AN000;
CALL INVOKE ; ;AN000;
POP DX ; ;AN000;
.IF <AL NE ZERO> ; error on invoke? ;AN000;
STC ; yes...set error flag. ;AN000;
.ELSE ; ;AN000;
MOV CS:[BX].STATE,LOCKED ; no, 'lock' the printer device ;AN000;
.IF <CS:PREV_LOCK EQ OFF> ; if we were not locked.. ;AN000;
MOV CS:[BX].SAVED_CP,DX ; and..save the old code page. ;AN000;
.ENDIF ; ;AN000;
CLC ; clear error flag. ;AN000;
.ENDIF ; ;AN000;
.ELSE ; ;AN000;
MOV CS:[BX].STATE,LOCKED ; 'lock' the printer device ;AN000;
.IF <CS:PREV_LOCK EQ OFF> ; if we were not locked.. ;AN000;
MOV CS:[BX].SAVED_CP,DX ; and..save the old code page. ;AN000;
.ENDIF ; ;AN000;
CLC ; clear the error flag ;AN000;
.ENDIF ; ;AN000;
.ENDIF ; ;AN000;
.ENDIF ; ;AN000;
RET ;AN000;
LOCK_CP ENDP ;AN000;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; PROCEDURE_NAME: CHECK_FOR_CP
;
; FUNCTION:
; THIS FUNCTION SEARCHES FOR THE CODE PAGE REQUESTED TO SEE IF IT HAS
; BEEN PREPARED OR IS A HARDWARE CODE PAGE
;
;
; AT ENTRY: BP = CODE PAGE REQUESTED
; BX - POINTS TO LPTx BUFFER
;
;
; AT EXIT:
; NORMAL: CARRY CLEAR - CODE PAGE IS VALID.
;
; ERROR: CARRY SET - CODE PAGE NOT AVAILABLE.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CHECK_FOR_CP PROC NEAR ;AN000;
PUSH DX ;AN000;
MOV DX,NOT_FOUND ; initialize flag ;AN000;
MOV CX,CS:[BX].RSLMX ; load number of RAM slots ;AN000;
MOV DI,CS:[BX].RAMSO ; load DI with table offset ;AN000;
.WHILE <DX EQ NOT_FOUND> AND ; whil not found and.... ;AN000;
.WHILE <CX NE ZERO> ; while still slots to check.. ;AN000;
.IF <CS:[DI].SLT_CP EQ BP> ; is it this one?? ;AN000;
MOV DX,FOUND ; yes....set flag ;AN000;
.ELSE ; ;AN000;
ADD DI,TYPE SLTS ; no..point to next entry ;AN000;
DEC CX ; decrement the count ;AN000;
.ENDIF ; ;AN000;
.ENDWHILE ; ;AN000;
.IF <DX EQ NOT_FOUND> ; if we didn't find it then.. ;AN000;
MOV CX,CS:[BX].HSLMX ; check hardware ;AN000;
MOV DI,CS:[BX].HARDSO ; load regs as before. ;AN000;
.WHILE <DX EQ NOT_FOUND> AND ; while not found and.. ;AN000;
.WHILE <CX NE ZERO> ; still have slots to check.. ;AN000;
.IF <CS:[DI].SLT_CP EQ BP> ; is it this one? ;AN000;
MOV DX,FOUND ; yes...set flag. ;AN000;
.ELSE ; ;AN000;
ADD DI,TYPE SLTS ; no ..point to next entry ;AN000;
DEC CX ; and decrement count. ;AN000;
.ENDIF ; ;AN000;
.ENDWHILE ; ;AN000;
.ENDIF ; ;AN000;
.IF <DX EQ NOT_FOUND> ; ;AN000;
STC ; set flag appropriately ;AN000;
.ELSE ; ;AN000;
CLC ; ;AN000;
.ENDIF ; ;AN000;
POP DX ; ;AN000;
RET ; ;AN000;
CHECK_FOR_CP ENDP ;AN000;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; PROCEDURE_NAME: FIND_ACTIVE_CP
;
; FUNCTION:
; THIS FUNCTION SEARCHES FOR THE ACTIVE CODE PAGE. IF REQUESTED, THE
; CODE PAGE IS MADE INACTIVE.
;
;
; AT ENTRY:
; BX - POINTS TO LPTx BUFFER
; AX = 0 - LEAVE AS ACTIVE
; AX = 1 - DE-ACTIVATE
;
;
; AT EXIT:
; NORMAL: DX - ACTIVE CODE PAGE. (NO ACTIVE = -1)
;
; ERROR: N/A
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
FIND_ACTIVE_CP PROC NEAR ;AN000;
MOV DX,UNDEFINED ; initialize register ;AN000;
MOV CX,CS:[BX].RSLMX ; load number of RAM slots ;AN000;
MOV DI,CS:[BX].RAMSO ; load DI with table offset ;AN000;
.WHILE <DX EQ UNDEFINED> AND ; whil not found and.... ;AN000;
.WHILE <CX NE ZERO> ; while still slots to check.. ;AN000;
.IF <BIT CS:[DI].SLT_AT AND AT_ACT> ; is it this one?? ;AN000;
MOV DX,CS:[DI].SLT_CP ; yes....load value ;AN000;
.IF <AX EQ ONE> ; is deactivate requested? ;AN000;
MOV CS:[DI].SLT_AT,AT_OCC; yes...change attrib. to occupied ;AN000;
.ENDIF ; ;AN000;
.ELSE ; ;AN000;
ADD DI,TYPE SLTS ; no..point to next entry ;AN000;
DEC CX ; decrement the count ;AN000;
.ENDIF ; ;AN000;
.ENDWHILE ; ;AN000;
.IF <DX EQ UNDEFINED> ; if we didn't find it then.. ;AN000;
MOV CX,CS:[BX].HSLMX ; check hardware ;AN000;
MOV DI,CS:[BX].HARDSO ; load regs as before. ;AN000;
.WHILE <DX EQ UNDEFINED> AND ; while not found and.. ;AN000;
.WHILE <CX NE ZERO> ; still have slots to check.. ;AN000;
.IF <BIT CS:[DI].SLT_AT AND AT_ACT> ; is it this one?? ;AN000;
MOV DX,CS:[DI].SLT_CP ; yes....load value ;AN000;
.IF <AX EQ ONE> ; is deactivate requested? ;AN000;
MOV CS:[DI].SLT_AT,AT_OCC; yes...change attrib to occupied;AN000;
.ENDIF ; ;AN000;
.ELSE ; ;AN000;
ADD DI,TYPE SLTS ; no ..point to next entry ;AN000;
DEC CX ; and decrement count. ;AN000;
.ENDIF ; ;AN000;
.ENDWHILE ; ;AN000;
.ENDIF ; ;AN000;
RET ; ;AN000;
FIND_ACTIVE_CP ENDP ;AN000;
CSEG ENDS
END
|
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string>
#include "modules/include/module_common_types.h"
#include "modules/rtp_rtcp/source/rtp_format_video_generic.h"
#include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
#include "rtc_base/logging.h"
namespace webrtc {
static const size_t kGenericHeaderLength = 1;
static const size_t kExtendedHeaderLength = 2;
RtpPacketizerGeneric::RtpPacketizerGeneric(
const RTPVideoHeader& rtp_video_header,
FrameType frame_type,
size_t max_payload_len,
size_t last_packet_reduction_len)
: picture_id_(rtp_video_header.generic
? absl::optional<uint16_t>(
rtp_video_header.generic->frame_id & 0x7FFF)
: absl::nullopt),
payload_data_(nullptr),
payload_size_(0),
max_payload_len_(max_payload_len - kGenericHeaderLength -
(picture_id_.has_value() ? kExtendedHeaderLength : 0)),
last_packet_reduction_len_(last_packet_reduction_len),
frame_type_(frame_type),
num_packets_left_(0),
num_larger_packets_(0) {}
RtpPacketizerGeneric::~RtpPacketizerGeneric() {}
size_t RtpPacketizerGeneric::SetPayloadData(
const uint8_t* payload_data,
size_t payload_size,
const RTPFragmentationHeader* fragmentation) {
payload_data_ = payload_data;
payload_size_ = payload_size;
// Fragment packets such that they are almost the same size, even accounting
// for larger header in the last packet.
// Since we are given how much extra space is occupied by the longer header
// in the last packet, we can pretend that RTP headers are the same, but
// there's last_packet_reduction_len_ virtual payload, to be put at the end of
// the last packet.
//
size_t total_bytes = payload_size_ + last_packet_reduction_len_;
// Minimum needed number of packets to fit payload and virtual payload in the
// last packet.
num_packets_left_ = (total_bytes + max_payload_len_ - 1) / max_payload_len_;
// Given number of packets, calculate average size rounded down.
payload_len_per_packet_ = total_bytes / num_packets_left_;
// If we can't divide everything perfectly evenly, we put 1 extra byte in some
// last packets: 14 bytes in 4 packets would be split as 3+3+4+4.
num_larger_packets_ = total_bytes % num_packets_left_;
RTC_DCHECK_LE(payload_len_per_packet_, max_payload_len_);
generic_header_ = RtpFormatVideoGeneric::kFirstPacketBit;
if (frame_type_ == kVideoFrameKey) {
generic_header_ |= RtpFormatVideoGeneric::kKeyFrameBit;
}
if (picture_id_.has_value()) {
generic_header_ |= RtpFormatVideoGeneric::kExtendedHeaderBit;
}
return num_packets_left_;
}
bool RtpPacketizerGeneric::NextPacket(RtpPacketToSend* packet) {
RTC_DCHECK(packet);
if (num_packets_left_ == 0)
return false;
// Last larger_packets_ packets are 1 byte larger than previous packets.
// Increase per packet payload once needed.
if (num_packets_left_ == num_larger_packets_)
++payload_len_per_packet_;
size_t next_packet_payload_len = payload_len_per_packet_;
if (payload_size_ <= next_packet_payload_len) {
// Whole payload fits into this packet.
next_packet_payload_len = payload_size_;
if (num_packets_left_ == 2) {
// This is the penultimate packet. Leave at least 1 payload byte for the
// last packet.
--next_packet_payload_len;
RTC_DCHECK_GT(next_packet_payload_len, 0);
}
}
RTC_DCHECK_LE(next_packet_payload_len, max_payload_len_);
size_t total_length = next_packet_payload_len + kGenericHeaderLength +
(picture_id_.has_value() ? kExtendedHeaderLength : 0);
uint8_t* out_ptr = packet->AllocatePayload(total_length);
// Put generic header in packet.
out_ptr[0] = generic_header_;
out_ptr += kGenericHeaderLength;
if (picture_id_.has_value()) {
WriteExtendedHeader(out_ptr);
out_ptr += kExtendedHeaderLength;
}
// Remove first-packet bit, following packets are intermediate.
generic_header_ &= ~RtpFormatVideoGeneric::kFirstPacketBit;
// Put payload in packet.
memcpy(out_ptr, payload_data_, next_packet_payload_len);
payload_data_ += next_packet_payload_len;
payload_size_ -= next_packet_payload_len;
--num_packets_left_;
// Packets left to produce and data left to split should end at the same time.
RTC_DCHECK_EQ(num_packets_left_ == 0, payload_size_ == 0);
packet->SetMarker(payload_size_ == 0);
return true;
}
std::string RtpPacketizerGeneric::ToString() {
return "RtpPacketizerGeneric";
}
void RtpPacketizerGeneric::WriteExtendedHeader(uint8_t* out_ptr) {
// Store bottom 15 bits of the the sequence number. Only 15 bits are used for
// compatibility with other packetizer implemenetations that also use 15 bits.
out_ptr[0] = (*picture_id_ >> 8) & 0x7F;
out_ptr[1] = *picture_id_ & 0xFF;
}
RtpDepacketizerGeneric::~RtpDepacketizerGeneric() = default;
bool RtpDepacketizerGeneric::Parse(ParsedPayload* parsed_payload,
const uint8_t* payload_data,
size_t payload_data_length) {
assert(parsed_payload != NULL);
if (payload_data_length == 0) {
RTC_LOG(LS_WARNING) << "Empty payload.";
return false;
}
uint8_t generic_header = *payload_data++;
--payload_data_length;
parsed_payload->frame_type =
((generic_header & RtpFormatVideoGeneric::kKeyFrameBit) != 0)
? kVideoFrameKey
: kVideoFrameDelta;
parsed_payload->video_header().is_first_packet_in_frame =
(generic_header & RtpFormatVideoGeneric::kFirstPacketBit) != 0;
parsed_payload->video_header().codec = kVideoCodecGeneric;
parsed_payload->video_header().width = 0;
parsed_payload->video_header().height = 0;
if (generic_header & RtpFormatVideoGeneric::kExtendedHeaderBit) {
if (payload_data_length < kExtendedHeaderLength) {
RTC_LOG(LS_WARNING) << "Too short payload for generic header.";
return false;
}
parsed_payload->video_header().generic.emplace();
parsed_payload->video_header().generic->frame_id =
((payload_data[0] & 0x7F) << 8) | payload_data[1];
payload_data += kExtendedHeaderLength;
payload_data_length -= kExtendedHeaderLength;
}
parsed_payload->payload = payload_data;
parsed_payload->payload_length = payload_data_length;
return true;
}
} // namespace webrtc
|
#include "Master.h"
#include "misc.h"
#include <algorithm>
#include <math.h>
#include <functional>
#include <random>
Master::Master(string filename, string alg){
isValidExecutions = 0;
algorithm = alg;
sat_solver = "default";
if(ends_with(filename, "smt2")){
#ifdef NOSMT
print_err("Working with SMT is currently not enabled. To enable it, run 'make cleanCore; make USESMT=YES'. For more info, see README.md.");
#else
satSolver = new Z3Handle(filename);
#endif
domain = "smt";
}
else if(ends_with(filename, "cnf")){
satSolver = new MSHandle(filename);
domain = "sat";
}
else if(ends_with(filename, "ltl")){
#ifdef NOLTL
print_err("Working with LTL is currently not enabled. To enable it, run 'make cleanCore; make USELTL=YES'. For more info, see README.md.");
#else
if(sat_solver == "nuxmv")
satSolver = new NuxmvHandle(filename);
else
satSolver = new SpotHandle(filename);
#endif
domain = "ltl";
}
else
print_err("The input file has to have one of these extensions: .smt2, .ltl, or .cnf. See example files in ./examples/ folder.");
dimension = satSolver->dimension;
cout << "Number of constraints in the input set:" << dimension << endl;
explorer = new Explorer(dimension);
explorer->satSolver = satSolver;
verbose = false;
depthMUS = 0;
dim_reduction = 0.5;
output_file = "";
validate_mus_c = false;
current_depth = 0;
unex_sat = unex_unsat = 0;
hash = random_number();
satSolver->hash = hash;
}
Master::~Master(){
delete satSolver;
delete explorer;
}
void Master::write_mus_to_file(MUS& f){
satSolver->exportMUS(f.bool_mus, output_file);
}
// mark formula and all of its supersets as explored
void Master::block_up(MUS& formula){
explorer->block_up(formula);
}
// mark formula and all of its subsets as explored
void Master::block_down(Formula formula){
explorer->block_down(formula);
}
// check formula for satisfiability
// core and grow controls optional extraction of unsat core and model extension (replaces formula)
bool Master::is_valid(Formula &formula, bool core, bool grow){
bool sat = satSolver->solve(formula, core, grow);
if(sat) unex_sat++;
else unex_unsat++;
return sat;
}
//verify if f is a MUS
void Master::validate_mus(Formula &f){
if(is_valid(f))
print_err("the mus is SAT");
if(!explorer->isUnexplored(f))
print_err("this mus has been already explored");
for(int l = 0; l < f.size(); l++)
if(f[l]){
f[l] = false;
if(!is_valid(f))
print_err("the mus has an unsat subset");
f[l] = true;
}
}
MUS& Master::shrink_formula(Formula &f, Formula crits){
int f_size = count_ones(f);
chrono::high_resolution_clock::time_point start_time = chrono::high_resolution_clock::now();
if(verbose) cout << "shrinking dimension: " << f_size << endl;
f_size = count_ones(f);
if(crits.empty()) crits = explorer->critical;
if(get_implies){ //get the list of known critical constraints
explorer->getImplied(crits, f);
if(verbose) cout << "# of known critical constraints before shrinking: " << count_ones(crits) << endl;
if(criticals_rotation && domain == "sat"){
int before = count_ones(crits);
MSHandle *msSolver = static_cast<MSHandle*>(satSolver);
msSolver->criticals_rotation(crits, f);
if(verbose) cout << "# of found critical constraints by criticals rotation: " << (count_ones(crits) - before) << endl;
}
float c_crits = count_ones(crits);
if(int(c_crits) == f_size){ // each constraint in f is critical for f, i.e. it is a MUS
muses.push_back(MUS(f, -1, muses.size(), f_size)); //-1 duration means skipped shrink
return muses.back();
}
if(!is_valid(crits, false, false)){
muses.push_back(MUS(crits, -1, muses.size(), f_size));//-1 duration means skipped shrink
return muses.back();
}
}
Formula mus = satSolver->shrink(f, crits);
chrono::high_resolution_clock::time_point end_time = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>( end_time - start_time ).count() / float(1000000);
muses.push_back(MUS(mus, duration, muses.size(), f_size));
return muses.back();
}
//grow formula into a MSS
Formula Master::grow_formula(Formula &f){
return satSolver->grow(f);
}
void Master::mark_MUS(MUS& f, bool block_unex){
if(validate_mus_c) validate_mus(f.bool_mus);
explorer->block_up(f);
chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>( now - initial_time ).count() / float(1000000);
cout << "Found MUS #" << muses.size() << ", mus dimension: " << f.dimension;
cout << ", checks: " << satSolver->checks << ", time: " << duration;
cout << ", unex sat: " << unex_sat << ", unex unsat: " << unex_unsat << ", criticals: " << explorer->criticals;
cout << ", intersections: " << std::count(explorer->mus_intersection.begin(), explorer->mus_intersection.end(), true);
cout << ", union: " << std::count(explorer->mus_union.begin(), explorer->mus_union.end(), true) << ", dimension: " << dimension;
cout << ", seed dimension: " << f.seed_dimension << ", shrink duration: " << f.duration;
cout << ", shrinks: " << satSolver->shrinks;
cout << endl;
if(output_file != "")
write_mus_to_file(f);
}
void Master::enumerate(){
initial_time = chrono::high_resolution_clock::now();
cout << "running algorithm: " << algorithm << endl;
Formula whole(dimension, true);
if(is_valid(whole))
print_err("the input instance is satisfiable");
if(algorithm == "remus"){
find_all_muses_duality_based_remus(Formula (dimension, true), Formula (dimension, false), 0);
}
else if(algorithm == "tome"){
find_all_muses_tome();
}
else if(algorithm == "marco"){
marco_base();
}
return;
}
|
.code
syscall_handler proc
mov r10, rcx
mov eax, 000h ; syscall number will be dynamically set by syscall::setup
syscall
ret
syscall_handler endp
end
|
; A040837: Continued fraction for sqrt(867).
; 29,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4,29,4,2,58,2,4
seq $0,10144 ; Continued fraction for sqrt(59).
seq $0,90771 ; Numbers that are congruent to {1, 9} mod 10.
add $0,1
mul $0,3
add $1,$0
mul $1,4
sub $1,5
div $1,15
sub $1,6
lpb $0
div $0,11
add $0,$1
add $1,1
lpe
|
#ifndef SIMULATION_H
#define SIMULATION_H
#include <list>
#include <map>
#include "topology/topology.hpp"
#include "simulation/event.hpp"
#include "utils/pktdumper.hpp"
#include "traffic/triggerGenerator.hpp"
#include "traffic/incastGenerator.hpp"
typedef struct Simulation
{
std::shared_ptr<Topology> topo;
// time-related. All units are nanoseconds
sim_time_t currTime;
sim_time_t timeIncrement;
sim_time_t totalTime;
// packets-related
pkt_id_t nextPktId;
pkt_id_t nextTriggerPktId;
pkt_id_t totalPktsDelivered;
std::multimap<sim_time_t, HostPktEvent> HostPktEventList;
std::list<pktevent_p<normalpkt_p>> NormalPktEventList;
std::list<pktevent_p<normalpkt_p>> freeNormalPktEvents; // to reuse shared_ptrs
std::list<pktevent_p<triggerpkt_p>> TriggerPktEventList;
std::list<normalpkt_p> freeNormalPkts;
// For tracking and logging triggerInfo
std::map<trigger_id_t, triggerInfo> TriggerInfoMap;
std::shared_ptr<TriggerGenerator> triggerGen;
std::shared_ptr<IncastGenerator> incastGen;
std::unique_ptr<PktDumper> pktDumper;
time_t startTime, endTime;
Simulation(); // default constructor
// needs to be thread-safe when parallelizing
inline pkt_id_t getNextPktId() { return this->nextPktId++; };
inline pkt_id_t getNextTriggerPktId() { return this->nextTriggerPktId++; };
inline void buildTopo(){ this->topo->buildTopo(); };
pktevent_p<normalpkt_p> getNewNormalPktEvent();
normalpkt_p getNewNormalPkt(pkt_id_t pktId, pkt_size_t pktSize);
void initTriggerGen();
void initIncastGen();
void initHosts();
void generateHostPktEvents();
void processHostPktEvents();
void processTriggerPktEvents();
void processNormalPktEvents();
void flushRemainingNormalPkts();
void logTriggerInfoMap();
void showLinkUtilizations();
void printSimulationSetup();
void printSimulationStats();
void cleanUp();
} Simulation;
extern Simulation syndbSim;
#endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r14
push %r9
push %rbp
push %rdx
push %rsi
lea addresses_A_ht+0x1cbd9, %rdx
dec %rsi
mov $0x6162636465666768, %rbp
movq %rbp, %xmm5
vmovups %ymm5, (%rdx)
nop
add $53958, %rsi
lea addresses_WC_ht+0x119b5, %r14
nop
nop
nop
nop
add $5223, %r10
mov $0x6162636465666768, %r9
movq %r9, (%r14)
and $47184, %r10
lea addresses_WC_ht+0x1c5b5, %rdx
nop
nop
nop
nop
sub %r12, %r12
and $0xffffffffffffffc0, %rdx
vmovntdqa (%rdx), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $1, %xmm7, %r9
nop
nop
nop
nop
nop
xor $61782, %rbp
lea addresses_A_ht+0x52f5, %r14
add $62262, %r9
vmovups (%r14), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $0, %xmm1, %r12
nop
nop
nop
nop
nop
sub %r10, %r10
pop %rsi
pop %rdx
pop %rbp
pop %r9
pop %r14
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r15
push %r9
push %rbp
push %rbx
push %rcx
// Faulty Load
lea addresses_PSE+0x65b5, %rbp
nop
nop
nop
and $24948, %r9
mov (%rbp), %rcx
lea oracles, %r9
and $0xff, %rcx
shlq $12, %rcx
mov (%r9,%rcx,1), %rcx
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r15
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 10}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 11}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
copyright zengfr site:http://github.com/zengfr/romhack
000F80 move.w D6, D5 [base+290, base+2B0, base+2D0]
000F8C lea (-$b28,A5), A4 [base+290, base+2B0, base+2D0]
0029B6 move.w D1, ($8,A4)
0029BA lea (-$20,A4), A4
002ACE cmp.w ($8,A4), D0 [base+28E, base+2AE, base+2CE]
002AD2 beq $2adc [base+290, base+2B0, base+2D0]
002B84 cmp.w ($8,A4), D0 [base+28E, base+2AE, base+2CE]
002B88 beq $2b74 [base+290, base+2B0, base+2D0]
002DE0 cmp.w ($8,A4), D0 [base+28E, base+2AE, base+2CE]
002DE4 beq $2df4 [base+290, base+2B0, base+2D0]
01A74C dbra D7, $1a74a
copyright zengfr site:http://github.com/zengfr/romhack
|
; A262480: Number of trivial c-Wilf equivalence classes in the symmetric group S_n.
; Submitted by Jon Maiga
; 1,1,1,2,8,32,192,1272,10176,90816,908160,9980160,119761920,1556766720,21794734080,326918753280,5230700052480,88921859604480,1600593472880640,30411275148656640,608225502973132800,12772735543856332800,281000181964839321600,6463004184741681561600,155112100433800357478400,3877802510833236993638400
mov $1,1
mov $2,1
lpb $0
mul $1,$0
add $3,$0
sub $0,2
sub $3,1
mul $2,$3
trn $3,$1
lpe
add $1,1
div $1,2
add $2,1
div $2,2
mul $2,$1
mov $0,$2
|
;
; C128 pseudo graphics routines
; Version for the 2x3 graphics symbols (UDG redefined)
;
;
; Written by Stefano Bodrato 2020
;
;
; Reset pixel at (x,y) coordinate.
;
;
; $Id: respixl.asm $
;
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC respixel
EXTERN div3_0
EXTERN __gfx_coords
EXTERN base_graphics
.respixel
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
dec a
ld (__gfx_coords),hl
push bc
ld c,a ; y
ld b,h ; x
push bc
ld hl,div3_0
ld d,0
ld e,c
inc e
add hl,de
ld a,(hl)
; ld c,a ; y/3
srl b ; x/2
; ld a,c
ld c,b ; !!
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
ld hl,(base_graphics)
ld b,a ; keep y/3
and a
ld de,maxx/2
;dec a
jr z,r_zero
.r_loop
add hl,de
dec a
jr nz,r_loop
.r_zero ;ld d,0
ld e,c
add hl,de
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
ld a,(hl) ; get current symbol from screen
ld e,a ; ..and its copy
ex (sp),hl ; save char address <=> restore x,y (y=h, x=l)
ld a,l
inc a
inc a
sub b
sub b
sub b ; we get the remainder of y/3
ld l,a
ld a,1 ; the pixel we want to draw
jr z,iszero
bit 0,l
jr nz,is1
add a,a
add a,a
.is1
add a,a
add a,a
.iszero
bit 0,h
jr nz,evenrow
add a,a ; move down the bit
.evenrow
cpl
and e
pop hl
ld (hl),a
pop bc
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r15
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x1442, %rsi
lea addresses_WC_ht+0x1ec52, %rdi
nop
add $63703, %r13
mov $30, %rcx
rep movsq
nop
nop
nop
nop
nop
sub $19263, %rbx
lea addresses_A_ht+0xd4f2, %r13
nop
nop
sub $49135, %r12
movups (%r13), %xmm3
vpextrq $1, %xmm3, %rcx
nop
sub %rdi, %rdi
lea addresses_A_ht+0x6af2, %rcx
nop
nop
sub $29956, %r9
movups (%rcx), %xmm3
vpextrq $0, %xmm3, %rsi
nop
nop
nop
nop
nop
and $1965, %r13
lea addresses_UC_ht+0x7ef2, %rdi
nop
nop
nop
nop
xor %r12, %r12
mov (%rdi), %rbx
nop
nop
nop
nop
nop
add $64825, %rdi
lea addresses_D_ht+0xa892, %r12
and %rdi, %rdi
mov $0x6162636465666768, %rbx
movq %rbx, %xmm4
movups %xmm4, (%r12)
nop
sub $54285, %r9
lea addresses_normal_ht+0xfef2, %rsi
lea addresses_A_ht+0x182f2, %rdi
add %r15, %r15
mov $67, %rcx
rep movsq
nop
nop
nop
dec %r13
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r15
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r15
push %r9
push %rbx
push %rdi
push %rdx
// Faulty Load
mov $0x39848700000002f2, %r9
nop
nop
xor $8830, %rdi
mov (%r9), %bx
lea oracles, %rdi
and $0xff, %rbx
shlq $12, %rbx
mov (%rdi,%rbx,1), %rbx
pop %rdx
pop %rdi
pop %rbx
pop %r9
pop %r15
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': True, 'congruent': 10}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 3}}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A020873: a(n) = number of cycles in Moebius ladder M_n.
; 2,3,7,15,29,53,95,171,313,585,1115,2159,4229,8349,16567,32979,65777,131345,262451,524631,1048957,2097573,4194767,8389115,16777769,33555033,67109515,134218431,268436213,536871725,1073742695,2147484579,4294968289,8589935649,17179870307,34359739559,68719477997,137438954805,274877908351,549755815371,1099511629337,2199023257193,4398046512827,8796093024015,17592186046309,35184372090813,70368744179735,140737488357491,281474976712913,562949953423665,1125899906845075,2251799813687799,4503599627373149,9007199254743749
mov $1,2
mov $2,1
mov $4,$0
lpb $0
sub $0,1
add $1,$4
mov $3,$2
mul $2,2
add $4,$3
lpe
|
dnl AMD K6 mpn_divrem_1 -- mpn by limb division.
dnl Copyright 1999, 2000, 2001, 2002, 2003, 2007 Free Software Foundation,
dnl Inc.
dnl
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU Lesser General Public License as
dnl published by the Free Software Foundation; either version 3 of the
dnl License, or (at your option) any later version.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
dnl Lesser General Public License for more details.
dnl
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C K6: 20 cycles/limb
C mp_limb_t mpn_divrem_1 (mp_ptr dst, mp_size_t xsize,
C mp_srcptr src, mp_size_t size, mp_limb_t divisor);
C mp_limb_t mpn_divrem_1c (mp_ptr dst, mp_size_t xsize,
C mp_srcptr src, mp_size_t size, mp_limb_t divisor,
C mp_limb_t carry);
C
C The code here is basically the same as mpn/x86/divrem_1.asm, but uses loop
C instead of decl+jnz, since it comes out 2 cycles/limb faster.
C
C A test is done to see if the high limb is less than the divisor, and if so
C one less div is done. A div is 20 cycles, so assuming high<divisor about
C half the time, then this test saves half that amount. The branch
C misprediction penalty is less than that.
C
C Back-to-back div instructions run at 20 cycles, the same as the loop here,
C so it seems there's nothing to gain by rearranging the loop. Pairing the
C mov and loop instructions was found to gain nothing.
C
C Enhancements:
C
C The low-latency K6 multiply might be thought to suit a mul-by-inverse, but
C that algorithm has been found to suffer from the relatively poor carry
C handling on K6 and too many auxiliary instructions. The fractional part
C however could be done at about 13 c/l, if it mattered enough.
defframe(PARAM_CARRY, 24)
defframe(PARAM_DIVISOR,20)
defframe(PARAM_SIZE, 16)
defframe(PARAM_SRC, 12)
defframe(PARAM_XSIZE, 8)
defframe(PARAM_DST, 4)
TEXT
ALIGN(32)
PROLOGUE(mpn_divrem_1c)
deflit(`FRAME',0)
movl PARAM_SIZE, %ecx
pushl %edi FRAME_pushl()
movl PARAM_SRC, %edi
pushl %esi FRAME_pushl()
movl PARAM_DIVISOR, %esi
pushl %ebx FRAME_pushl()
movl PARAM_DST, %ebx
pushl %ebp FRAME_pushl()
movl PARAM_XSIZE, %ebp
orl %ecx, %ecx C size
movl PARAM_CARRY, %edx
jz L(fraction) C if size==0
leal -4(%ebx,%ebp,4), %ebx C dst one limb below integer part
jmp L(integer_top)
EPILOGUE()
ALIGN(16)
PROLOGUE(mpn_divrem_1)
deflit(`FRAME',0)
movl PARAM_SIZE, %ecx
pushl %edi FRAME_pushl()
movl PARAM_SRC, %edi
pushl %esi FRAME_pushl()
movl PARAM_DIVISOR, %esi
orl %ecx,%ecx C size
jz L(size_zero)
pushl %ebx FRAME_pushl()
movl -4(%edi,%ecx,4), %eax C src high limb
xorl %edx, %edx
movl PARAM_DST, %ebx
pushl %ebp FRAME_pushl()
movl PARAM_XSIZE, %ebp
cmpl %esi, %eax
leal -4(%ebx,%ebp,4), %ebx C dst one limb below integer part
jae L(integer_entry)
C high<divisor, so high of dst is zero, and avoid one div
movl %edx, (%ebx,%ecx,4)
decl %ecx
movl %eax, %edx
jz L(fraction)
L(integer_top):
C eax scratch (quotient)
C ebx dst+4*xsize-4
C ecx counter
C edx scratch (remainder)
C esi divisor
C edi src
C ebp xsize
movl -4(%edi,%ecx,4), %eax
L(integer_entry):
divl %esi
movl %eax, (%ebx,%ecx,4)
loop L(integer_top)
L(fraction):
orl %ebp, %ecx
jz L(done)
movl PARAM_DST, %ebx
L(fraction_top):
C eax scratch (quotient)
C ebx dst
C ecx counter
C edx scratch (remainder)
C esi divisor
C edi
C ebp
xorl %eax, %eax
divl %esi
movl %eax, -4(%ebx,%ecx,4)
loop L(fraction_top)
L(done):
popl %ebp
movl %edx, %eax
popl %ebx
popl %esi
popl %edi
ret
L(size_zero):
deflit(`FRAME',8)
movl PARAM_XSIZE, %ecx
xorl %eax, %eax
movl PARAM_DST, %edi
cld C better safe than sorry, see mpn/x86/README
rep
stosl
popl %esi
popl %edi
ret
EPILOGUE()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.