Microsoft PowerPoint - M02_VerilogHDL02.ppt [호환 모드]

Similar documents
게이트및스위치프리미티브 q predefined primitives v 정의나선언없이사용가능 v 단일출력을가짐 v 모듈내에서만사용가능 Ø initial과 always 구문내부에서는사용불가 Verilog 에서제공되는게이트및스위치프리미티브 n-input gates n-out

Microsoft PowerPoint - DSD02_verilog2a.pptx

Microsoft PowerPoint - hw4.ppt [호환 모드]

Microsoft PowerPoint - DSD02_verilog2b.pptx

Microsoft PowerPoint - DSD03_verilog3b.pptx

wire [n-1:0] a, b, c, d, e, f, g, h; wire [n-1:0] x; // internal wires wire [n-1:0] tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; mux_2to1 mux001 (.x(tmp0),.a(a

Microsoft PowerPoint - Verilog_Summary.ppt

Microsoft PowerPoint - DSD03_verilog3a.pptx

OCW_C언어 기초

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

歯Chap1-Chap2.PDF

Microsoft PowerPoint - hw8.ppt [호환 모드]

슬라이드 1

PowerPoint 프레젠테이션

MAX+plus II Getting Started - 무작정따라하기

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

Microsoft PowerPoint - additional01.ppt [호환 모드]

Microsoft PowerPoint - ch07 - 포인터 pm0415

슬라이드 1

PowerPoint 프레젠테이션

슬라이드 1

Microsoft PowerPoint - verilog문법new.ppt

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

Microsoft PowerPoint - chap05-제어문.pptx

금오공대 컴퓨터공학전공 강의자료

Microsoft Word - logic2005.doc

C# Programming Guide - Types

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

Microsoft PowerPoint - a10.ppt [호환 모드]

<BFACBDC0B9AEC1A6C7AEC0CC5F F E687770>

C++-¿Ïº®Çؼ³10Àå

슬라이드 1

Microsoft PowerPoint - ICCAD_Digital_lec02.ppt [호환 모드]

Microsoft PowerPoint - chap04-연산자.pptx

PowerPoint 프레젠테이션

Microsoft PowerPoint - chap06-2pointer.ppt

Microsoft PowerPoint - C++ 5 .pptx

슬라이드 1

4 CD Construct Special Model VI 2 nd Order Model VI 2 Note: Hands-on 1, 2 RC 1 RLC mass-spring-damper 2 2 ζ ω n (rad/sec) 2 ( ζ < 1), 1 (ζ = 1), ( ) 1

Microsoft PowerPoint - 30.ppt [호환 모드]

프로그래밍개론및실습 2015 년 2 학기프로그래밍개론및실습과목으로본내용은강의교재인생능출판사, 두근두근 C 언어수업, 천인국지음을발췌수정하였음

Microsoft PowerPoint - VHDL08.ppt [호환 모드]

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

<4D F736F F F696E74202D20C1A63036C0E520BCB1C5C3B0FA20B9DDBAB928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Template

Microsoft PowerPoint - chap03-변수와데이터형.pptx

Microsoft PowerPoint - C프로그래밍-chap03.ppt [호환 모드]

PowerPoint Presentation

T100MD+

Microsoft Word - logic2005.doc

K&R2 Reference Manual 번역본

VHDL 기초 VHDL 두원공과대학정보통신미디어계열이무영

tut_modelsim(student).hwp

hwp

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - DSD01_verilog1a.pptx

Microsoft PowerPoint - [2009] 02.pptx

<4D F736F F F696E74202D C61645FB3EDB8AEC7D5BCBA20B9D720C5F8BBE7BFEBB9FD2E BC8A3C8AF20B8F0B5E55D>

chap 5: Trees

학습목차 2.1 다차원배열이란 차원배열의주소와값의참조

adfasdfasfdasfasfadf

Microsoft PowerPoint - 2주차-1차시 (강의자료) ch01 - C Programming 기초 (part 2)

디지털공학 5판 7-8장

PowerPoint 프레젠테이션

Microsoft PowerPoint 세션.ppt

Infinity(∞) Strategy

PowerPoint 프레젠테이션

<BFACBDC0B9AEC1A6C7AEC0CC5F F E687770>

Microsoft PowerPoint - VHDL01_chapter1.ppt [호환 모드]

Slide 1

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

Microsoft PowerPoint - chap12-고급기능.pptx

Microsoft PowerPoint - chap-03.pptx

디지털시스템설계및실습 1. Verilog HDL 문법 한국기술교육대학교전기전자통신공학부 Ver1.0 (2008)1

컴파일러

ºÎ·ÏB

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

Microsoft PowerPoint - Lesson2.pptx

Microsoft PowerPoint - DSD01_verilog1b.pptx

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

목차 배열의개요 배열사용하기 다차원배열 배열을이용한문자열다루기 실무응용예제 C 2

[2010 년디지털시스템설계및실험중간고사 2 답안지 ] 출제 : 채수익 1. (a) (10 pts) Robertson diagram Quotient 와 remainder 의 correction 을뒤로미루는것이 non-restoring division 이다. 즉, q =

4장.문장

Microsoft PowerPoint - chap06-5 [호환 모드]

Data Structure

11장 포인터

CAN-fly Quick Manual

PowerPoint 프레젠테이션

한국기술교육대학교장영조 한국기술교육대학교전기전자통신공학부 1

Microsoft Word - FunctionCall

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

PowerPoint 프레젠테이션

Microsoft PowerPoint - ICCAD_Digital_lec03.ppt [호환 모드]

10 강. 쉘스크립트 l 쉘스크립트 Ÿ 쉘은명령어들을연속적으로실행하는인터프리터환경을제공 Ÿ 쉘스크립트는제어문과변수선언등이가능하며프로그래밍언어와유사 Ÿ 프로그래밍언어와스크립트언어 -프로그래밍언어를사용하는경우소스코드를컴파일하여실행가능한파일로만들어야함 -일반적으로실행파일은다

Microsoft PowerPoint - M07_RTL.ppt [호환 모드]

윈도우즈프로그래밍(1)

chap x: G입력

쉽게

Transcription:

Verilog HDL 을이용한디지털시스템설계및실습 5. 행위수준모델링 Ver1.0 (2008) 1

5.1.1 always 구문 행위수준모델링 조합논리회로와순차논리회로의설계, 설계된회로의시뮬레이션을위한 테스트벤치의작성에사용 always 구문, initial 구문, task, function 내부에사용 always 구문 always [@(sensitivity_list)] begin blocking_or_nonblocking statements; @(sensitivity_list) 는 always 문의실행을제어 sensitivity_list ( 감지신호목록 ) 에나열된신호들중하나이상에변화 (event) 가 발생했을때 always 내부에있는 begin- 블록의실행이트리거됨 begin- 블록은절차형문장들로구성 blocking 할당문또는 nonblocking 할당문에따라실행방식이달라짐 시뮬레이션이진행되는동안무한히반복실행됨 Ver1.0 (2008) 2

5.1.1 always 구문 module sample(a, b, out); 2 입력 OR 게이트 input a, b; output out; reg out; always @(a or b) begin if(a==1 b==1) out = 1; // blocking 할당문 else out = 0; // blocking 할당문 module 코드 5.1 Ver1.0 (2008) 3

5.1.1 always 구문 module dff(clk, din, qout); input clk, din; output qout; reg qout; D 플립플롭 always @(posedge clk) qout <= din; // Non-blocking 할당문 module 코드 5.2 Ver1.0 (2008) 4

5.1.1 always 구문 always 구문의 sensitivity_list ( 감지신호목록 ) 조합논리회로모델링 always 구문으로모델링되는회로의입력신호가모두나열되어야함 일부신호가감지신호목록에서빠지면, 합성이전의 RTL 시뮬레이션결과와 합성후의시뮬레이션결과가다를수있음 함축적감지신호표현 (@*) 을사용가능 순차회로모델링 동기식셋 / 리셋을갖는경우 : 클록신호만포함 비동기식셋 / 리셋을갖는경우 : 클록신호, 셋, 리셋신호를포함 always @(*) // equivalent to @(a or b or c or d or f) y =(a & b) (c & d) f; Ver1.0 (2008) 5

5.1.1 always 구문 module mux21_bad(a, b, sel, out); input [1:0] a, b; input sel; output [1:0] out; reg [1:0] out; 감지신호목록에 sel 이빠진경우 always @(a or b) // sel is omitted if(sel ==0) out = a; else out = b; module 코드 5.3 Ver1.0 (2008) 6

5.1.1 always 구문 always 구문이테스트벤치에사용되는경우 시뮬레이션시간의진행에관련된제어가포함되어야함 그렇지않으면 zero-delay 무한루프 (infinite loop) 가발생되어교착상태 (deadlock) 에빠지게되어시뮬레이션이진행되지않음 always clk = ~clk; // zero-delay infinite loop always #20 clk = ~clk; // 주기가 40ns 인신호 clk 를생성 Ver1.0 (2008) 7

5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; 시뮬레이션이실행되는동안한번만실행 절차형문장들로구성되며, 문장이나열된순서대로실행 논리합성이지원되지않으므로시뮬레이션을위한테스트벤치에사용 initial begin areg = 0; // initialize i i areg for(index = 0; index < size; index = index + 1) memory[index] = 0; //initialize memory word Ver1.0 (2008) 8

5.1.2 initial 구문 시뮬레이션입력벡터생성 initial begin din = 6'b000000; // initialize at time zero #10 din = 6'b011001; // first pattern #10 din = 6'b011011; // second pattern #10 din = 6'b011000; // third pattern #10 din = 6'b001000; // last pattern Ver1.0 (2008) 9

5.1.2 initial 구문 주기신호의생성 module behave; reg a, b; 코드 5.4 initial iti begin // 초기값지정 a = 1'b1; b = 1'b0; always #50 a = ~a; always #100 b = ~b; module Ver1.0 (2008) 10

5.2 절차형할당문 절차형할당문 reg, integer, time, real, realtime 자료형과메모리변수에값을갱신 문장이나열된순서대로실행 (execute) 되어할당문좌변의변수값을 갱신하는소프트웨어적특성 연속할당 : 피연산자값에변화 (event) 가발생할때마다우변의식이평가되고, 그결과값이좌변의 net 를구동 (drive) 하는하드웨어적특성 Blocking 할당문 할당기호 = 을사용 Nonblocking 할당문 할당기호 <= 을사용 Ver1.0 (2008) 11

5.2.1 Blocking 할당문 Blocking 할당문 현재할당문의실행이완료된이후에그다음의할당문이실행되는순차적 흐름을가짐 reg_lvalue = [delay_or_event_operator] expression; initial begin rega = 0; // reg형변수에대한할당 regb[3] = 1; // 단일비트에대한할당 regc[3:5] = 7; // 부분비트에대한할당 mema[address] = 8'hff; // 메모리요소에대한할당 {carry, acc} = rega + regb; // 결합에대한할당 Ver1.0 (2008) 12

5.2.2 Nonblocking 할당문 Nonblocking 할당문 나열된할당문들이순차적흐름에대한 blocking 없이정해진할당스케줄 (assignment scheduling) 에의해값이할당 할당문들은우변이동시에평가된후, 문장의나열순서또는지정된지연 값에따른할당스케줄에의해좌변의객체에값이갱신 동일시점에서변수들의순서나상호의존성에의해할당이이루어져야하는 경우에사용 reg_lvalue <= [delay_or_event_operator] event operator] expression; Ver1.0 (2008) 13

5.2.2 Nonblocking 할당문 module non_blk1; output out; reg a, b, clk; initial begin a = 0; b = 1; clk = 0; always clk = #5 ~clk; always @(posedge clk) begin a <= b; b <= a; module 코드 5.5-(a) module blk1; output out; reg a, b, clk; initial begin a = 0; b = 1; clk = 0; always clk = #5 ~clk; always @(posedge clk) begin a = b; // a=1 b = a; // b=a=1 module 코드 5.5-(b) Ver1.0 (2008) 14

5.2.2 Nonblocking 할당문 Nonblocking 할당문의시뮬레이션결과 Blocking 할당문의시뮬레이션결과 Ver1.0 (2008) 15

5.2.2 Nonblocking 할당문 module non_block2; reg a, b, c, d, e, f; //blocking assignments with intra-assignment delay initial begin a = #10 1; // a will be assigned 1 at time 10 b = #2 0; // b will be assigned 0 at time 12 c = #4 1; // c will be assigned 1 at time 16 //non-blocking assignments with intra-assignment delay initial begin d <= #10 1; // d will be assigned 1 at time 10 e <= #2 0; // e will be assigned 0 at time 2 f <= #4 1; // f will be assigned 1 at time 4 module 코드 5.6 Ver1.0 (2008) 16

5.2.2 Nonblocking 할당문 module non_block3; reg a, b, c, d, e, f; //blocking assignments with delay initial begin #10 a = 1; // a will be assigned 1 at time 10 #2 b = 0; // b will be assigned 0 at time 12 #4 c = 1; // c will be assigned 1 at time 16 //non-blocking assignments with delay initial begin #10 d <= 1; // d will be assigned 1 at time 10 #2 e <= 0; // e will be assigned 0 at time 12 #4 f <= 1; // f will be assigned 1 at time 16 module Ver1.0 (2008) 17

5.2.2 Nonblocking 할당문 non_block2 의시뮬레이션결과 non_block3 의시뮬레이션결과 Ver1.0 (2008) 18

5.2.2 Nonblocking 할당문 Nonblocking 할당문의내부지연 module multiple2; reg a; 코드 5.7 initial a = 1; initial begin a <= #4 1; // schedules a = 1 at time 4 a <= #4 0; // schedules a = 0 at time 4 #20 $stop; // At time 4, a = 0 module Ver1.0 (2008) 19

5.2.2 Nonblocking 할당문 Nonblocking 할당문의내부지연을이용한주기신호의생성 module multiple; reg r1; reg [2:0] i; 코드 5.8 initial begin r1 = 0; for(i = 0; i <= 5; i = i+1) r1 <= #(i*10) i[0]; module Ver1.0 (2008)

5.3 if 조건문 if 조건문 if(expression) statement_true; [else statement_false;] t t 조건식이참 (0 이아닌알려진값 ) 이면, statement_true 부분실행 조건식이거짓 (0, x, z) 이면, statement_false 부분실행 else 부분이없으면, 변수는이전에할당받은값을유지 (latch 동작 ) if 문의내포 (nested) ( 즉, if 문내부에또다른 if 문이있는경우 ) if 문내부에하나이상의 else 문장이생략되는경우, 내부의 else 문은이전의 가장가까운 if 와결합됨 들여쓰기또는 begin 로명확하게표현 Ver1.0 (2008) 21

5.3 if 조건문 if(index > 0) // IF-1 if(rega > regb) // IF-2 result = rega; else // else of the IF-2 result = regb; if(index > 0) begin // IF-1 if(rega > regb) result = rega; // IF-2 else result = regb; // else of the IF-1 Ver1.0 (2008) 22

5.3 if 조건문 module mux21_if(a, b, sel, out); input [1:0] a, b; input sel; output [1:0] out; reg [1:0] out; always @(a or b or sel) if(sel == 1'b0) // 또는 if(!sel) out = a; else out = b; module if 조건문을이용한 2:1 멀티플렉서코드 5.9 Ver1.0 (2008) 23

5.3 if 조건문 비동기 set/reset 을갖는 D 플립플롭 module dff_sr_async(clk, d, rb, sb, q, qb); input clk, d, rb, sb; output q, qb; reg q; always @(posedge clk or negedge rb or negedge sb) begin if(rb==0) q <= 0; else if(sb==0) q <= 1; else q <= d; assign qb = ~q; module 코드 5.10 Ver1.0 (2008) 24

5.3 if 조건문 코드 5.10 의시뮬레이션결과 Ver1.0 (2008) 25

5.4 case 문 case 문 case(expression) case_item {, case_item} : statement_or_null; default [:] statement_or_null; case case 조건식의값과일치하는 case_item 의문장이실행 각비트가 0, 1, x, z 를포함하여정확히같은경우에만일치로판단 case 문의조건식과모든 case_item 의비트크기는큰쪽에맞추어져야함 모든 case_item 들에대한비교에서일치되는항이없는경우에는 default 항이실행 default 항이없으면변수는이전에할당받은값을유지 하나의 case 문에서여러개의 default 를사용하는것은허용되지않음 Ver1.0 (2008) 26

5.4 case 문 case 문을이용한 2:1 멀티플렉서 module mux21_case(a, b, sel, out); input [1:0] a, b; input sel; output [1:0] out; reg [1:0] out; always @(a or b or sel) begin case(sel) 0 : out = a; 1 : out = b; case module 코드 5.11 Ver1.0 (2008) 27

5.4 case 문 reg [15:0] rega; reg [9:0] result; case 문을이용한디코더 always @(rega) begin case(rega) 16'd0: result = 10'b0111111111; 16'd1: result = 10'b1011111111; 16'd2: result = 10'b1101111111; 16'd3: result = 10'b1110111111; 16'd4: result = 10'b1111011111; 16'd5: result = 10'b1111101111; 16'd6: result = 10'b1111110111; 16'd7: result = 10'b1111111011; 16'd8: result = 10'b1111111101; 16'd9: result = 10'b1111111110; default: result = 10'bx; case Ver1.0 (2008) 28

5.4 case 문 case 문을이용한 x 와 z 의처리예 case(select[1:2]) 2'b00 : result = 0; 2'b01 : result = flaga; 2'b0x, 2'b0z : result = flaga? 'bx : 0; 2'b10 : result = flagb; 2'bx0, 2'bz0 : result = flagb? 'bx : 0; default : result = 'bx; case case 문을이용한 x와 z의검출예 case(sig) 1'bz: $display("signal i l is floating"); 1'bx: $display("signal is unknown"); default: $display("signal is %b", sig); case Ver1.0 (2008) 29

5.4 case 문 don't care 를갖는 case 문 casez 문 :z 를 don t - care 로취급하여해당비트를비교에서제외 don't care 조건으로? 기호사용가능 casex 문 : x 와 z 를 don t - care 로취급하여해당비트를비교에서제외 reg [7:0] ir; casez(ir) 8'b1???????: instruction1(ir); 8'b01??????: instruction2(ir); 8'b00010???: instruction3(ir); 8'b000001??: instruction4(ir); case Ver1.0 (2008) 30

5.4 case 문 module pri_enc_casex(encode, enc); input [3:0] encode; output [1:0] enc; reg [1:0] enc; casex 문을이용한 3 비트우선순위인코더 (priority encoder) always @(encode) begin casex(encode) 4'b1xxx : enc = 2'b11; 4'b01xx : enc = 2'b10; 4'b001x : enc = 2'b01; 4'b0001 : enc = 2'b00; case module 코드 5.12 Ver1.0 (2008) 31

5.4 case 문 코드 5.12 의시뮬레이션결과 Ver1.0 (2008) 32

5.4 case 문 module pri_enc_case(encode, enc); input [3:0] encode; output t [1:0] enc; reg [1:0] enc; case 조건식에상수값을사용한 3 비트우선순위인코더 always @(encode) begin case(1) encode[3]: enc = 2'b11; encode[2]: enc = 2'b10; encode[1]: enc = 2'b01; encode[0]: enc = 2'b00; default : $display("error: One of the bits expected ON"); case module 코드 5.13 Ver1.0 (2008) 33

5.5 반복문 반복문 forever 문 : 문장이무한히반복적으로실행 repeat 문 : 지정된횟수만큼문장이반복실행 반복횟수를나타내는수식이 x 또는 z 로평가되면반복횟수는 0 이되고, 문장은실행되지않음 while 문 : 조건식의값이거짓이될때까지문장이반복실행 조건식의초기값이거짓이면문장은실행되지않음 for 문 : 반복횟수를제어하는변수에의해문장이반복실행 forever statement; repeat(expression) statement; while(expression) statement; for(variable_assign); expression; variable_assign) statement; Ver1.0 (2008) 34

5.5 반복문 repeat 문을이용한 shift-add 방식의승산기 module multiplier_8b(opa, opb, result); parameter SIZE = 8, LongSize = 2*SIZE; input [SIZE-1:0] opa, opb; output [LongSize-1:0] result; reg [LongSize-1:0] result, shift_opa, shift_opb; always ays @(opa or opb) begin shift_opa = opa; // multiplicand shift_opb = opb; // multiplier result = 0; repeat(size) begin if(shift_opb[0]) result = result + shift_opa; shift_ opa = shift_ opa << 1; shift_opb = shift_opb >> 1; module d 코드 514 5.14 Ver1.0 (2008) 35

5.5 반복문 코드 5.14 의시뮬레이션결과 Ver1.0 (2008) 36

5.5 반복문 module cnt_one(rega, count); input [7:0] rega; output [3:0] count; reg [7:0] temp_reg; reg [3:0] count; always @(rega) begin count = 0; temp_reg = rega; 8 비트입력 rega 에포함된 1 을계수하는회로 while(temp_reg) begin if(temp_reg[0]) count = count + 1; temp_reg = temp_reg >> 1; module 코드 5.15 Ver1.0 (2008) 37

5.5 반복문 코드 5.15 의시뮬레이션결과 Ver1.0 (2008) 38

5.5 반복문 for 문을이용한 8 비트우선순위인코더 (priority encoder) module enc_for(in, out); input [7:0] in; output [2:0] out; reg [2:0] out; integer i; 입력 in[7:0] 출력 out[2:0] 0000_0001 000 0000_00100010 001 0000_0100 010 0000_1000 011 always @(in) begin : LOOP 0001_0000 100 out=0; 0010_0000 101 for(i = 7; i >= 0; i = i-1) begin 0100_0000 110 if(in[i]) begin 1000_0000 111 out=i; 8비트우선순위인코더 disable LOOP; module 코드 5.16 Ver1.0 (2008) 39

5.5 반복문 코드 5.16 의시뮬레이션결과 Ver1.0 (2008) 40

5.5 반복문 module tb_dff ; reg clk, d; forever 문을이용한주기신호생성 dff U1 (clk, d, q); initial begin clk = 1'b0; forever #10 clk = ~clk; initial begin d = 1'b0; forever begin #15 d = 1'b1; #20 d = 1'b0; #30 d = 1'b1; #20 d = 1'b0; module Ver1.0 (2008) 41

5.6 절차형할당의타이밍제어 절차형할당의실행제어 지연제어 : delay operator : # 특정절차형할당문의실행순서가된시점과그문장이실제실행되는시점 사이의시간간격을지정 ( 문장의실행을지연시킴 ) 지연값이 x 또는 z 인경우에는지연이 0 으로처리 음수지연값이지정된경우에는 2 의보수 unsigned 정수로해석 #10 rega = regb; #d rega = regb; // d is defined as a parameter #((d+e)/2) rega = regb; // delay is average of d and e event 제어 event operator : @ 시뮬레이션 event가발생될때까지문장의실행을지연시킴 net 나변수의값변화가순차문의실행을트리거하기위한 event 로사용가능 Ver1.0 (2008) 42

5.6 절차형할당의타이밍제어 에지천이검출 negedge:1 g 에서 0, x, z로변화, 또는 x, z에서 0으로변화에서 event 발생 posedge:0 에서 x, z, 1 로변화, 또는 x, z 에서 1 로변화에서 event 발생 event 발생수식의결과가 1 비트이상인경우에는, 에지천이는결과의 LSB 에서검출 표 5.1 posedge 와 negedge event 의발생 From To 0 1 x z 0 No edge posedge posedge posedge 1 negedge No edge negedge negedge x negedge posedge No edge No edge z negedge posedge No edge No edge Ver1.0 (2008) 43

5.6 절차형할당의타이밍제어 module dff(clk, d, q); input clk, d; output q; reg q; 상승에지로동작하는 D 플립플롭 always @(posedge clk) q <= d; module 코드 517 5.17 Ver1.0 (2008) 44

5.6 절차형할당의타이밍제어 named event event 자료형으로선언된식별자 순차문의실행을제어하기위한 event 표현에사용 event 가발생될때까지실행이지연됨 named event 는데이터값을유지하지않음 임의의특정한시간에발생될수있음 지속시간을갖지않음 event 제어구문을이용해서 event 의발생을감지할수있음 event list_of_event_identifiers; // event 선언 -> event_identifier; tifi // event trigger Ver1.0 (2008) 45

5.6 절차형할당의타이밍제어 named event 를이용한 D 플립플롭 module ff_event(clock, reset, din, q); input reset, clock, din; output q; reg q; event upedge; // event 선언 always @(posedge clock) -> upedge; always @(upedge or negedge reset) begin if(reset==0) q = 0; else q = din; module 코드 5.18 Ver1.0 (2008) 46

5.6 절차형할당의타이밍제어 코드 5.18 의시뮬레이션결과 Ver1.0 (2008) 47

5.6 절차형할당의타이밍제어 event or 연산자 다수의 event 들은키워드 or 또는콤마 () (,) 로결합 always @(posedge clk_a or posedge clk_b or trig) rega = regb; always @(posedge clk_a, posedge clk_b, trig) rega = regb; wait 문 조건을평가하여참이면 wait 문에속하는절차형할당문이실행되며, 조건이거짓이면절차형할당문의실행이중지 wait(expression) statement_or_null; begin wait(!enable) #10 a = b; #10 c = d; Ver1.0 (2008) 48

5.6 절차형할당의타이밍제어 intra-assignment 타이밍제어 지연과 event 제어가순차할당문안에포함 우변의수식에대한평가를먼저실행한후, 좌변의객체에새로운값이 할당되는시점을지정된지연만큼지연시킴 a <= repeat(5) @(posedge clk) data; Ver1.0 (2008) 49

5.6 절차형할당의타이밍제어 module intra_delay1(clk, lk d, out); input clk, d; output out; reg out; always @(*) out = repeat(3) @(posedge clk) d; module module intra_delay1_eq(clk, d, out); input clk, d; output out; reg out,temp; t always @(*) begin temp = d; @(posedge clk); @(posedge clk); @(posedge clk) out = temp; 등가코드 코드 5.19 module d 코드 520 5.20 Ver1.0 (2008) 50

5.6 절차형할당의타이밍제어 코드 519 5.19 의시뮬레이션결과 Ver1.0 (2008) 51

절차형할당의타이밍제어 Equivalent model of Intra-assignment timing control With intra-assignment construct a = #5 b; a = @(posedge clk) b; a = repeat(3) @(posedge clk) b; Without intra-assignment construct begin temp = b; #5 a = temp; begin temp = b; @(posedge clk) a = temp; begin temp = b; @(posedge clk); @(posedge clk); @(posedge clk) a = temp; Ver1.0 (2008) 52

5.7 블록문 블록문 두개이상의문장을그룹으로묶어구문적으로하나의문장처럼처리 begin- 절차형할당문블록 문장이나열된순서에의해순차적으로실행 시작시간 : 첫번째문장이실행될때 종료시간 : 마지막문장이실행될때 각절차형할당문의실행은이전문장의지연시간에대해상대적으로결정됨 fork-join 병렬문블록 문장의나열순서에무관하게동시에실행 시작시간 : 블록내의모든문장의시작시간이동일 종료시간 : 각문장의지연이고려되어시간적으로마지막에실행되는문장의 실행이완료된시점 각문장의지연은블록에들어가는시뮬레이션시간을기준으로결정됨 시뮬레이션파형생성에유용함 Ver1.0 (2008) 53

5.7 블록문 parameter d = 50; reg [7:0] r; begin // a waveform controlled by sequential delay #d r = 8'h35; #d r = 8'hE2; #d r = 8'h00; #d r = 8'hF7; #d -> _wave; //trigger an event called _wave fork join #50 r = 8'h35; #100 r = 8'hE2; #150 r = 8'h00; #200 r = 8'hF7; #250 -> _wave; 등가코드 fork join #250 -> _wave; #200 r = 8'hF7; #150 r = 8'h00; #100 r = 8'hE2; #50 r = 8'h35; Ver1.0 (2008) 54

Verilog HDL 을이용한디지털시스템설계및실습 6. 구조적모델링 Ver1.0 (2008) 55

6.1 모듈 module module_name (port_list); port 선언 reg 선언 wire 선언 parameter 선언 머리부 선언부 하위모듈인스턴스게이트프리미티브 always 문, initial 문 assign 문 function, task 정의 function, task 호출 몸체 module 그림 6.1 Verilog 모듈의구성 Ver1.0 (2008) 56

6.1.1 모듈포트선언 모듈포트선언 포트목록에나열된포트들은선언부에서포트선언을통해 input, output, inout( 양방향 ) 으로선언 signed와범위에대한정의를포함한포트에관한모든다른속성들이 포트선언에포함될수있음 inout_declaration ::= inout [ net_type type ][ signed ][ range ] list_of_port_identifiers identifiers input_declaration ::= input [ net_type ][ signed ][ range ] list_of_port_identifiers output _ declaration ::= output [ net_type ][ signed ][ range ] ist_of_port_identifiers output [ reg ][ signed ][ range ] list_of_port_identifiers output reg [ signed ][ range ] list_of_variable_port_identifiers output [ output_variable_type ] list_of_port_identifiers output output_variable_type list_of_variable_port_identifiers list_of_port_identifiers ::= port_identifier {, port_identifier } Ver1.0 (2008) 57

6.1.1 모듈포트선언 input aport; // First declaration - okay. input aport; // Error - multiple port declaration output aport; // Error - multiple port declaration module test(a, b, c, d, e, f, g, h); input [7:0] a, b; // no explicit declaration - net is unsigned input signed [7:0] c, d; // no explicit net declaration - net is signed output [7:0] e, f; // no explicit declaration - net is unsigned output signed [7:0] g, h; // no explicit net declaration - net is signed wire signed [7:0] b; // port b inherits signed attribute from net decl. wire [7:0] c; // net c inherits signed attribute from port reg signed [7:0] f; // port f inherits signed attribute from reg decl. reg [7:0] g; // reg g inherits signed attribute from port Ver1.0 (2008) 58

6.1.1 모듈포트선언 module complex_ports({c,d},.e(f)); // Nets {c,d} receive the first port bits. // Name 'f' is declared inside the module. // Name 'e' is defined outside the module. // Can't use named port connections of first port. module split_ports(a[7:4], a[3:0]); // First port is upper 4 bits of 'a'. // Second port is lower 4 bits of 'a'. // Can't use named port connections because of part-select port 'a'. module same_port(.a(i),.b(i)); // Name 'i' is declared inside the module as a inout port. // Names 'a' and 'b' are defined for port connections. Ver1.0 (2008) 59

6.1.1 모듈포트선언 module renamed_concat(.a({b,c}), f,.g(h[1])); // Names 'b', 'c', 'f', 'h' are defined inside the module. // Names 'a', 'f', 'g' are defined for port connections. // Can use named port connections. module same_input(a, a); input a; // This is legal. The inputs are ored together. Ver1.0 (2008) 60

6.1.2 모듈포트선언목록 포트선언목록 포트선언목록에서포트를선언 포트선언목록으로선언된포트들은모듈의선언부에서재선언되지않음 module test( input [7:0] a, input signed [7:0] b, c, d, output [7:0] e, output signed reg [7:0] f, g, output signed [7:0] h ) ; // illegal l to redeclare any ports of the module in the body of the module. Ver1.0 (2008) 61

6.2 모듈인스턴스 구조적모델링 다른모듈의인스턴스와포트매핑을통한모델링 범위지정을통한인스턴스배열의생성가능 모듈인스턴스이름은생략할수없음 게이트프리미티브의인스턴스이름은생략가능 포트순서에의한포트매핑 모듈의포트목록에나열된포트순서와 1:1 로대응되어연결 포트에연결되는신호가없는경우에는해당위치를빈칸으로남겨둔다 포트이름에의한포트매핑 포트이름과그포트에연결되는신호이름을명시적으로지정 포트의비트선택, 부분선택, 결합등을사용할수없음.port_name([expression]) Ver1.0 (2008) 62

6.2 모듈인스턴스 module topmod; wire [4:0] v; wire c, w; modb b1(v[0], v[3], w, v[4]); module 순서에의한포트매핑 (,,, ); 코드 6.3 module modb(wa, wb, c, d); inout wa, wb; input c, d; tranif1 g1(wa, wb, cinvert); not #(2, 6) n1(cinvert, int); and #(6, 5) g2(int, c, d); module module topmod; wire [4:0] v; wire a,b,c,w; 이름에의한포트매핑 modb b1(.wb(v[3]),.wa(v[0]),.d(v[4]),.c(w)); module 코드 6.4 Ver1.0 (2008) 63

6.2 모듈인스턴스 module bus_driver(busin, bushigh, buslow, enh, enl); input [15:0] busin; input enh, enl; output [7:0] bushigh, buslow; driver busar3(busin[15:12], bushigh[7:4], enh); driver busar2(busin[11:8], bushigh[3:0], enh); driver busar1(busin[7:4], buslow[7:4], enl); driver busar0(busin[3:0], buslow[3:0], enl); module 코드 6.2-(a) driver busar[3:0] (.in(busin),.out({bushigh, h buslow}),.en({enh, enh, enl, enl}) ); module 모듈인스턴스의배열을이용 코드 6.2-(b) Ver1.0 (2008) 64

6.2 모듈인스턴스 동일포트에대한다중연결오류 module test; a U0(.i(a),.i(b), // illegal connection of input port twice..o(c),.o(d), // illegal connection of output port twice..e(e),.e(f) // illegal connection of inout port twice. ); module 코드 6.4 Ver1.0 (2008) 65

6.2 모듈인스턴스 a b cin Half Adder temp_sum Half Adder temp_c1 temp_c2 sum cout module half_adder(a, b, sum, cout); input a, b; output sum, cout; wire cout_bar; // 생략가능 (1-bit wire) 반가산기모듈 xor U0 (sum, a, b); nand (cout_bar, a, b); // 인스턴스이름생략가능 (gate primitive) not U1 (cout, cout_bar); module 코드 6.6-(a) Ver1.0 (2008) 66

6.2 모듈인스턴스 module full_adder(a, b, cin, sum, cout); input a, b, cin; output sum, cout; wire temp_sum, temp_c1, temp_c2; // 생략가능 // half_adder 모듈의 instantiation half_adder u0(a, b, temp_sum, temp_c1); // 순서에의한포트연결 half_adder u1(.a(temp_sum),.b(cin),.sum(sum),.cout(temp_c2) ); // 이름에의한포트연결 or u2(cout, temp_ c1, temp_ c2); // 게이트프리미티브인스턴스 module 코드 6.6-(b) Ver1.0 (2008) 67

6.2 모듈인스턴스 // 1 비트 full_adder 모듈의시뮬레이션 testbench module tb_full_adder ; reg a, b, cin; // initial 블록에서값을받으므로 reg 로선언 integer k; // full_adder 모듈의 instantiation full_adder U0(a, b, cin, sum, cout); // 시뮬레이션을위한파형생성 initial begin forever for(k = 0; k < 8; k = k+1) begin cin = k/4; b =(k%4)/2; a = k%2; #10; module 코드 6.7 Ver1.0 (2008) 68

6.2 모듈인스턴스 Ver1.0 (2008) 69

6.2 모듈인스턴스 실수형값의포트연결 real 자료형은직접포트에연결될수없음 시스템함수인 $realtobit와 $bittoreal를통해real 자료형을비트자료형으로변환한후모듈포트에적용 module driver(net_r); output net_r; real r; wire [64:1] net_r = $realtobits(r); module 코드 6.8 module receiver(net_r); r); input net_r; wire [64:1] net_r; real r; initial assign r = $bitstoreal(net_r); module 코드 6.9 Ver1.0 (2008) 70

6.3 모듈 parameter 모듈 parameter variable 또는 net 범주에속하지않는상수 모듈이인스턴스될때값을변경시킬수있음 구조적설계에서모듈인스턴스의개별화 (customize) 를위한유용한수단 localparaml 으로선언된 parameter 는그값을변경할수없음 모듈 parameter 값의변경 defparam 문을이용하는방법 모듈인스턴스를통해 parameter 값을변경하는방법 위의두가지방법에의한 parameter 값변경이충돌되는경우, defparam 문에의해설정된값이사용됨 Ver1.0 (2008) 71

6.3 모듈 parameter 모듈 parameter 값의변경 module foo(a, b); real r1, r2; parameter [2:0] A = 3'h2; // 자료형과범위가지정된 parameter 선언 // 자료형과범위가지정되지않은 parameter 선언 parameter B = 3'h2; // 자료형과범위가지정되지않은 parameter 선언 initial begin r1 = A; r2 = B; $display("r1 is %f, r2 is %f",r1,r2); module 코드 6.10-(a) module bar; // parameter overriding using defparam wire a, b; defparam U0.A = 3.1415; // A는 3으로변경됨 defparam U0.B = 3.1415; // B 는 3.1415 로변경됨 foo U0(a, b); // module instantiation module 코드 6.10-(b) Ver1.0 (2008) 72

6.3 모듈 parameter defparam 문 parameter 의계층적이름을사용하여전체설계에걸친모듈인스턴스의 parameter 값을변경 인스턴스배열의하부계층구조에있는 defparam 문은계층구조밖의 parameter 값을변경시킬수없음 모든 parameter 변경문들을함께묶어독립된모듈로정의할때유용 Ver1.0 (2008) 73

모듈 parameter defparam 문에의한 parameter 값의변경 module top; reg clk; reg [0:4] in1; reg [0:9] in2; wire [0:4] o1; wire [0:9] o2; module vdff(out, in, clk); parameter size = 1, delay = 1; input [0:size-1] in; input clk; output [0:size-1] out; reg [0:size-1] out; vdff m1(o1, in1, clk); vdff m2(o2, in2, clk); module always @(posedge clk) # delay out = in; module module annotate; defparam top.m1.size = 5, top.m1.delay = 10, top.m2.size = 10, top.m2.delay = 20; module 코드 6.10 Ver1.0 (2008) 74

6.3 모듈 parameter 모듈인스턴스의 parameter 값변경 순서화된 parameter 목록에의한방법 (ordered _p parameter_ assignment) #(expression {, expression,} ) parameter 이름에의한방법 (named_parameter_assignment) #(.parameter_name([expression])) 단일모듈인스턴스문에서이들두가지방법을혼용하여사용할수없음 기호 # : delay operator 로도사용됨 Ver1.0 (2008) 75

6.3 모듈 parameter module dffn(q, d, clk); parameter BITS = 1; input [BITS-1:0] d; input clk; output [BITS-1:0] q; 모듈 parameter 값의변경 DFF dff_array [BITS-1:0] (q, d, clk); // instance array module module MxN_pipeline(in, out, clk); parameter M = 3, N = 4; // M=width,N=depth input [M-1:0] in; output [M-1:0] out; input clk; wire [M*(N-1):1] t; // #(M) 은모듈 dffn 의 Parameter BITS 값을재설정 dffn #(M) p [1:N] ({out, t}, {t, in}, clk); module 코드 6.12 Ver1.0 (2008) 76

6.3 모듈 parameter 모듈 parameter 값의변경 Ver1.0 (2008) 77

6.3 모듈 parameter module vdff(out, in, clk); parameter size = 5, delay = 1; input [0:size-1] in; input clk; output [0:size-1] out; reg [0:size-1] out; always @(posedge clk) # delay out = in; // # 은 delay operator 임 module module m; reg clk; wire [0:4] out_c, in_c; wire [1:10] out_a, in_a; wire [1:5] out_b, in_b; 코드 6.13-(a) vdff #(10,15) mod_a(out_a, in_a, clk); vdff mod_b(out_b, in_b, clk); // default parameter values vdff #(.delay(12)) mod_c(out_c, in_c, clk); module d 코드 613(b) 6.13-(b) Ver1.0 (2008) 78

6.4 생성문 생성문 (Generate statement) generate-generate g 블록으로모델링 반복생성문 (generate-for) 조건생성문 (generate-if) case 생성문 (generate-case) 모듈, 사용자정의프리미티브 (UDP), 게이트프리미티브, 연속할당문, initial 블록과 always 블록등의인스턴스를하나또는다수개생성 net, reg, integer, real, time, realtime, event 등의자료형선언가능 생성된인스턴스와자료형은고유의식별자를가지며계층적으로참조가능 순서또는이름에의한 parameter 값의변경또는 defparam 문에의한 parameter 재정의가능 defparam 문은생성범위내에서선언된 parameter 의값에만영향을미침 생성문에서 parameter, local parameter, input, output, inout, specify block 등의선언은허용되지않음 Ver1.0 (2008) 79

6.4.1 genvar 선언 genvar 선언 생성문내에서만사용될수있는인덱스변수의선언에사용 genvar 로선언되는변수는정수형 선언된변수를인덱스로갖는반복생성문내에서만사용되는지역변수 genvar 의값은 parameter 값이참조될수있는어떤문장에서도참조가능 시뮬레이터또는논리합성툴의 elaboration 과정동안에만정의되며, 시뮬레이션또는합성이진행되는동안에는존재하지않음 elaboration 과정 : 시뮬레이션이나합성을위해모듈을분석하는과정 구문의오류검출, 인스턴스된모듈의연결 (link), parameter 값의전달, 계층적인참조에대한분해등을수행하는과정 Ver1.0 (2008) 80

6.4.2 반복생성문 반복생성문 (generate-for 문 ) generate-generate g 구문내부에 for 문을사용하여특정모듈또는 블록을반복적으로인스턴스 variable 선언, 모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, always 블록등을인스턴스할수있음 생성문내부의 for-loop에서사용되는인덱스변수는 genvar로선언 for 문의 begin 뒤에생성문블록식별자 (:identifier) 를붙여야함 Ver1.0 (2008) 81

6.4.2 반복생성문 표 6.2 순환 2 진부호 (gray code) 와이진부호 10 진수순환 2 진부호이진부호 0 0000 0000 1 0001 0001 2 0011 0010 3 0010 0011 4 0110 0100 5 0111 0101 6 0101 0110 7 0100 0111 8 1100 1000 9 1101 1001 Ver1.0 (2008) 82

6.4.2 반복생성문 generate-for 문을이용한 gray-to-binary 변환기 module gray2bin1(bin, gray); parameter SIZE = 4; // this module is parameterizable output [SIZE-1:0] bin; input [SIZE-1:0] gray; genvar i; generate for(i=0; i<size; i=i+1) begin :bit assign bin[i] = ^gray[size-1:i]; generate module 코드 6.14 Ver1.0 (2008) 83

6.4.2 반복생성문 module gray2bin2(bin, gray); parameter SIZE = 4; output [SIZE-1:0] bin; input [SIZE-1:0] gray; reg [SIZE-1:0] bin; genvar i; generate-for 문을이용한 gray-to-binary 변환기 generate for(i=0; i<size; i=i+1) begin :bit always @(gray[size-1:i]) bin[i] = ^gray[size-1:i]; generate module 코드 615 6.15 Ver1.0 (2008) 84

6.4.2 반복생성문 generate-for 문을이용한 gray-to-binary 변환기 Ver1.0 (2008) 85

6.4.2 반복생성문 참고사항 : always 문을사용하는경우, error 발생 module gray2bin_error (bin, gray); parameter SIZE = 4; output [SIZE-1:0] bin; input [SIZE-1:0] gray; reg [SIZE-1:0] bin, tmp; integer i; always @(gray) begin tmp = gray; for (i=0; i<size; i=i+1) bin[i] = ^tmp[size-1:i]; // i should be constant module always 문을사용하는경우의올바른코드는? Ver1.0 (2008) 86

6.4.2 반복생성문 생성루프외부에 2 차원 net 선언을갖는 ripple-carry 가산기 module adder_gen1(co, sum, a, b, ci); parameter SIZE = 4; output [SIZE-1:0] sum; output co; input [SIZE-1:0] a, b; input ci; wire [SIZE :0] c; wire [SIZE-1:0] t [1:3]; // 2차원 net 선언 genvar i; assign c[0] = ci; generate for(i=0; i<size; i=i+1) begin :bit xor g1( t[1][i], a[i], b[i]); xor g2( sum[i], t[1][i], c[i]); and g3( t[2][i], a[i], b[i]); and g4( t[3][i], ], t[1][i], ], c[i]); or g5( c[i+1], t[2][i], t[3][i]); generate assign co = c[size]; module 코드 6.16 Ver1.0 (2008) 87

6.4.2 반복생성문 생성루프내부에 2 차원 net 선언을갖는 ripple-carry 가산기 module adder_gen2(co, sum, a, b, ci); parameter SIZE = 4; output [SIZE-1:0] sum; output co; input [SIZE-1:0] a, b; input ci; wire [SIZE :0] c; genvar i; assign c[0] = ci; generate for(i=0; i<size; i=i+1) begin :bit wire t1, t2, t3; // generated net declaration xor g1( t1, a[i], b[i]); xor g2( sum[i], t1, c[i]); and g3( t2, a[i], b[i]); and g4( t3, t1, c[i]); or g5( c[i+1], t2, t3); generate assign co = c[size]; module 코드 6.17 Ver1.0 (2008) 88

6.4.2 반복생성문 code 6.16, code 6.17 의시뮬레이션결과 Ver1.0 (2008) 89

6.4.3 조건생성문 조건생성문 (generate-if 문 ) generate-generate generate 블록내에 if-else-if 의조건문을 사용하여조건에따라특정모듈또는블록을선택적으로인스턴스 모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, always 블록등을 인스턴스할수있음 인스턴스가선택되는조건은 elaboration 되는시점에서의값에의해결정 Ver1.0 (2008) 90

6.4.3 조건생성문 if 생성문을이용한파라미터화된곱셈기 module multiplier(a, b, product); parameter a_width = 8, b_width = 8; localparam product_width = a_width+b_width; // can not be modified d directly with defparam or // module instance statement # input [a_width-1:0] a; input [b_ width-1:0] b; output [product_width-1:0] product; generate if((a_width idth < 8) (b_width < 8)) CLA_mul #(a_width, b_width) u1(a, b, product); // instance a CLA multiplier else WALLACE_mul #(a_width, b_width) u1(a, b, product); // instance a Wallace-tree multiplier generate module d 코드 619 6.19 Ver1.0 (2008) 91

6.4.4 case 생성문 case 생성문 (generate-case 문 ) generate-generate generate 블록내에 case 문을사용하여조건에따라 특정모듈또는블록을선택적으로인스턴스 모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, always 블록등을 인스턴스할수있음 인스턴스가선택되는조건은 elaboration 되는시점에서의값에의해결정 Ver1.0 (2008) 92

6.4.4 case 생성문 3 이하의비트폭을처리하기위한 case 생성문 generate case(width) 1: adder_1bit x1(co, sum, a, b, ci); // 1-bit adder 2: adder_2bit x1(co, sum, a, b, ci); // 2-bit adder default: adder_cla #(WIDTH) x1(co, sum, a, b, ci); // carry look-ahead adder case generate 코드 6.20 Ver1.0 (2008) 93

Verilog HDL 을이용한디지털시스템설계및실습 7. task 와함수 Ver1.0 (2008) 94

7.1 Task 와함수 Task 와함수 장점 종류 반복되는행위수준모델링부분을독립된코드의 task 나함수 (function) 로 정의하고, 이들을호출하여사용 규모가큰행위수준모델링을작은부분들로분할하여 task 또는함수로 표현함 소스코드의가독성 (readability) 과디버깅을용이하게함 사용자정의 task, 함수 시스템 task, 함수 Ver1.0 (2008) 95

7.1 Task 와함수 Function 적어도 1 개이상의 input 인수가필요 output, inout 인수를가질수없음 항상 1개의결과값을 return 함 함수명을통해값을 return zero delay 를갖는조합회로구현다른 function 호출가능 (task는불가) zero simulation delay Task 0 개이상의 input, output, inout 인수포함 값을 return 하지않을수있음 output, inout 을통해다수개의값을 return delay, timing, event 를갖고, multiple output 을반환하는 source code 에적용가능 task 의 I/O 에정의되지않은 module 내 reg로선언된변수 access 가능 다른 task 나 function 호출가능 non-zero simulation time 수행가능 delay, event, timing control 문포함불가 delay, event, timing control 문포함가능 variable 자료형만가질수있으며, net 자료형은가질수없음 assign 문, 게이트프리미티브와모듈인스턴스는사용할수없음 initial 문과 always 문을포함할수없음 bh behavioral 문만포함가능함 Ver1.0 (2008) 96

7.1 Task 와함수 function 과 task 의정의및호출 module test (..); function [n-1:0] func_name; // 함수정의 input ; // 인수순서중요. begin. func_name = ;. function... = func_name( ); name( // 함수호출 module module test (..); task task_name; //task 정의 input ; // 인수순서중요 output.; inout ;. begin.. task. task_name( ); // task 호출 module Ver1.0 (2008) 97

7.2 Task Task 의정의 task task_identifier(task_port_list); {block_item_declaration} statement; task task task_identifier; {task_item_declaration} // task 의입력, 출력인수를선언 statement; task Task 의호출 task_enable ::= task_identifier [(expression {, expression} )]; 인수의순서는 task 정의에서선언된인수목록의순서와일치되어야함 Ver1.0 (2008) 98

7.2 Task task my_task; 선언부에서인수를선언 input a, b; inout c; output d, e; begin... // task의기능을수행하는문장들 task c = foo1; // 결과값을 reg 변수에할당하는문장들 d = foo2; e = foo3; task my_task(input a, b, inout c, output d, e); begin... // task 의기능을수행하는문장들 my_task(v, w, x, y, z); // 인수는순서대로매핑 task 호출문 Ver1.0 (2008) 99

7.2 Task module bit_counter (data_word, bit_count); input [7:0] data_word; output [3:0] bit_ count; reg [3:0] bit_count; always @(data_word) count_ ones(data_ word, bit_ count); // task 호출 task count_ones; input [7:0] reg_a; // 인수가여러개인경우, 순서가중요함. output [3:0] count; reg [3:0] count; reg [7:0] temp_reg; begin count=0; temp_reg=reg_a; while (temp_reg) begin if (temp_reg[0]) count=count+ 1; temp_reg = temp_reg >> 1; task module 코드 7.1 Ver1.0 (2008) 100

7.2 Task 코드 7.1 의시뮬레이션결과 Ver1.0 (2008) 101

7.2 Task module traffic_lights; reg clock, red, amber, green; parameter on = 1, off = 0, red_tics = 350, //initialize colors. initial red = off; initial amber = off; initial green = off; amber_tics = 30, green_tics = 200; always begin // sequence to control the lights. red = on; // turn red light on and wait. light(red, red_tics); green = on; // turn green light on and wait. light(green, green_tics); amber = on; // turn amber light on and wait. light(amber, amber_tics); 코드 72 7.2 Ver1.0 (2008) 102

7.2 Task // task to wait for 'tics' positive edge clocks before turning 'color' light off. task light; output color; input [31:0] tics; begin repeat(tics) @(posedge clock); color = off; // turn light off. task always begin // waveform for the clock. #100 clock = 0; #100 clock = 1; module 코드 7.2 Ver1.0 (2008) 103

7.3 함수 함수의정의 function [signed][range_type] function_identifier(function_port_list); {block_item_declaration} statement; function function [signed][range_type] function_identifier ; {function_item_declaration} statement; function 함수결과값의속성및범위지정 : [signed][range_type] ] 별도의지정이없으면, default 로 1 비트 reg 형이됨 함수가정의되면함수이름과동일한이름의변수가함수내부에선언됨 함수가정의되는영역에서함수이름과동일한이름의다른객체를선언하는 것이허용되지않음 Ver1.0 (2008) 104

7.3 함수 함수의호출 ftn_call ::= hierarchical_ftn_identifier{attribute_inst}(expr {,expr}) 함수의규칙 함수는적어도하나이상의입력인수를포함해야한다. 함수는 output 과 inout 으로선언된어떠한인수도가질수없다. 함수는시간제어문장을가질수없다. 함수내부의어떠한구문도타이밍제어 (#, @ 또는 wait 등 ) 를포함할수없다. 함수는 task 를호출할수없다. 함수는함수이름과동일한이름의내부변수에함수의결과값을할당하는 문장을포함한다. 함수는 nonblocking 할당을가질수없다. Ver1.0 (2008) 105

7.3 함수 function [7:0] getbyte; 선언부에서인수를선언 input [15:0] address; begin // code to extract low-order byte from addressed word function... getbyte = result_expression; function [7:0] getbyte(input [15:0] address); begin // code to extract low-order byte from addressed word... getbyte = result_expression; function word = control? {getbyte(msbyte), t b t getbyte(lsbyte)}:0; t b t 함수호출 Ver1.0 (2008) 106

7.3 함수 module word_aligner (word_in, word_out); input [7:0] word_in; output [7:0] word_ out; function [7:0] word_align; input [7:0] word; begin word_align = word; if (word_align!= 0) while (word _ align[7] == 0) word_ align=word _ align << 1; function assign word_out = word_align (word_in); // 함수호출 module 코드 7.3 Ver1.0 (2008) 107

7.3 함수 코드 7.3 의시뮬레이션결과 Ver1.0 (2008) 108

7.3 함수 module tryfact; // define the function function automatic integer factorial; input [31:0] operand; integer i; if(operand >= 2) factorial = factorial(operand - 1) * operand; else factorial = 1; function 0 factorial=1 // test the function 1 factorial=1 integer result; 2 factorial=2 integer n; 3 factorial=6 initial begin 4 factorial=24 for(n = 0; n <= 7; n = n+1) begin 5 factorial=120 result = factorial(n); 6 factorial=720 $display("%0d factorial=%0d", n, result); 7 factorial=5040 module 코드 7.4 Ver1.0 (2008) 109

Verilog HDL 을이용한디지털시스템설계및실습 8. 컴파일러지시어 Ver1.0 (2008) 110

컴파일러지시어 컴파일러지시어 (Compiler directive) Verilog 소스코드의컴파일과정에영향을미치는명령어 accent grave 문자 ( ` ) 로시작된위치에서부터다른컴파일러지시어에 의해대체되거나또는컴파일이완료되기까지전체소스파일에영향을미침 단일인용부호 ( ' ) 와혼동하지않도록주의 표 8.1 Verilog 컴파일러지시어 celldefine default_ nettype define else elsif celldefine if ifdef ifndef include line nounconnected_drive resetall timescale unconnected_drive undef Ver1.0 (2008) 111

8.1 `define 과 `undefine define 문자치환을위한문자매크로생성에사용 C 프로그래밍언어의 #define 과유사 문자매크로치환 자주사용되는문자또는상수를의미있는이름으로정의하고, 문자매크로 치환을통해정의된값을사용 특정상수 ( 비트폭, 지연등 ) 가회로모델링전체에걸쳐반복적으로사용되는 경우에, 문자매크로정의를사용하면소스코드의수정및관리가용이 macro_name 을이용하여소스코드에사용 인수를갖는문자매크로를정의할수있으며, 매크로사용의개별화가가능 define wait_state 3'b010 // No semicolon Ver1.0 (2008) 112

8.1 `define 과 `undefine text_macro_definition ::= 문자매크로정의 define text_macro_name macro_text text_macro_name ::= text_macro_identifier [ ( list_of_formal_arguments ) ] list_of_formal_arguments ::= formal_argument_identifier {, formal_argument_identifier } text_macro_identifier ::= simple_identifieridentifier text_macro_usage ::= text_macro_identifier t tifi [ ( list_of_actual_arguments t l t ) ] list_of_actual_arguments ::= actual_argument {, actual_argument } actual_argument argument ::= expression 문자매크로사용 Ver1.0 (2008) 113

8.1 `define 과 `undefine define wordsize 8 reg [1: wordsize] data; //define a nand with variable delay define var_nand(dly) nand #dly 인수를갖는문자매크로 var_nand(2) g121(q21, n10, n11); var_nand(5) g122(q22, n10, n11); Ver1.0 (2008) 114

8.1 `define 과 `undefine undefine 이전에정의된문자매크로를해제 'define 으로정의되지않은문자매크로에대해 undef 를정의하면컴파일 시경고메시지가출력 undefine_compiler_directive ::= undef text_macro_identifier ifi Ver1.0 (2008) 115

8.2 `ifdef, `else, `elsif 등 ifdef, 'else, 'elsif, 'if, 'ifndef Verilog HDL 소스코드의일부를조건적으로컴파일하기위해사용 소스의어느곳에서든사용될수있음 모듈에대한여러가지 ( 행위적모델링, 구조적모델링, 스위치수준모델링등 ) 모델링중하나를선택하여컴파일하는경우 여러가지의타이밍정보나구조적정보 ( 비트폭등 ) 중하나를선택하여 컴파일하는경우 시뮬레이션을위해여러가지입력벡터들중하나를선택하는경우 ifdef 매크로이름이정의되어있으면, ifdef 이후의소스코드가컴파일에포함 매크로이름이정의되어있지않고 else 가있으면, else 이후의소스코드가 if 컴파일에포함 조건적으로컴파일되는소스코드의경계를나타냄 Ver1.0 (2008) 116

8.2 `ifdef, `else, `elsif 등 ifndef 매크로이름이정의되어있지않으면, ifndef 이후의코드가컴파일에포함 매크로이름이정의되어있고 else 지시어가있으면, else 이후의코드가 컴파일에포함 conditional_compilation_directive ::= ifdef_directive ifndef_directive ifdef_directive ::= ifdef text_macro_identifier ifdef_group_of_lines { elsif text_macro_identifier elsif_group_of_lines } [ else else_group_of_lines of lines ] if ifndef_directive ::= ifndef text_macro_identifier ifndef_group_of_lines { elsif text_macro_identifier elsif_group_of_lines } [ else else_group_of_lines ] if Ver1.0 (2008) 117

8.2 `ifdef, `else, `elsif 등 module and_op(a, b, c); output a; input b, c; ifdef behavioral wire a = b & c; else and a1(a,b,c); if module d 코드 81 8.1 Ver1.0 (2008) 118

8.2 `ifdef, `else, `elsif 등 module test(out); output out; define wow define nest_one define second_nest define nest_two ifdef wow initial $display( wow is defined ); ifdef nest_one initial $display( nest_one is defined ); ifdef nest_two initial $display( nest_two two is defined ); else initial $display( nest_two is not defined ); if else initial $display( nest_one is not defined ); if else initial $display( wow is not defined ); ifdef second_nest initial $display( nest_two is defined ); else initial $display( nest_two is not defined ); if if module 코드 82 8.2 Ver1.0 (2008) 119

8.3 `include include 파일삽입컴파일러지시어 소스파일의내용전체를다른소스파일에포함시켜컴파일할때사용 자주사용되는정의나 task 등을별도의파일에만든후, 컴파일과정에서 포함시킬때사용 Verilog 소스코드내의어느곳에서든지정의될수있음 삽입되는파일은또다른 include 컴파일러지시어를포함할수있음 설계전체에대한구성관리를통합적으로처리할수있음 Verilog 소스코드의효율적인구성및관리가능 include_compiler_directive ::= include filename include parts/count.v include fileb // including fileb Ver1.0 (2008) 120

8.6 `timescale timescale 시간과지연값의측정단위와정밀도를지정 다른 timescale 지시어가나타나기전까지효력을유지 timescale_compiler_directive ::= timescale time_unit / time_precision 표 8.2 시간정밀도단위 Character string s ms us ns ps fs Unit of measurement seconds milliseconds microseconds nanoseconds picoseconds femtoseconds Ver1.0 (2008) 121

8.6 `timescale timescale 1 ns / 1 ps timescale 10 us / 100 ns timescale 10 ns / 1 ns module test; reg set; parameter d = 1.55; //16ns의지연으로변환 initial begin #d set = 0; //16ns에서 set에 0이할당 #d set = 1; //32ns에서 set에 1이할당 module 코드 8.3 Ver1.0 (2008) 122

8.6 `timescale Timescale directive (unit/precision) Delay specification Simulator time step delay value used in sim. Conversion 1 ns / ns #4 1 ns 4 ns 4 x 1 1 ns / 100 ps #4 100 ps 4.0 ns 4 x 1 10 ns / 100 ps #4 100 ps 40.00 ns 4 x 10 10 ns / ns #4 1 ns 40 ns 4 x 10 100 ns / ns #4 1ns 400 ns 4 x 100 10 ns / 100 ps #4.629 100 ps 46.3 ns round 46.29 to 46.3 10 ns / 1 ns #4.629 1 ns 46 ns round 46.29 to 46 10 ns / 10 ns #4.629 10 ns 50 ns round 46.29 to 50 Ver1.0 (2008) 123