//除法优化示例,这里edi为无符号整数edi = edi /3//优化后编译成汇编 即 edi = (edi * 0xaaaaaaab) >> 33mov eax, edi ; eax = edimov edi,2863311531 ; edi =0xaaaaaaabimul rax, rdi ; rax = rax *0xaaaaaaabshr rax,33 ; rax >>=33
2.有符号除法优化
//除法优化示例,这里edi为有符号整数edi = edi /2;//优化后编译成汇编 即 edi = (edi + (edi >> 33)) >> 1//其中所有的右移都为有符号右移mov eax, edi ; eax = edishr eax,31 ; eax = eax >>31add eax, edi ; eax = eax + edisar eax ; eax = eax >>1
3.无符号取余优化
//取余优化示例,这里edi为无符号整数edi %3==0//优化后编译成汇编imul edi, edi,-1431655765 ; edi = edi *0xaaaaaaabcmp edi,1431655765 ; compare with 0x55555555setbe al ; return1if edi <=0x55555555
-V =>V*-1V+-W==>V-W((V+ c) + d) =>V+ (c+d)((V* c) * d) =>V* (c*d)((V+ (W+ c)) + d) => (W+ (c+d)) +VV+0xff...=>V-0x00...(V<<W) & d => (V& (W>> c)) << c(V& c) & d =>V& (c & d)(V>>X) | (W >> X) => (V|W) >>X!!V =>V!(V==W) =>V!=W!(V<W) =>W<=V!(V<=W) =>W<V!(V!=W) =>V==WV^^ W =>V!=WV* c +V* d =>V* (c + d)sub( (zext(V)*c)>>n,0) =>V/ (2^n/(c-1))sub( (sext(V)*c)s>>n,0) =>V s/ (2^n/(c-1))sub(ext(V)*c,b)>>d +V->sub( (ext(V)*(c+2^n))>>n,0)W+((V-W)>>1) =>sub( (zext(V)*(c+2^n))>>(n+1),0)(V<< c) << d =>V<< (c+d)(V<< c) >> c =>V&0xffsub( concat(V,W),0) =>Wsub( concat(V,W), c) =>Vsub( concat(V,W), c) =>sub(V,c)V*-1== c =>V==-cV+ c == d =>V== (d-c)~V== c =>V==~c((V+ c) +W) &0xfff0=> (V+ (c &0xfff0)) +W