more ccr4bd/3330/s2018/slides/20180130--slides-1up.pdfagenda •pointer vs array •using man page...

46
Samira Khan MORE C

Upload: others

Post on 23-Apr-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SamiraKhan

MOREC

Page 2: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Agenda• Pointervsarray

• Usingmanpage

• Structureanddynamicallocation

• Undefinedbehavior

• Intotoinstructionsetarchitecture(ISA)

Page 3: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

UnderstandingPointers&Arrays

A1

A2Allocatedint

UnallocatedpointerAllocatedpointer

Unallocatedint

Variable Decl

int A1[3]

int *A2

size

12

8

Page 4: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

UnderstandingPointers&Arrays

A1

A2/A4

AllocatedintUnallocatedpointerAllocatedpointer

Unallocatedint

A3

Variable Decl

int A1[3]

int *A2[3]

int (*A3)[3]

int (*A4[3])

Size

12

24

8

24

Page 5: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Arrayvs.Pointer

int array[100];

int *pointer;

pointer = array;• sameaspointer=&(array[0]);

array = pointer;

Page 6: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Arrayvs.Pointer

int array[100];

int *pointer = array;

• sizeof(array)==400(sizeofallelements)• sizeof(pointer)==8(sizeofaddress)

• sizeof(&array[0])==???• (&array[0]sameas&(array[0]))

Page 7: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Agenda• Pointervsarray

• Usingmanpage

• Structureanddynamicallocation

• Undefinedbehavior

• Intotoinstructionsetarchitecture(ISA)

Page 8: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

interlude:commandlinetips

Page 9: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction
Page 10: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction
Page 11: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

chmod

• chmod --recursiveog-r /home/USER

• ogà othersandgroup(student)• user(yourself)/group/others

• -à remove• - remove/+add

• rà read• read/write/execute

Page 12: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

tar

• StandardLinux/Unixfilearchiveutility• Tableofcontents:tartf filename.tar• eXtract:tarxvf filename.tar• Create:tarcvf filename.tar directory• (v:verbose;f:file— defaultistape)

Page 13: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

stdio

• Cdoesnothave<iostream>• instead<stdio.h>

Page 14: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction
Page 15: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction
Page 16: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

printf

1 int custNo = 1000;

2 const char *name = "Jane Smith"3 printf("Customer #%d: %s\n”, custNo, name);4 // "Customer #1000: Jane Smith"5 // same as:

6 //cout << "Customer #" << custNo

7 // << ": " << name << endl;

Formatstringmustmatchtypesofargument

Page 17: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

printf formatsquickreference

Specifier ArgumentType Example

%s char* Hello,World!

%p anypointer 0x4005d4

%d int/short/char 42

%u unsignedint/short/char 42

%x unsignedint/short/char 2a

%ld long 42

%f double/float 42.0000000.000000

%e double/float 4.200000e+014.200000e-19

%g double/float 42,4.2e-19

%% noargument %man3printf

Page 18: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Agenda• Pointervsarray

• Usingmanpage

• Structureanddynamicallocation

• Undefinedbehavior

• Intotoinstructionsetarchitecture(ISA)

Page 19: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Structure

• Structurerepresentedasblockofmemory• Bigenoughtoholdallofthefields

• Fieldsorderedaccordingtodeclaration

a

r

next

0 16 24

struct rec {int a[4];struct rec *next;

};

Page 20: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

structstruct rational {int numerator;int denominator;};// ...struct rational two_and_a_half;two_and_a_half.numerator = 5;two_and_a_half.denominator = 2;struct rational *pointer = &two_and_a_half;printf("%d/%d\n",pointer->numerator,pointer->denominator);

Page 21: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

typedef structstruct other_name_for_rational {int numerator;int denominator;};typedef struct other_name_for_rational rational;// ...rational two_and_a_half;two_and_a_half.numerator = 5;two_and_a_half.denominator = 2;rational *pointer = &two_and_a_half;printf("%d/%d\n",pointer->numerator,pointer->denominator);

Page 22: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

typedef structstruct other_name_for_rational {int numerator;int denominator;};typedef struct other_name_for_rational rational;// same as:typedef struct other_name_for_rational {int numerator;int denominator;} rational;// almost the same as:typedef struct {int numerator;int denominator;} rational;

Page 23: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

structs aren’treferencestypedef struct {long a; long b; long c;} triple;...triple foo;foo.a = foo.b = foo.c = 3;triple bar = foo;bar.a = 4;// foo is 3, 3, 3// bar is 4, 3, 3

Page 24: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Dynamicallocation

typedef struct list_t {int item;struct list_t *next;} list;// ...list* head = malloc(sizeof(list));/* C++: new list; */head->item = 42;head->next = NULL;// ...free(head);/* C++: delete list */

Page 25: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Dynamicarraysint *array = malloc(sizeof(int)*100);// C++: new int[100]

for (i = 0; i < 100; ++i) {

array[i] = i;

}

// ...

free(array); // C++: delete[] array

Page 26: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

unsignedandsignedtypes

Type min max

signedint =signed=int −231 231 - 1

unsignedint =unsigned 0 232 - 1

signedlong=long −263 263 - 1

unsignedlong 0 264 - 1

Page 27: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Agenda• Pointervsarray

• Usingmanpage

• Structureanddynamicallocation

• Undefinedbehavior

• Intotoinstructionsetarchitecture(ISA)

Page 28: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

unsigned/signedcomparisontrap

int x = -1;unsigned int y = 0;printf("%d\n", x < y);• resultis0• shortsolution:don’tcomparesignedtounsigned:• (long)x<(long)y

• Compilerconvertsbothtosametypefirst• int ifallpossiblevaluesfit• otherwise:firstoperand(x,y)typefromthislist:• unsignedlong,long,unsignedint,int

Page 29: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Cevolutionandstandards

• 1978:KernighanandRitchiepublishTheCProgrammingLanguage— “K&RC”• verydifferentfrommodernC

• 1989:ANSIstandardizesC— C89/C90/-ansi• compileroption:-ansi,-std=c90• looksmostlylikemodernC

• 1999:ISO(andANSI)updateCstandard— C99• compileroption:-std=c99• adds:declarevariablesinmiddleofblock• adds://comments

• 2011:SecondISOupdate— C11

Page 30: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Undefinedbehaviorexample(1)

#include <stdio.h>#include <limits.h>int test(int number) {return (number + 1) > number;}int main(void) {printf("%d\n", test(INT_MAX));}• withoutoptimizations:0• withoptimizations:1

Page 31: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Undefinedbehaviorexample(2)int test(int number) {return (number + 1) > number;}• Optimized:test:movl $1, %eax # eax 1ret• Lessoptimized:test:leal 1(%rdi), %eax # eax rdi + 1cmpl %eax, %edisetl %al # al eax < edimovzbl %al, %eax # eax al (pad with zeros)ret

Page 32: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Undefinedbehavior

• compilerscandowhatevertheywant• whatyouexpect• crashyourprogram• …

• commontypes:• signedintegeroverflow/underflow• out-of-boundspointers• integerdivide-by-zero• writingread-onlydata• out-of-boundsshift(later)

Page 33: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Agenda• Pointervsarray

• Usingmanpage

• Structureanddynamicallocation

• Undefinedbehavior

• Intotoinstructionsetarchitecture(ISA)

Page 34: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

LEVELSOFTRANSFORMATION• ISA• Agreeduponinterfacebetweensoftwareandhardware• SW/compilerassumes,HWpromises

• Whatthesoftwarewriterneedstoknowtowritesystem/userprograms

• Microarchitecture• SpecificimplementationofanISA• Notvisibletothesoftware

• Microprocessor• ISA,uarch,circuits• “Architecture” =ISA+microarchitecture

MicroarchitectureISAProgram/Language

AlgorithmProblem

Logic

Circuits

34

Page 35: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

ISAVS.MICROARCHITECTURE• WhatispartofISAvs.Uarch?

• Gaspedal:interfacefor“acceleration”• Internalsoftheengine:implements“acceleration”• Addinstructionvs.Adderimplementation

• Implementation(uarch)canbevariousaslongasitsatisfiesthespecification(ISA)• Bitserial,ripplecarry,carrylookahead adders• x86ISAhasmanyimplementations:286,386,486,Pentium,PentiumPro,…

• Uarch usuallychangesfasterthanISA• FewISAs(x86,SPARC,MIPS,Alpha)butmanyuarchs• Why?

35

Page 36: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

ISA • Instructions• Opcodes,AddressingModes,DataTypes• InstructionTypesandFormats• Registers,ConditionCodes

• Memory• Addressspace,Addressability,Alignment• Virtualmemorymanagement

• Call,Interrupt/ExceptionHandling• AccessControl,Priority/Privilege• I/O• TaskManagement• PowerandThermalManagement• Multi-threadingsupport,Multiprocessorsupport

36

Page 37: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

ISAsbeingmanufacturedtoday

• x86— dominantindesktops,servers• ARM— dominantinmobiledevices• POWER—WiiU,IBMsupercomputersandsomeservers• MIPS— commoninconsumerwifi accesspoints• SPARC— someOracleservers,Fujitsusupercomputers• z/Architecture— IBMmainframes• Z80— TIcalculators• SHARC— somedigitalsignalprocessors• Itanium— someHPservers(beingretired)• RISCV— someembedded• …

Page 38: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

Microarchitecture• ImplementationoftheISAunderspecific designconstraintsandgoals• Anythingdoneinhardwarewithoutexposuretosoftware• Pipelining• In-orderversusout-of-orderinstructionexecution• Memoryaccessschedulingpolicy• Speculativeexecution• Superscalarprocessing(multipleinstructionissue?)• Clockgating• Caching?Levels,size,associativity,replacementpolicy• Prefetching?• Voltage/frequencyscaling?• Errorcorrection?

38

Page 39: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

ISA-LEVELTRADEOFFS:SEMANTICGAP

• WheretoplacetheISA?Semanticgap• Closertohigh-levellanguage(HLL)orclosertohardwarecontrolsignals?àComplexvs.simpleinstructions• RISCvs.CISCvs.HLLmachines

• FFT,QUICKSORT,POLY,FPinstructions?• VAXINDEXinstruction(arrayaccesswithboundschecking)

• e.g.,A[i][j][k]oneinstructionwithboundcheck

39

Page 40: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SEMANTICGAP

40

High-LevelLanguage

ControlSignals

ISA

SemanticGap

Software

Hardware

Page 41: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SEMANTICGAP

41

High-LevelLanguage

ControlSignals

ISASemanticGap

Software

Hardware

CISC

RISC

Page 42: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

ISA-LEVELTRADEOFFS:SEMANTICGAP• WheretoplacetheISA?Semanticgap• Closertohigh-levellanguage(HLL)orclosertohardwarecontrolsignals?à Complexvs.simpleinstructions• RISCvs.CISCvs.HLLmachines

• FFT,QUICKSORT,POLY,FPinstructions?• VAXINDEXinstruction(arrayaccesswithboundschecking)

• Tradeoffs:• Simplecompiler,complexhardwarevs.complexcompiler,simplehardware• Caveat:Translation(indirection)canchangethetradeoff!

• Burdenofbackwardcompatibility• Performance?

• Optimizationopportunity:ExampleofVAXINDEXinstruction:who(compilervs.hardware)putsmoreeffortintooptimization?

• Instructionsize,codesize42

Page 43: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SMALLSEMANTICGAPEXAMPLESINVAX• FINDFIRST

• Findthefirstsetbitinabitfield• HelpsOSresourceallocationoperations

• SAVECONTEXT,LOADCONTEXT• Specialcontextswitchinginstructions

• INSQUEUE,REMQUEUE• Operationsondoublylinkedlist

• INDEX• Arrayaccesswithboundschecking

• STRINGOperations• Comparestrings,findsubstrings,…

• CyclicRedundancyCheckInstruction• EDITPC

• Implementseditingfunctionstodisplayfixedformatoutput

• DigitalEquipmentCorp.,“VAX11780ArchitectureHandbook,” 1977-78.

43

Page 44: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

CISCvs.RISC

44

REPMOVSX:MOVADDCOMPMOVADDJMPX

Whichoneiseasytooptimize?

x86: REP MOVS DEST SRC

Page 45: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SMALLVERSUSLARGESEMANTICGAP• CISCvs.RISC• Complexinstructionsetcomputerà complexinstructions

• Initiallymotivatedby“notgoodenough” codegeneration• Reducedinstructionsetcomputerà simpleinstructions

• JohnCocke,mid1970s,IBM801• Goal:enablebettercompilercontrolandoptimization

• RISCmotivatedby• Memorystalls(noworkdoneinacomplexinstructionwhenthereisamemorystall?)• Whenisthiscorrect?

• Simplifyingthehardwareà lowercost,higherfrequency• Enablingthecompilertooptimizethecodebetter

• Findfine-grainedparallelismtoreducestalls

45

Page 46: MORE Ccr4bd/3330/S2018/slides/20180130--slides-1up.pdfAgenda •Pointer vs array •Using man page •Structure and dynamic allocation •Undefined behavior •Into to instruction

SMALLVERSUSLARGESEMANTICGAP• JohnCockeʼsRISC(largesemanticgap)concept:

• Compilergeneratescontrolsignals:openmicrocode

• AdvantagesofSmallSemanticGap(Complexinstructions)+Denserencodingà smallercodesizeà savesoff-chipbandwidth,bettercachehitrate(betterpackingofinstructions)

+Simplercompiler

• Disadvantages- Largerchunksofworkà compilerhaslessopportunitytooptimize- Morecomplexhardwareà translationtocontrolsignalsandoptimizationneedstobedonebyhardware

• ReadColwelletal.,“InstructionSetsandBeyond:Computers,Complexity,andControversy,” IEEEComputer1985.

46