ch4 1指令系统架构_第1页
ch4 1指令系统架构_第2页
ch4 1指令系统架构_第3页
ch4 1指令系统架构_第4页
ch4 1指令系统架构_第5页
已阅读5页,还剩59页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ComputerOrganizationPrinciplesSchoolofSoftware,DalianUniversityofTechnologyChiLin(林驰)

Whydoweneedtostudyassemblylanguage?ComplicatedBoringTediousNearlyuseless…2CarnegieMellonGreatReality#2:

You’veGottoKnowAssemblyChancesare,you’llneverwriteprogramsinassemblyCompilersaremuchbetter&morepatientthanyouareBut:Understandingassemblyiskeytomachine-levelexecutionmodelBehaviorofprogramsinpresenceofbugsHigh-levellanguagemodelsbreakdownTuningprogramperformanceUnderstandoptimizationsdone/notdonebythecompilerUnderstandingsourcesofprograminefficiencyImplementingsystemsoftwareCompilerhasmachinecodeastargetOperatingsystemsmustmanageprocessstateCreating/fightingmalwarex86assemblyisthelanguageofchoice!ReasonTwo:ProgrammerRankingsHigherLevelLanguageleadstoLowLevelProgrammer.Niubility=Familiarwith(orGrasp)ComputerPrinciples+DataStructure+Algorithm+C/C++Struggle!YoucanbeNiubilitywithnofriends.4OurCoverageIA32Thetraditionalx86x86-64/EM64T(Optional)TheemergingstandardPresentationBookpresentsIA32inSections3.1—3.12Coversx86-64in3.13(Optional)ChapterFour:InstructionSystemsInstructionEncoding(指令编码)AddressingModesandFormats(寻址方式)InstructionUsage(指令使用方法)RISCChapterFour:InstructionSystemsInstructionEncoding(指令编码)AddressingModesandFormats(寻址方式)InstructionUsage(指令使用方法)RISCChap4.1InstructionEncodingMachineInstructionCharacteristicsTypesofOperands(操作数类型)TypesofOperations(指令操作种类)Examples8Chap4.1InstructionEncodingMachineInstructionCharacteristicsTypesofOperandsTypesofOperationsExamples9DefinitionofInstructionSet(指令集)Theoperationoftheprocessorisdeterminedbytheinstructionsitexecutes,referredtoasmachineinstructionsorcomputerinstructions.Thecollectionsofdifferentinstructionsthattheprocessorcanexecuteisreferredtoastheprocessor’sinstructionset.10InstructionCycleStateDiagramOperand:操作数11ElementsofainstructionOperationcode:Specifiestheoperationtobeperformed(e.g.,ADD,I/O).Theoperationisspecifiedbyabinarycode,knownastheoperationcode,oropcode.Sourceoperandreference:Theoperationmayinvolveoneormoresourceoperands,thatis,operandsthatareinputsfortheoperation.Resultoperandreference:Theoperationmayproducearesult.Nextinstructionreference:Thistellstheprocessorwheretofetchthenextinstructionaftertheexecutionofthisinstructioniscomplete.12InstructionRepresentationWithinthecomputer,eachinstructionisrepresentedbyasequenceofbits.Theinstructionisdividedintofields,correspondingtotheconstituentelementsoftheinstruction.Duringinstructionexecution,aninstructionisreadintoaninstructionregister(IR)intheprocessor.Theprocessormustbeabletoextractthedatafromthevariousinstructionfieldstoperformtherequiredoperation.13OpcodesOpcodesarerepresentedbyabbreviations(缩写).CommonexamplesincludeADDAddSUBSubtractMULMultiplyDIVDivideLOADLoaddatafrommemorySTORStoredatatomemoryOperandsarealsorepresentedsymbolically.Forexample,theinstruction14High-LevelLanguageToLowLevelX=X+Y(X=513,Y=514)Loadaregisterwiththecontentsofmemorylocation513.Addthecontentsofmemorylocation514totheregister.Storethecontentsoftheregisterinmemorylocation513.15Howtoconvertitintoassemblylanguage?texttextbinarybinaryCompiler(gcc-S)Assembler(gccoras)Linker(gccor

ld)Cprogram(p1.cp2.c)Asmprogram(p1.sp2.s)Objectprogram(p1.op2.o)Executableprogram(p)Staticlibraries(.a)TurningCintoObjectCodeCodeinfilesp1.cp2.cCompilewithcommand:gcc–O1p1.cp2.c-opUsebasicoptimizations(-O1)PutresultingbinaryinfilepCompilingIntoAssemblyCCodeintsum(intx,inty){intt=x+y;returnt;}GeneratedIA32Assemblysum:pushl%ebpmovl%esp,%ebpmovl12(%ebp),%eaxaddl8(%ebp),%eaxpopl%ebpretObtainwithcommand/usr/local/bin/gcc–O1-Scode.cProducesfilecode.sSomecompilersuseinstruction“leave”DataTypes“Integer”dataof1,2,or4bytesDatavaluesAddresses(untypedpointers)Floatingpointdataof4,8,or10bytesNoaggregatetypessuchasarraysorstructuresJustcontiguouslyallocatedbytesinmemoryInstructiontypesDataprocessing:Arithmeticandlogicinstructions.Datastorage:MovementofdataintooroutofregisterandormemorylocationsDatamovement:I/OinstructionsControl:Testandbranchinstruction19NumberofAddresses20Trade-offsofthenumberofaddressesMoreaddressesLongexecutiontimeMorecomplexprogramFaster(Registervs.memory)FlexibilityFeweraddressesMoreprimitiveRequirealesscomplexprocessorShortlengthofinstructions21Mostcomputersemployamixtureoftwo-andthreeaddressinstructionsInstructionSetDesignOneofthemostinteresting,andmostanalyzed,aspectsofcomputerdesignisinstructionsetdesign.Thedesignofaninstructionsetisverycomplexbecauseitaffectssomanyaspectsofthecomputersystem.Theinstructionsetdefinesmanyofthefunctionsperformedbytheprocessorandthushasasignificanteffectontheimplementationoftheprocessor.

Theinstructionsetistheprogrammer’smeansofcontrollingtheprocessor.Thus,programmerrequirementsmustbeconsideredindesigningtheinstructionset.22InstructionSetDesignOperationrepertoire(操作种类):Howmanyandwhichoperationstoprovide,andhowcomplexoperationsshouldbe?Datatypes:Thevarioustypesofdatauponwhichoperationsareperformed.Instructionformat:Instructionlength(inbits),numberofaddresses,sizeofvariousfields,andsoon.23InstructionSetDesignRegisters:Numberofprocessorregistersthatcanbereferencedbyinstructions,andtheiruseAddressing:Themodeormodesbywhichtheaddressofanoperandisspecified24Chap4.1InstructionEncodingMachineInstructionCharacteristicsTypesofOperandsTypesofOperationsExamples25TypesofOperands(操作数)

Machineinstructionsoperateondata.Themostimportantgeneralcategoriesofdataare:Memory(内存地址)Register(寄存器)Immediate(立即数)26OperandsForms2728MovingData:IA32MovingDatamovl

Source,Dest:OperandTypesImmediate:ConstantintegerdataExample:$0x400,$-533LikeCconstant,butprefixedwith‘$’Encodedwith1,2,or4bytesRegister:Oneof8integerregistersExample:%eax,%edxBut%espand%ebpreservedforspecialuseOthershavespecialusesforparticularinstructionsMemory:4consecutivebytesofmemoryataddressgivenbyregisterSimplestexample:(%eax)Variousother“addressmodes”%eax%ecx%edx%ebx%esi%edi%esp%ebpmovlOperandCombinationsCannotdomemory-memorytransferwithasingleinstructionmovlImmRegMemRegMemRegMemRegSourceDestCAnalogmovl$0x4,%eaxtemp=0x4;movl$-147,(%eax)*p=-147;movl%eax,%edxtemp2=temp1;movl%eax,(%edx)*p=temp;movl(%eax),%edxtemp=*p;Src,DestSimpleMemoryAddressingModesNormal (R) Mem[Reg[R]]RegisterRspecifiesmemoryaddress

movl(%ecx),%eaxDisplacement D(R) Mem[Reg[R]+D]RegisterRspecifiesstartofmemoryregionConstantdisplacementDspecifiesoffset

movl8(%ebp),%edxChap4.1InstructionEncodingMachineInstructionCharacteristicsTypesofOperandsTypesofOperationsExamples32AssemblyCharacteristics:OperationsPerformarithmeticfunctiononregisterormemorydataTransferdatabetweenmemoryandregisterLoaddatafrommemoryintoregisterStoreregisterdataintomemoryTransfercontrolUnconditionaljumpsto/fromproceduresConditionalbranchesTypesofOperations(opcode)

Thenumberofdifferentopcodesvarieswidelyfrommachinetomachine.However,thesamegeneraltypesofoperationsarefoundonallmachines.Ausefulandtypicalcategorizationisthefollowing:DatamovementArithmetic&LogicalStateControl&SettingsJumping34DataMovementInstruction35DataMovementInstructionAmongthemostheavilyusedinstructionsarethosethatcopydatafromonelocationtoanother.Thegeneralityoftheoperandnotationallowsasimpledatamovementinstructiontoperformwhatinmanymachineswouldrequireanumberofinstructions36DataTransfer&DataMovementInstructionThelocationofthesourceanddestinationoperandsmustbespecified.Eachlocationcouldbememory,aregister,orthetopofthestack.ThelengthofdatatobetransferredmustbeindicatedThemodeofaddressingforeachoperandmustbespecified.37MovclassTheinstructionsinthemovclasscopytheirsourcevaluestotheirdestinations.Thesourceoperanddesignatesavaluethatisimmediate,storedinaregister,orstoredinmemory.Thedestinationoperanddesignatesalocationthatiseitheraregisteroramemoryaddress.38Push&PopWeadddatatoastackviaapushoperationandremoveitviaapopoperation,withthepropertythatthevaluepoppedwillalwaysbethevaluethatwasmostrecentlypushedandisstillonthestack.Firstinlastout39IntegerArithmeticOperations40ArithmeticInstructionTheexecutionofanarithmeticinstructionmayinvolvedatatransferoperationstopositionoperandsforinputtotheALU,andtodelivertheoutputoftheALU.E.g.ADD%ESP,%EAX41LogicalInstruction42Shiftinstructions43SpecialArithmeticOperations44ComparisonandTestInstructions45ConditionCodeRegisterInadditiontotheintegerregisters,theCPUmaintainsasetofsingle-bitconditioncoderegistersdescribingattributesofthemostrecentarithmeticorlogicaloperation.Theseregisterscanthenbetestedtoperformconditionalbranches.Themostusefulconditioncodesare:CF:CarryFlag.Themostrecentoperationgeneratedacarryoutofthemostsignificantbit.Usedtodetectoverflowforunsignedoperations.ZF:ZeroFlag.Themostrecentoperationyieldedzero.SF:SignFlag.Themostrecentoperationyieldedanegativevalue.OF:OverflowFlag.Themostrecentoperationcausedatwo’plementoverflow—eithernegativeorpositive.46TheSetInstructions47JumpingInstructionAjumpinstructioncancausetheexecutiontoswitchtoacompletelynewpositionintheprogram.Thesejumpdestinationsaregenerallyindicatedinassemblycodebyalabel.48TheJumpingInstruction/branchInstruction49TransferringControlThecallinstructionhasatargetindicatingtheaddressoftheinstructionwherethecalledprocedurestarts.Likejumps,acallcaneitherbedirectorindirect.Theretinstructionpopsanaddressoffthestackandjumpstothislocation.Theproperuseofthisinstructionistohavepreparedthestacksothatthestackpointerpointstotheplacewheretheprecedingcallinstructionstoreditsreturnaddress.50ExampleofNestedProcedures(嵌套函数)51Chap4.1InstructionEncodingMachineInstructionCharacteristicsTypesofOperandsTypesofOperationsExamples52UsingSimpleAddressingModesvoidswap(int*xp,int*yp){intt0=*xp;intt1=*yp;*xp=t1;*yp=t0;}BodySetUpFinishswap:pushl%ebpmovl%esp,%ebppushl%ebxmovl8(%ebp),%edxmovl12(%ebp),%ecxmovl(%edx),%ebxmovl(%ecx),%eaxmovl%eax,(%edx)movl%ebx,(%ecx)popl%ebxpopl%ebpretUsingSimpleAddressingModesvoidswap(int*xp,int*yp){intt0=*xp;intt1=*yp;*xp=t1;*yp=t0;}swap:

pushl%ebp movl%esp,%ebp pushl%ebx

movl 8(%ebp),%edx movl 12(%ebp),%ecx movl (%edx),%ebx movl (%ecx),%eax movl %eax,(%edx) movl %ebx,(%ecx)

popl %ebx popl %ebp retBodySetUpFinishUnderstandingSwapvoidswap(int*xp,int*yp){intt0=*xp;intt1=*yp;*xp=t1;*yp=t0;}Stack(inmemory)Register Value%edx xp%ecx yp%ebx t0%eax t1ypxpRtnadrOld%ebp%ebp04812Offset•••Old%ebx-4%esp movl 8(%ebp),%edx #edx=xp movl 12(%ebp),%ecx #ecx=yp movl (%edx),%ebx #ebx=*xp(t0) movl (%ecx),%eax #eax=*yp(t1) movl %eax,(%edx) #*xp=t1 movl %ebx,(%ecx) #*yp=t0UnderstandingSwap0x1200x124Rtnadr%ebp04812Offset-4123456Address0x1240x1200x11c0x1180x1140x1100x10c0x1080x1040x100ypxp%eax%edx%ecx%ebx%esi%edi%esp%ebp0x104 movl 8(%ebp),%edx #edx=xp movl 12(%ebp),%ecx #ecx=yp movl (%edx),%ebx #ebx=*xp(t0) movl (%ecx),%eax #eax=*yp(t1) movl %eax,(%edx) #*xp=t1 movl %ebx,(%ecx) #*yp=t0UnderstandingSwap0x1200x124Rtnadr%ebp04812Offset-4123456Address0x1240x1200x11c0x1180x1140x1100x10c0x1080x1040x100ypxp%eax%edx%ecx%ebx%esi%edi%esp%ebp0x1240x1040x120

movl 8(%ebp),%edx #edx=xp movl 12(%ebp),%ecx #ecx=yp movl (%edx),%ebx #ebx=*xp(t0) movl (%ecx),%eax #eax=*yp(t1) movl %eax,(%edx) #*xp=t1 movl %ebx,(%ecx) #*yp=t0UnderstandingSwap0x1200x124Rtnadr%ebp04812Offset-4123456Address0x1240x1200x11c0x1180x1140x1100x10c0x1080x1040x100ypxp%eax%edx%ecx%ebx%esi%edi%esp%ebp0x1200x1040x1240x124 movl 8(%ebp),%edx #edx=xp

movl 12(%ebp),%ecx #ecx=yp movl (%edx),%ebx #ebx=*xp(t0) movl (%ecx),%eax #eax=*yp(t1) movl %eax,(%edx) #*xp=t1 movl %ebx,(%ecx) #*yp=t0456UnderstandingSwap0x1200x124Rtnadr%ebp04812Offset-4123456Address0x1240x1200x11c0x1180x1140x1100x10c0x1080x1040x100ypxp%eax%edx%ecx%ebx%esi%edi%esp%ebp0x1240x1201230x1

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论