Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
CS61C:GreatIdeasinComputerArchitectureLecture2:IntroductiontoC,PartI
Instructors:VladimirStojanovic&NicholasWeaver
http://inst.eecs.berkeley.edu/~cs61c/
1
Agenda
• EverythingisaNumber• ComputerOrganization• Compilevs.Interpret
2
KeyConcepts• Insidecomputers,everythingisanumber• Butnumbersusuallystoredwithafixedsize– 8-bitbytes,16-bithalfwords,32-bitwords,64-bitdoublewords,…
• Integerandfloating-pointoperationscanleadtoresultstoobig/smalltostorewithintheirrepresentations:overflow/underflow
3
NumberRepresentation
• Valueofi-th digitisd × Baseiwherei startsat0andincreasesfromrighttoleft:
• 12310=110 x 10102 +210 x 10101 +310 x 10100
=1x10010 +2x1010 +3x110=10010 +2010 +310=12310
• Binary(Base2),Hexadecimal(Base16),Decimal(Base10)differentwaystorepresentaninteger– We’lluse1two,5ten,10hex tobeclearer
(vs.12,48,510,1016)
4
NumberRepresentation
• Hexadecimaldigits:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
• FFFhex =15tenx16ten2 +15tenx16ten1 +15tenx16ten0=3840ten +240ten +15ten=4095ten
• 111111111111two =FFFhex =4095ten• Mayputblankseverygroupofbinary,octal,orhexadecimaldigitstomakeiteasiertoparse,likecommasindecimal
5
SignedandUnsignedIntegers
• C,C++,andJavahavesignedintegers,e.g.,7,-255:int x, y, z;
• C,C++alsohaveunsigned integers,whichareusedforaddresses
• 32-bitwordcanrepresent232 binarynumbers• Unsignedintegersin32bitwordrepresent0to232-1(4,294,967,295)
6
UnsignedIntegers00000000000000000000000000000000two =0ten00000000000000000000000000000001two =1ten00000000000000000000000000000010two =2ten
... ...01111111111111111111111111111101two =2,147,483,645ten01111111111111111111111111111110two =2,147,483,646ten01111111111111111111111111111111two =2,147,483,647ten10000000000000000000000000000000two =2,147,483,648ten10000000000000000000000000000001two =2,147,483,649ten10000000000000000000000000000010two =2,147,483,650ten
... ...11111111111111111111111111111101two =4,294,967,293ten11111111111111111111111111111110two =4,294,967,294ten11111111111111111111111111111111two =4,294,967,295ten
7
SignedIntegersandTwo’s-ComplementRepresentation
• SignedintegersinC;want½numbers<0,want½numbers>0,andwantone0
• Two’scomplementtreats0aspositive,so32-bitwordrepresents232integersfrom-231(–2,147,483,648) to231-1(2,147,483,647)– Note:onenegativenumberwithnopositiveversion– Booklistssomeotheroptions,allofwhichareworse– Everycomputerusestwo’scomplementtoday
• Most-significantbit(leftmost)isthesignbit,since0meanspositive(including0),1meansnegative– Bit31ismostsignificant,bit0isleastsignificant
8
Two’s-ComplementIntegers00000000000000000000000000000000two =0ten00000000000000000000000000000001two =1ten00000000000000000000000000000010two =2ten
... ...01111111111111111111111111111101two =2,147,483,645ten01111111111111111111111111111110two =2,147,483,646ten01111111111111111111111111111111two =2,147,483,647ten10000000000000000000000000000000two =–2,147,483,648ten10000000000000000000000000000001two =–2,147,483,647ten10000000000000000000000000000010two =–2,147,483,646ten
... ...11111111111111111111111111111101two =–3ten11111111111111111111111111111110two =–2ten11111111111111111111111111111111two =–1ten
1/21/16 9
SignBit
WaystoMakeTwo’sComplement• ForN-bitword,complementto2tenN
– For4bitnumber3ten=0011two,
two’scomplement(i.e.-3ten)wouldbe
16ten-3ten=13ten or10000two – 0011two =1101two
10
• Hereisaneasierway:– Invertallbitsandadd1
– Computersactuallydoitlikethis,too
0011two
1100two+1two
3ten
1101two
Bitwisecomplement
-3ten
BinaryAdditionExample
00110010
3+25 1
0
0
1
1
0
0
0
0
Carry
11
Two’s-ComplementExamples
• Assumeforsimplicity4bitwidth,-8to+7represented
12
00110010
3+25 0101
00111110
3+(-2)
1 10001
01110001
7+1-8 1000Overflow!
11011110
-3+(-2)
-5 11011
10001111
-8+(-1)+7 10111
CarryintoMSB=CarryOutMSB
CarryintoMSB=CarryOutMSB
Overflow!
Overflowwhenmagnitudeofresulttoobigtofitintoresultrepresentation
Carryin=carryfromlesssignificantbitsCarryout=carrytomoresignificantbits
0to+31
-16to+15
-32to+31☐
☐
☐
☐
13
Supposewehada5-bitword.Whatintegerscanberepresentedintwo’scomplement?
0to+31
-16to+15
-32to+31☐
☐
☐
☐
14
Supposewehada5bitword.Whatintegerscanberepresentedintwo’scomplement?
Agenda
• EverythingisaNumber• ComputerOrganization• Compilevs.Interpret
15
ENIAC(U.Penn.,1946)FirstElectronicGeneral-PurposeComputer
16
• Blazinglyfast(multiplyin2.8ms!)– 10decimaldigitsx10decimaldigits
• Butneeded2-3daystosetupnewprogram,asprogrammedwithpatchcordsandswitches
EDSAC(Cambridge,1949)FirstGeneralStored-ProgramComputer
17
• Programsheldasnumbersinmemory• 35-bitbinary2’scomplementwords
Processor
Control
Datapath
ComponentsofaComputer
18
PC
Registers
Arithmetic&LogicUnit(ALU)
MemoryInput
Output
Bytes
Enable?Read/Write
Address
WriteData
ReadData
Processor-Memory Interface I/O-MemoryInterfaces
Program
Data
GreatIdea:LevelsofRepresentation/Interpretation
lw $t0,0($2)lw $t1,4($2)sw $t1,0($2)sw $t0,4($2)
HighLevelLanguageProgram(e.g.,C)
AssemblyLanguageProgram(e.g.,MIPS)
MachineLanguageProgram(MIPS)
HardwareArchitectureDescription(e.g.,blockdiagrams)
Compiler
Assembler
MachineInterpretation
temp=v[k];v[k]=v[k+1];v[k+1]=temp;
0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
LogicCircuitDescription(CircuitSchematicDiagrams)
ArchitectureImplementation
Anythingcanberepresentedasanumber,
i.e.,dataorinstructions
19
Wearehere!
IntroductiontoC“TheUniversalAssemblyLanguage”
• Classpre-req includedclassesteachingJava
• Pythonusedintwolabs• Cusedforeverythingelse
• “Some”experienceisrequiredbeforeCS61CC++orJavaOK
20
IhaveprogrammedinC,C++,C#,orObjective-C☐
IhaveprogrammedinJava☐
IhaveprogrammedinFORTRAN,Cobol,Algol-68,Ada,Pascal,orBasic
☐
☐
21
LanguagePoll!Pleaseraisehandforfirstoneoffollowingyoucansayyesto
IntrotoC• Cisnota“veryhigh-level” language,nora“big”one,andisnotspecializedtoanyparticularareaofapplication.Butitsabsenceofrestrictionsanditsgeneralitymakeitmoreconvenientandeffectiveformanytasksthansupposedlymorepowerfullanguages.
– KernighanandRitchie• Enabledfirstoperatingsystemnotwritteninassemblylanguage:UNIX- AportableOS!
22
IntrotoC
• WhyC?:wecanwriteprogramsthatallowustoexploitunderlying featuresofthearchitecture– memorymanagement,specialinstructions,parallelism
• Candderivatives(C++/Obj-C/C#)stilloneofthemostpopularapplicationprogramminglanguagesafter>40years!
23
TIOBEIndexofLanguagePopularity
24http://www.tiobe.comTheratingsarebasedon thenumber ofskilledengineersworld-wide,coursesandthirdpartyvendors.
TIOBEProgrammingCommunityIndex
25
Disclaimer• YouwillnotlearnhowtofullycodeinCintheselectures!You’llstillneedyourCreference forthiscourse– K&Risamust-have
• Checkonlineformoresources– “JAVAinaNutshell,”O’Reilly
• Chapter2,“HowJavaDiffersfromC”• http://oreilly.com/catalog/javanut/excerpt/index.html
– BrianHarvey’shelpfultransitionnotes• OnCS61Cclasswebsite:pages3-19• http://inst.eecs.berkeley.edu/~cs61c/resources/HarveyNotesC1-3.pdf
• KeyCconcepts:Pointers,Arrays,ImplicationsforMemorymanagement
26
Agenda
• EverythingisaNumber• ComputerOrganization• Compilevs.Interpret
27
Compilation:Overview• CcompilersmapCprogramsintoarchitecture-specificmachinecode(stringof1sand0s)– UnlikeJava,whichconvertstoarchitecture-independentbytecode
– UnlikePythonenvironments,whichinterpretthecode– Thesediffermainlyinexactlywhenyourprogramisconvertedtolow-levelmachineinstructions(“levelsofinterpretation”)
– ForC,generallyatwopartprocessofcompiling.c filesto.o files,thenlinkingthe.o filesintoexecutables;
– Assemblingisalsodone(butishidden,i.e.,doneautomatically,bydefault);we’lltalkaboutthatlater
28
CCompilationSimplifiedOverview(morelaterincourse)
29
foo.c bar.c
Compiler Compiler
foo.o bar.o
Linker lib.o
a.out
Csourcefiles(text)
Machinecodeobjectfiles
Pre-builtobjectfilelibraries
Machinecodeexecutablefile
Compiler/assemblercombinedhere
Compilation:Advantages
• Excellentrun-timeperformance:generallymuchfasterthanSchemeorJavaforcomparablecode(becauseitoptimizesforagivenarchitecture)
• Reasonablecompilationtime:enhancementsincompilationprocedure(Makefiles)allowonlymodifiedfilestoberecompiled
30
Compilation:Disadvantages• Compiledfiles,includingtheexecutable,arearchitecture-specific,dependingonprocessortype(e.g.,MIPSvs.RISC-V)andtheoperatingsystem(e.g.,Windowsvs.Linux)
• Executablemustberebuiltoneachnewsystem– I.e.,“portingyourcode”toanewarchitecture
• “Change→ Compile→ Run[repeat]”iterationcyclecanbeslowduringdevelopment– butMaketoolonlyrebuildschangedpieces,andcandocompilesinparallel(linkerissequentialthough->Amdahl’sLaw)
31
CPre-Processor(CPP)
• Csourcefilesfirstpassthroughmacroprocessor,CPP,beforecompilerseescode
• CPPreplacescommentswithasinglespace• CPPcommandsbeginwith“#”• #include“file.h”/*Insertsfile.h intooutput*/• #include<stdio.h>/*Looksforfileinstandardlocation*/• #defineM_PI(3.14159)/*Defineconstant*/• #if/#endif /*Conditionalinclusionoftext*/• Use–save-tempsoptiontogcc toseeresultofpreprocessing• Fulldocumentationat:http://gcc.gnu.org/onlinedocs/cpp/
32
foo.c CPP foo.i Compiler