Tải bản đầy đủ - 0 (trang)
6 " Medium Level " Control Structures: JT and JF

6 " Medium Level " Control Structures: JT and JF

Tải bản đầy đủ - 0trang

7.7ImplementingCommonControlStructuresin

AssemblyLanguage

Becauseaprimarygoalofthischapteristoteachyouhowtousethelow

levelmachineinstructionstoimplementdecisions,loops,andother

controlconstructs,itwouldbewisetoshowyouhowtosimulatethese

highlevelstatementsusing"pure"assemblylanguage.Thefollowing

sectionsprovidethisinformation.



7.8IntroductiontoDecisions

Initsmostbasicform,adecisionissomesortofbranchwithinthecode

thatswitchesbetweentwopossibleexecutionpathsbasedonsome

condition.Normally(thoughnotalways),conditionalinstruction

sequencesareimplementedwiththeconditionaljumpinstructions.

Conditionalinstructionscorrespondtotheif..then..endifstatement

inHLA:

if(expression)then

<>

endif;

Assemblylanguage,asusual,offersmuchmoreflexibilitywhendealing

withconditionalstatements.ConsiderthefollowingC/C++statement:

if(((xt))||(a!=b))

stmt1;

A"bruteforce"approachtoconvertingthisstatementintoassembly

languagemightproduce:



mov(x,eax);

cmp(eax,y);

setl(bl);//StoreX
mov(z,eax);

cmp(eax,t);

setg(bh);//StoreZ>Tinbh.

and(bh,bl);//Put(XT)into

mov(a,eax);

cmp(eax,b);

setne(bh);//StoreA!=Bintobh.

or(bh,bl);//Put(XT)||(A

jeSkipStmt1;//Branchifresultisfals

//false).





SkipStmt1:

Asyoucansee,ittakesaconsiderablenumberofconditionalstatements

justtoprocesstheexpressionintheexampleabove.Thisroughly

correspondstothe(equivalent)C/C++statements:

bl=x
bh=z>t;

bl=bl&&bh;

bh=a!=b;

bl=bl||bh;

if(bl)

stmt1;

Nowcomparethiswiththefollowing"improved"code:

mov(a,eax);

cmp(eax,b);

jneDoStmt;

mov(x,eax);

cmp(eax,y);

jnlSkipStmt;

mov(z,eax);

cmp(eax,t);

jngSkipStmt;

DoStmt:

<>

SkipStmt:

Twothingsshouldbeapparentfromthecodesequencesabove:First,a

singleconditionalstatementinC/C++(orsomeotherHLL)mayrequire

severalconditionaljumpsinassemblylanguage;second,organizationof

complexexpressionsinaconditionalsequencecanaffecttheefficiency

ofthecode.Therefore,careshouldbeexercisedwhendealingwith

conditionalsequencesinassemblylanguage.

Conditionalstatementsmaybebrokendownintothreebasiccategories:

ifstatements,switch/casestatements,andindirectjumps.The

followingsectionswilldescribetheseprogramstructures,howtouse



them,andhowtowritetheminassemblylanguage.



7.8.1IF..THEN..ELSESequences

Themostcommonconditionalstatementistheif..thenor

if..then..elsestatement.Thesetwostatementstaketheform

showninFigure7-1.





Figure7-1:IF..THEN..ELSE..ENDIFandIF..ENDIFStatement

Flow.

Theif..endifstatementisjustaspecialcaseofthe

if..else..endifstatement(withanemptyelseblock).Therefore,

we'llonlyconsiderthemoregeneralif..else..endifform.Thebasic

implementationofanif..then..elsestatementin80x86assembly

languagelookssomethinglikethis:

{Sequenceofstatementstotestsomecondition}

JccElseCode

{SequenceofstatementscorrespondingtotheTHENblock}

jmpEndOfIF

ElseCode:



{SequenceofstatementscorrespondingtotheELSEblock}

EndOfIF:

Note Jccrepresentssomeconditionaljumpinstruction.

Forexample,toconverttheC/C++statement

if(a==b)

c=d;

else

b=b+1;

toassemblylanguage,youcouldusethefollowing80x86code:

mov(a,eax);

cmp(eax,b);

jneElsePart;

mov(d,c);

jmpEndOfIf;

ElseBlk:

inc(b);

EndOfIf:

Forsimpleexpressionslike"(a==b)"generatingthepropercodeforan

if..else..endifstatementisalmosttrivial.Shouldtheexpression

becomemorecomplex,theassociatedassemblylanguagecode

complexityincreasesaswell.ConsiderthefollowingC/C++ifstatement

presentedearlier:

if(((x>y)&&(z
c=d;

Whenprocessingcomplexifstatementssuchasthisone,you'llfindthe

conversiontaskeasierifyoubreakthisifstatementintoasequenceof

threedifferentifstatementsasfollows:

if(a!=b)C=D;

elseif(x>y)

if(z


C=D;

ThisconversioncomesfromthefollowingC/C++equivalences:

if(expr1&&expr2)stmt;

isequivalentto

if(expr1)if(expr2)stmt;

and

if(expr1||expr2)stmt;

isequivalentto

if(expr1)stmt;

elseif(expr2)stmt;

Inassemblylanguage,theformerifstatementbecomes:

//if(((x>y)&&(z
//c=d;

mov(a,eax);

cmp(eax,b);

jneDoIF;

mov(x,eax);

cmp(eax,y);

jngEndOfIF;

mov(z,eax);

cmp(eax,t);

jnlEndOfIf;

DoIf:

mov(d,c);

EndOfIF:

Asyoucanprobablytell,thecodenecessarytotestaconditioncan

easilybecomemorecomplexthanthestatementsappearingintheelse

andthenblocks.Althoughitseemssomewhatparadoxicalthatitmay

takemoreefforttotestaconditionthantoactupontheresultsofthat

condition,ithappensallthetime.Therefore,youshouldbepreparedto



acceptthis.

Probablythebiggestproblemwithcomplexconditionalstatementsin

assemblylanguageistryingtofigureoutwhatyou'vedoneafteryou've

writtenthecode.Abigadvantagehighlevellanguagesofferover

assemblylanguageisthatexpressionsaremucheasiertoreadand

comprehend.ThisisoneoftheprimaryreasonsHLAsupportshighlevel

controlstructures.Thehighlevelversionisself-documenting,whereas

assemblylanguagetendstohidethetruenatureofthecode.Therefore,

well-writtencommentsareanessentialingredienttoassemblylanguage

implementationsofif..then..elsestatements.Anelegant

implementationoftheexampleaboveis:

//IF((X>Y)&&(Z
//Implementedas:

//IF(A!=B)THENGOTODoIF;

mov(a,eax);

cmp(eax,b);

jneDoIF;

//ifNOT(X>Y)THENGOTOEndOfIF;

mov(x,eax);

cmp(eax,y);

jngEndOfIF;

//IFNOT(Z
mov(z,eax);

cmp(eax,t);

jnlEndOfIf;

//THENBlock:

DoIf:

mov(d,c);

//EndofIFstatement



EndOfIF:

Admittedly,thisappearstobegoingoverboardforsuchasimple

example.Thefollowingwouldprobablysuffice:

//if(((x>y)&&(z
//Testthebooleanexpression:

mov(a,eax);

cmp(eax,b);

jneDoIF;

mov(x,eax);

cmp(eax,y);

jngEndOfIF;

mov(z,eax);

cmp(eax,t);

jnlEndOfIf;

;THENBlock:

DoIf:

mov(d,c);

;EndofIFstatement

EndOfIF:

However,asyourifstatementsbecomecomplex,thedensity(and

quality)ofyourcommentsbecomemoreandmoreimportant.



7.8.2TranslatingHLAIFStatementsintoPureAssembly

Language

TranslatingHLAifstatementsintopureassemblylanguageisvery

easy.ThebooleanexpressionsthattheHLAifsupportswere

specificallychosentoexpandintoafewsimplemachineinstructions.The

followingparagraphsdiscusstheconversionofeachsupportedboolean



expressionintopuremachinecode.

if(flag_specification)then<>endif;

Thisformis,perhaps,theeasiestHLAifstatementtoconvert.To

executethecodeimmediatelyfollowingthethenkeywordifaparticular

flagisset(orclear),allyouneeddoisskipoverthecodeiftheflagis

clear(set).Thisrequiresonlyasingleconditionaljumpinstructionfor

implementationasthefollowingexamplesdemonstrate:

//if(@c)theninc(eax);endif;

jncSkipTheInc;

inc(eax);

SkipTheInc:

//if(@ns)thenneg(eax);endif;

jsSkipTheNeg;

neg(eax);

SkipTheNeg:

if(register)then<>endif;

Thisformoftheifstatementusesthetestinstructiontocheckthe

specifiedregisterforzero.Iftheregistercontainszero(false),thenthe

programjumpsaroundthestatementsafterthethenclausewithajz

instruction.Convertingthisstatementtoassemblylanguagerequiresa

testinstructionandajzinstructionasthefollowingexamples

demonstrate:

//if(eax)thenmov(false,eax);endif;

test(eax,eax);

jzDontSetFalse;



mov(false,eax);

DontSetFalse:

//if(al)thenmov(bl,cl);endif;

test(al,al);

jznoMove;

mov(bl,cl);

noMove:

if(!register)then<>endif;

Thisformoftheifstatementusesthetestinstructiontocheckthe

specifiedregistertoseeifitiszero.Iftheregisterisnotzero(true),then

theprogramjumpsaroundthestatementsafterthethenclausewitha

jnzinstruction.Convertingthisstatementtoassemblylanguagerequires

atestinstructionandajnzinstructioninamanneridenticaltothe

previousexamples.

if(boolean_variable)then<>endif;

Thisformoftheifstatementcomparesthebooleanvariableagainst

zero(false)andbranchesaroundthestatementsifthevariablecontains

false.HLAimplementsthisstatementbyusingthecmpinstructionto

comparethebooleanvariabletozeroandthenitusesajz(je)

instructiontojumparoundthestatementsifthevariableisfalse.The

followingexampledemonstratestheconversion:

//if(bool)thenmov(0,al);endif;

cmp(bool,false);

jeSkipZeroAL;

mov(0,al);

SkipZeroAL:



if(!boolean_variable)then<>endif;

Thisformoftheifstatementcomparesthebooleanvariableagainst

zero(false)andbranchesaroundthestatementsifthevariablecontains

true(i.e.,theoppositeconditionofthepreviousexample).HLA

implementsthisstatementbyusingthecmpinstructiontocomparethe

booleanvariabletozeroandthenitusesajnz(jne)instructionto

jumparoundthestatementsifthevariablecontainstrue.Thefollowing

exampledemonstratestheconversion:

//if(!bool)thenmov(0,al);endif;

cmp(bool,false);

jneSkipZeroAL;

mov(0,al);

SkipZeroAL:

if(mem_regrelopmem_reg_const)then<>endif;

HLAtranslatesthisformoftheifstatementintoacmpinstructionanda

conditionaljumpthatskipsoverthestatementsontheoppositecondition

specifiedbytherelopoperator.Table7-4liststhecorrespondence

betweenoperatorsandconditionaljumpinstructions.

Table7-4:IFStatementConditionalJumpInstructions

ConditionalJumpInstruction ConditionalJump

Relop IfBothOperandsAre

InstructionIfEither

Unsigned

OperandIsSigned

=or

==



JNE



JNE



<>or

JE

!=



JE



<



JNL



JNB



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

6 " Medium Level " Control Structures: JT and JF

Tải bản đầy đủ ngay(0 tr)

×