123
Verilog HDL을 이용한 디지털시스템 설계 및 실습 5 행위수준 모델링 5. 행위수준 모델링 Ver1.0 (2008) 1 한국기술교육대학교 정보기술공학부

5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

Verilog HDL을이용한디지털시스템설계및실습

5 행위수준 모델링5. 행위수준 모델링

Ver1.0 (2008)1한국기술교육대학교 정보기술공학부

Page 2: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.1 always 구문행위수준모델링

조합논리회로와순차논리회로의설계, 설계된회로의시뮬레이션을위한리회 와 차 리회 의 계, 계 회 의시 레이 위

테스트벤치의작성에사용

always 구문, initial 구문, task, function 내부에사용

always 구문

always [@(sensitivity_list)] begin

@(sensitivity list)는 always문의실행을제어

blocking_or_nonblocking statements;end

@(sensitivity_list)는 always 문의실행을제어sensitivity_list (감지신호목록)에나열된신호들중하나이상에변화(event)가발생했을때 always 내부에있는 begin-end 블록의실행이트리거됨begin-end 블록은절차형문장들로구성blocking 할당문또는 nonblocking할당문에따라실행방식이달라짐시뮬레이션이진행되는동안무한히반복실행됨

Ver1.0 (2008)2

시뮬레이션이진행되는동안무한히반복실행됨

한국기술교육대학교 정보기술공학부

Page 3: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.1 always 구문

module sample(a b out); 2입력OR게이트module sample(a, b, out);input a, b;output out;reg out;

2입력OR 게이트

g ;

always @(a or b) beginif(a==1 || b==1) out = 1; // blocking 할당문else out = 0; // blocking 할당문

endendmodule 코드 5.1

Ver1.0 (2008)3한국기술교육대학교 정보기술공학부

Page 4: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.1 always 구문

module dff(clk, din, qout);input clk, din;

D 플립플롭

output qout;reg qout;

always @(posedge clk)qout <= din; // Non-blocking 할당문

endmodule 코드 5.2

Ver1.0 (2008)4한국기술교육대학교 정보기술공학부

Page 5: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.1 always 구문always 구문의 sensitivity_list (감지신호목록)조합논리회로모델링조합논리회로모델링

always 구문으로모델링되는회로의입력신호가모두나열되어야함일부신호가감지신호목록에서빠지면, 합성이전의 RTL 시뮬레이션결과와합성후의시뮬레이션결과가다를수있음

함축적감지신호표현 (@*)을사용가능

순차회로모델링순차회로모델링

동기식셋/리셋을갖는경우 : 클록신호만포함비동기식셋/리셋을갖는경우 : 클록신호, 셋, 리셋신호를포함

always @(*) // equivalent to @(a or b or c or d or f)always @(*) // equivalent to @(a or b or c or d or f)y =(a & b) |(c & d) | f;

Ver1.0 (2008)5한국기술교육대학교 정보기술공학부

Page 6: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.1 always 구문module mux21_bad(a, b, sel, out);

input [1:0] a, b;input sel;

감지신호목록에 sel이빠진경우p

output [1:0] out;reg [1:0] out;

always @(a or b) // sel is omittedyif(sel ==0)

out = a;else

out = b;endmodule 코드 5.3

Ver1.0 (2008)6한국기술교육대학교 정보기술공학부

Page 7: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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한국기술교육대학교 정보기술공학부

Page 8: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.2 initial 구문initial 구문

initial beginblocking_or_nonblocking statements;

end

시뮬레이션이실행되는동안한번만실행

절차형문장들로구성되며, 문장이나열된순서대로실행,논리합성이지원되지않으므로시뮬레이션을위한테스트벤치에사용

initial begin0 // i i i liareg = 0; // initialize areg

for(index = 0; index < size; index = index + 1)memory[index] = 0; //initialize memory word

end

Ver1.0 (2008)8

end

한국기술교육대학교 정보기술공학부

Page 9: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.2 initial 구문

시뮬레이션입력벡터생성

initial begindin = 6'b000000; // initialize at time zero

#10 din = 6'b011001; // first pattern#10 din = 6 b011001; // first pattern#10 din = 6'b011011; // second pattern#10 din = 6'b011000; // third pattern#10 din = 6'b001000; // last pattern#10 din 6 b001000; // last pattern

end

Ver1.0 (2008)9한국기술교육대학교 정보기술공학부

Page 10: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.1.2 initial 구문주기신호의생성

module behave;reg a, b;

i iti l b i // 초기값 지정

코드 5.4

initial begin // 초기값 지정a = 1'b1;b = 1'b0;

end

always #50 a = ~a;

always #100 b = ~b;

endmodule

Ver1.0 (2008)10한국기술교육대학교 정보기술공학부

Page 11: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2절차형할당문절차형할당문

reg integer time real realtime자료형과메모리변수에값을갱신reg, integer, time, real, realtime 자료형과메모리변수에값을갱신문장이나열된순서대로실행(execute)되어할당문좌변의변수값을갱신하는소프트웨어적특성

연속할당 : 피연산자값에변화(event)가발생할때마다우변의식이평가되고, 그결과값이좌변의 net를구동(drive)하는하드웨어적특성

Bl ki 할당문Blocking 할당문할당기호 =을사용

Nonblocking할당문Nonblocking 할당문할당기호 <=을사용

Ver1.0 (2008)11한국기술교육대학교 정보기술공학부

Page 12: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.1 Blocking 할당문Blocking 할당문

현재할당문의실행이완료된이후에그다음의할당문이실행되는순차적현재할당문의실행이완료된이후에그다음의할당문이실행되는순차적

흐름을가짐

reg_lvalue = [delay_or_event_operator] expression;

initial begingrega = 0; // reg형 변수에 대한 할당

regb[3] = 1; // 단일 비트에 대한 할당

regc[3:5] = 7; // 부분 비트에 대한 할당

mema[address] = 8'hff; // 메모리 요소에 대한 할당

{carry, acc} = rega + regb; // 결합에 대한 할당

end

Ver1.0 (2008)12한국기술교육대학교 정보기술공학부

Page 13: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문Nonblocking 할당문나열된할당문들이순차적흐름에대한 blocking없이정해진할당스케줄나열된할당문들이순차적흐름에대한 blocking 없이정해진할당스케줄(assignment scheduling)에의해값이할당할당문들은우변이동시에평가된후, 문장의나열순서또는지정된지연값에따른할당스케줄에의해좌변의객체에값이갱신

동일시점에서변수들의순서나상호의존성에의해할당이이루어져야하는

경우에사용

reg lvalue <= [delay or event operator] expression;reg_lvalue <= [delay_or_event_operator] expression;

Ver1.0 (2008)13한국기술교육대학교 정보기술공학부

Page 14: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문

module non_blk1;output out;reg a b clk;

module blk1;output out;reg a b clk;reg a, b, clk;

initial begina = 0;b 1

reg a, b, clk;

initial begina = 0;b 1b = 1;

clk = 0;end

l lk #5 lk

b = 1;clk = 0;

end

l lk #5 lkalways clk = #5 ~clk;

always @(posedge clk) begin a <= b;

always clk = #5 ~clk;

always @(posedge clk) begin a = b; // a=1

b <= a;end

endmodule

b = a; // b=a=1end

endmodule코드 5.5-(a) 코드 5.5-(b)

Ver1.0 (2008)14한국기술교육대학교 정보기술공학부

Page 15: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문Nonblocking 할당문의시뮬레이션결과

Blocking 할당문의시뮬레이션결과

Ver1.0 (2008)15한국기술교육대학교 정보기술공학부

Page 16: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문

module non_block2;reg a b c d e f;reg a, b, c, d, e, f;

//blocking assignments with intra-assignment delayinitial begin

a = #10 1; // a will be assigned 1 at time 10b = #2 0; // b will be assigned 0 at time 12b = #2 0; // b will be assigned 0 at time 12c = #4 1; // c will be assigned 1 at time 16

end//non-blocking assignments with intra-assignment delayinitial begininitial begin

d <= #10 1; // d will be assigned 1 at time 10e <= #2 0; // e will be assigned 0 at time 2f <= #4 1; // f will be assigned 1 at time 4

dendendmodule 코드 5.6

Ver1.0 (2008)16한국기술교육대학교 정보기술공학부

Page 17: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문

module non_block3;reg a, b, c, d, e, f;

//blocking assignments with delay//blocking assignments with delayinitial 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#4 c = 1; // c will be assigned 1 at time 16

end//non-blocking assignments with delayinitial begin

#10 d <= 1; // d will be assigned 1 at time 10#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

endendmoduleendmodule

Ver1.0 (2008)17한국기술교육대학교 정보기술공학부

Page 18: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문non_block2의시뮬레이션결과

non_block3의시뮬레이션결과

Ver1.0 (2008)18한국기술교육대학교 정보기술공학부

Page 19: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문Nonblocking 할당문의내부지연

module multiple2;reg a;

initial a = 1;

코드 5.7

initial begina <= #4 1; // schedules a = 1 at time 4a <= #4 0; // schedules a = 0 at time 4#20 $stop; // At time 4, a = 0

endendmodule

Ver1.0 (2008)19한국기술교육대학교 정보기술공학부

Page 20: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.2.2 Nonblocking 할당문Nonblocking 할당문의내부지연을이용한주기신호의생성

module multiple;reg r1;reg [2:0] i;

코드 5.8

initial beginr1 = 0;for(i = 0; i <= 5; i = i+1)

r1 <= #(i*10) i[0];end

endmodule

Ver1.0 (2008)20한국기술교육대학교 정보기술공학부

Page 21: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.3 if 조건문if 조건문

if(expression)statement_true;

[elset t t f l ]

조건식이참 (0이아닌알려진값 )이면, statement_true 부분실행

statement_false;]

조건식이거짓 (0, x, z)이면, statement_false 부분실행else 부분이없으면, 변수는이전에할당받은값을유지 (latch 동작)if문의내포( t d) (즉 if문내부에또다른 if문이있는경우)if 문의내포(nested) (즉, if 문내부에또다른 if 문이있는경우)

if 문내부에하나이상의 else 문장이생략되는경우, 내부의 else 문은이전의가장가까운 if와결합됨들여쓰기또는 begin – end로명확하게표현

Ver1.0 (2008)21한국기술교육대학교 정보기술공학부

Page 22: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.3 if 조건문

if(index > 0) // IF-1if(rega > regb) // IF-2if(rega > regb) // IF 2

result = rega;else // else of the IF-2

result = regb;

if(index > 0) begin // IF-1if(rega > regb)

result = rega; // IF-2endelse result = regb; // else of the IF-1

Ver1.0 (2008)22한국기술교육대학교 정보기술공학부

Page 23: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.3 if 조건문module mux21_if(a, b, sel, out);

input [1:0] a, b;input sel;input sel;output [1:0] out;reg [1:0] out;

always @(a or b or sel)always @(a or b or sel)if(sel == 1'b0) // 또는 if(!sel)

out = a;else

out = b;out = b;endmodule 코드 5.9if 조건문을이용한 2:1 멀티플렉서

Ver1.0 (2008)23한국기술교육대학교 정보기술공학부

Page 24: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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;

elseq <= d;

end

assign qb = ~q;g q q

endmodule 코드 5.10

Ver1.0 (2008)24한국기술교육대학교 정보기술공학부

Page 25: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.3 if 조건문

코드 5.10의시뮬레이션결과

Ver1.0 (2008)25한국기술교육대학교 정보기술공학부

Page 26: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문case 문

case(expression)case_item {, case_item} : statement_or_null;| default [:] statement_or_null;d

case 조건식의값과일치하는 case_item의문장이실행

endcase

각비트가 0, 1, x, z를포함하여정확히같은경우에만일치로판단case 문의조건식과모든 case_item의비트크기는큰쪽에맞추어져야함

모든 case item들에대한비교에서일치되는항이없는경우에는 default모든 case_item들에대한비교에서일치되는항이없는경우에는 default 항이실행

default 항이없으면변수는이전에할당받은값을유지하나의 case 문에서여러개의 default를사용하는것은허용되지않음

Ver1.0 (2008)26한국기술교육대학교 정보기술공학부

Page 27: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문

case문을이용한 2:1멀티플렉서

module mux21_case(a, b, sel, out);input [1:0] a, b;i t l

case문을이용한 2 1 멀티플렉서

input sel;output [1:0] out;reg [1:0] out;

always @(a or b or sel) begincase(sel)

0 : out = a;1 : out b;1 : out = b;

endcaseend

endmodule 코드 5.11

Ver1.0 (2008)27한국기술교육대학교 정보기술공학부

Page 28: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문case문을이용한디코더

reg [15:0] rega;reg [9:0] result;

always @(rega) beginalways @(rega) begincase(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'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;

endcaseend

Ver1.0 (2008)28

end

한국기술교육대학교 정보기술공학부

Page 29: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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;d f lt lt 'bdefault : result = 'bx;

endcase

case(sig)1 b $di l ( i l i fl i )

case 문을이용한 x와 z의검출예

1'bz: $display("signal is floating");1'bx: $display("signal is unknown");

default: $display("signal is %b", sig);endcase

Ver1.0 (2008)29

endcase

한국기술교육대학교 정보기술공학부

Page 30: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문don't care를갖는 case 문

casez문 : z를 don’t - care로취급하여해당비트를비교에서제외casez문 : z를 don t care로취급하여해당비트를비교에서제외don't – care 조건으로 ? 기호사용가능

casex문 : x와 z를 don’t - care로취급하여해당비트를비교에서제외

reg [7:0] ir;casez(ir)casez(ir)

8'b1???????: instruction1(ir);8'b01??????: instruction2(ir);8'b00010???: instruction3(ir);8 b00010???: instruction3(ir);8'b000001??: instruction4(ir);

endcase

Ver1.0 (2008)30한국기술교육대학교 정보기술공학부

Page 31: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문

casex문을이용한 3비트우선순위인코더(priority encoder)

module pri_enc_casex(encode, enc);input [3:0] encode;

casex 문을이용한 3비트우선순위인코더(priority encoder)

p [ ] ;output [1:0] enc;reg [1:0] enc;

always @(encode) begincasex(encode)

4'b1xxx : enc = 2'b11;4'b01xx : enc = 2'b10;4'b001x : enc = 2'b01;4'b0001 : enc = 2'b00;

dendcaseend

endmodule 코드 5.12

Ver1.0 (2008)31한국기술교육대학교 정보기술공학부

Page 32: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문

코드 5.12의시뮬레이션결과

Ver1.0 (2008)32한국기술교육대학교 정보기술공학부

Page 33: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.4 case 문

case 조건식에상수값을사용한 3비트우선순위인코더

module pri_enc_case(encode, enc);input [3:0] encode;t t [1 0]output [1:0] enc;

reg [1:0] enc;

always @(encode) beginalways @(encode) begincase(1)

encode[3]: enc = 2'b11;encode[2]: enc = 2'b10;encode[2]: enc 2 b10;encode[1]: enc = 2'b01;encode[0]: enc = 2'b00;default : $display("Error: One of the bits expected ON");p y p

endcaseend

endmodule 코드 5.13

Ver1.0 (2008)33한국기술교육대학교 정보기술공학부

Page 34: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문반복문

forever 문:문장이무한히반복적으로실행forever 문:문장이무한히반복적으로실행

repeat문:지정된횟수만큼문장이반복실행

반복횟수를나타내는수식이 x 또는 z로평가되면반복횟수는 0이되고, 문장은실행되지않음

while문:조건식의값이거짓이될때까지문장이반복실행

조건식의초기값이거짓이면문장은실행되지않음조건식의초기값이거짓이면문장은실행되지않음

for문:반복횟수를제어하는변수에의해문장이반복실행

forever statement;| repeat(expression) statement;| repeat(expression) statement;| while(expression) statement;| for(variable_assign); expression; variable_assign) statement;

Ver1.0 (2008)34한국기술교육대학교 정보기술공학부

Page 35: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문repeat 문을이용한 shift-add 방식의승산기

module multiplier_8b(opa, opb, result);parameter SIZE = 8, LongSize = 2*SIZE;input [SIZE-1:0] opa, opb;

[ i 1 0] loutput [LongSize-1:0] result;reg [LongSize-1:0] result, shift_opa, shift_opb;

always @(opa or opb) begina ays @(opa o opb) begshift_opa = opa; // multiplicandshift_opb = opb; // multiplierresult = 0;

t(SIZE) b irepeat(SIZE) beginif(shift_opb[0])

result = result + shift_opa;shift opa = shift opa << 1;_ p _ p ;shift_opb = shift_opb >> 1;

endendd d l 코드 5 14

Ver1.0 (2008)35

endmodule 코드 5.14

한국기술교육대학교 정보기술공학부

Page 36: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문

코드 5.14의시뮬레이션결과

Ver1.0 (2008)36한국기술교육대학교 정보기술공학부

Page 37: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문

8비트입력 rega에포함된 1을계수하는회로

module cnt_one(rega, count);input [7:0] rega;output [3:0] count;preg [7:0] temp_reg;reg [3:0] count;

always @(rega) beginalways @(rega) begincount = 0;temp_reg = rega;while(temp_reg) begin_

if(temp_reg[0])count = count + 1;

temp_reg = temp_reg >> 1;endend

end

endmodule 코드 5.15

Ver1.0 (2008)37한국기술교육대학교 정보기술공학부

Page 38: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문

코드 5.15의시뮬레이션결과

Ver1.0 (2008)38한국기술교육대학교 정보기술공학부

Page 39: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문for 문을이용한 8비트우선순위인코더(priority encoder)

module enc_for(in, out);input [7:0] in;output [2:0] out;

입력 in[7:0] 출력 out[2:0]

0000_0001 000

0000 0010 001preg [2:0] out;integer i;

0000_0010 001

0000_0100 010

0000_1000 011

always @(in) begin : LOOPout=0;for(i = 7; i >= 0; i = i-1) begin

if(i [i]) b i

0001_0000 100

0010_0000 101

0100_0000 110if(in[i]) begin

out=i;disable LOOP;

end

1000_0000 111

8비트우선순위인코더

endend

endendmodule 코드 5.16

Ver1.0 (2008)39

endmodule 코드 5.16

한국기술교육대학교 정보기술공학부

Page 40: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문

코드 5.16의시뮬레이션결과

Ver1.0 (2008)40한국기술교육대학교 정보기술공학부

Page 41: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.5반복문module tb_dff ;

reg clk, d;forever 문을이용한주기신호생성

g

dff U1 (clk, d, q);

initial begininitial beginclk = 1'b0;forever #10 clk = ~clk;

end

initial begin d = 1'b0;forever beginforever begin

#15 d = 1'b1;#20 d = 1'b0;#30 d = 1'b1;#20 d = 1'b0;

endend

endmodule

Ver1.0 (2008)41

endmodule

한국기술교육대학교 정보기술공학부

Page 42: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어절차형할당의실행제어

지연제어 :지연제어 : delay operator : # 특정절차형할당문의실행순서가된시점과그문장이실제실행되는시점

사이의시간간격을지정 (문장의실행을지연시킴)지연값이 x 또는 z인경우에는지연이 0으로처리음수지연값이지정된경우에는 2의보수 unsigned정수로해석음수지연값이지정된경우에는 2의보수 unsigned 정수로해석

#10 rega = regb;#d rega = regb; // d is defined as a parameter

event 제어

# g g ; // p#((d+e)/2) rega = regb; // delay is average of d and e

event operator : @ 시뮬레이션 event가발생될때까지문장의실행을지연시킴net나변수의값변화가순차문의실행을트리거하기위한 event로사용가능

Ver1.0 (2008)42

net나변수의값변화가순차문의실행을트리거하기위한 event로사용가능

한국기술교육대학교 정보기술공학부

Page 43: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어에지천이검출

negedge:1에서 0, x, z로변화, 또는 x, z에서 0으로변화에서 event 발생g g

posedge:0에서 x, z, 1로변화, 또는 x, z에서 1로변화에서 event 발생event 발생수식의결과가 1비트이상인경우에는, 에지천이는결과의LSB에서검출LSB에서검출

표 5.1 posedge와 negedge event의발생

ToFrom 0 1 x z

표 5.1 posedge와 negedge event의발생

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한국기술교육대학교 정보기술공학부

Page 44: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어상승에지로동작하는 D 플립플롭

module dff(clk, d, q);input clk, d;output q;reg q;reg q;

always @(posedge clk)q <= d;

코드 5 17endmodule 코드 5.17

Ver1.0 (2008)44한국기술교육대학교 정보기술공학부

Page 45: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어named event

event자료형으로선언된식별자event 자료형으로선언된식별자순차문의실행을제어하기위한 event 표현에사용

event가발생될때까지실행이지연됨

named event는데이터값을유지하지않음임의의특정한시간에발생될수있음

지속시간을갖지않음

event 제어구문을이용해서 event의발생을감지할수있음

event list_of_event_identifiers; // event 선언

> t id tifi // t t i-> event_identifier; // event trigger

Ver1.0 (2008)45한국기술교육대학교 정보기술공학부

Page 46: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어

module ff_event(clock, reset, din, q);input reset clock din;

named event를이용한 D 플립플롭

input reset, clock, din;output q;reg q;event upedge; // event 선언

always @(posedge clock) -> upedge;

always @(upedge or negedge reset)always @(upedge or negedge reset) begin

if(reset==0) q = 0;else q = din;

endendmodule 코드 5.18

Ver1.0 (2008)46한국기술교육대학교 정보기술공학부

Page 47: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어

코드 5.18의시뮬레이션결과

Ver1.0 (2008)47한국기술교육대학교 정보기술공학부

Page 48: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어event or 연산자

다수의 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;

b ibeginwait(!enable) #10 a = b;

#10 c = d;end

Ver1.0 (2008)48한국기술교육대학교 정보기술공학부

Page 49: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어intra-assignment 타이밍제어

지연과 event제어가순차할당문안에포함지연과 event 제어가순차할당문안에포함우변의수식에대한평가를먼저실행한후, 좌변의객체에새로운값이할당되는시점을지정된지연만큼지연시킴

a <= repeat(5) @(posedge clk) data;

Ver1.0 (2008)49한국기술교육대학교 정보기술공학부

Page 50: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어

d l i d l 1( lk d )module intra_delay1(clk, d, out);input clk, d;output out;reg out;reg out;always @(*)

out = repeat(3) @(posedge clk) d;endmodule

등가코드코드 5.19

module intra_delay1_eq(clk, d, out);input clk, d;output out;

t t

등가코드

reg out,temp;always @(*) begin

temp = d;@(posedge clk);@(p g );@(posedge clk);@(posedge clk) out = temp;

endd d l 코드 5 20

Ver1.0 (2008)50

endmodule 코드 5.20

한국기술교육대학교 정보기술공학부

Page 51: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.6절차형할당의타이밍제어

코드 5 19의시뮬레이션결과코드 5.19의시뮬레이션결과

Ver1.0 (2008)51한국기술교육대학교 정보기술공학부

Page 52: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

절차형할당의타이밍제어

Equivalent model of Intra-assignment timing control

With intra-assignment construct Without intra-assignment construct

a = #5 b;

begintemp = b;

a = #5 b;#5 a = temp;

end

begin

a = @(posedge clk) b;

gtemp = b;@(posedge clk) a = temp;

end

a = repeat(3) @(posedge clk) b;

begintemp = b;@(posedge clk);

a = repeat(3) @(posedge clk) b;@(posedge clk);@(posedge clk) a = temp;

end

Ver1.0 (2008)52한국기술교육대학교 정보기술공학부

Page 53: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.7블록문블록문

두개이상의문장을그룹으로묶어구문적으로하나의문장처럼처리두개이상의문장을그룹으로묶어구문적으로하나의문장처럼처리

begin-end 절차형할당문블록문장이나열된순서에의해순차적으로실행

시작시간 : 첫번째문장이실행될때종료시간 : 마지막문장이실행될때각절차형할당문의실행은이전문장의지연시간에대해상대적으로결정됨각절차형할당문의실행은이전문장의지연시간에대해상대적으로결정됨

fork-join 병렬문블록문장의나열순서에무관하게동시에실행

시작시간 : 블록내의모든문장의시작시간이동일종료시간 : 각문장의지연이고려되어시간적으로마지막에실행되는문장의실행이완료된시점실행이완료된시점

각문장의지연은블록에들어가는시뮬레이션시간을기준으로결정됨

시뮬레이션파형생성에유용함

Ver1.0 (2008)53한국기술교육대학교 정보기술공학부

Page 54: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

5.7블록문

parameter d = 50;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 -> end wave; //trigger an event called end wave#d -> end_wave; //trigger an event called end_wave

end

fork#50 r = 8'h35;#100 r = 8'hE2;

fork#250 -> end_wave;#200 r = 8'hF7;#100 r = 8'hE2;

#150 r = 8'h00;#200 r = 8'hF7;#250 -> end_wave;

#200 r = 8 hF7;#150 r = 8'h00;#100 r = 8'hE2;#50 r = 8'h35;

등가코드

Ver1.0 (2008)54

_join join

한국기술교육대학교 정보기술공학부

Page 55: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

Verilog HDL을이용한디지털시스템설계및실습

6 구조적 모델링6. 구조적 모델링

Ver1.0 (2008)55한국기술교육대학교 정보기술공학부

Page 56: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.1모듈

module module_name (port_list); 머리부

port 선언reg 선언

i 선언선언부

wire 선언parameter 선언

하위모듈인스턴스

게이트프리미티브

always 문, initial 문assign 문function, task 정의function, task 호출

몸체

endmodule

, 출

그림 6 1 Verilog모듈의구성

Ver1.0 (2008)56

그림 6.1 Verilog 모듈의구성

한국기술교육대학교 정보기술공학부

Page 57: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.1.1모듈포트선언모듈포트선언

포트목록에나열된포트들은선언부에서포트선언을통해 input, output, p , p ,inout(양방향)으로선언signed와범위에대한정의를포함한포트에관한모든다른속성들이포트선언에포함될수있음

inout_declaration ::= inout [ net type ][ signed ][ range ] list of port identifiersinout [ net_type ][ signed ][ range ] list_of_port_identifiers

input_declaration ::=input [ net_type ][ signed ][ range ] list_of_port_identifiers

output declaration ::=p _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_identifierslist_of_port_identifiers ::= port identifier { port identifier }

Ver1.0 (2008)57

port_identifier { , port_identifier }

한국기술교육대학교 정보기술공학부

Page 58: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.1.1모듈포트선언

input aport; // First declaration - okay.p p yinput aport; // Error - multiple port declarationoutput 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 unsignedinput signed [7:0] c, d; // no explicit net declaration - net is signedoutput [7:0] e, f; // no explicit declaration - net is unsignedoutput signed [7:0] g, h; // no explicit net declaration - net is signedwire signed [7:0] b; // port b inherits signed attribute from net decl.wire [7:0] c; // net c inherits signed attribute from portwire [7:0] c; // net c inherits signed attribute from portreg 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한국기술교육대학교 정보기술공학부

Page 59: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.1.1모듈포트선언

module complex_ports({c,d}, .e(f)); // Nets {c d} receive the first port bits// 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'.

p p

// 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한국기술교육대학교 정보기술공학부

Page 60: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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한국기술교육대학교 정보기술공학부

Page 61: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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 ) ;

// ill l d l f h d l i h b d f h d l// illegal to redeclare any ports of the module in the body of the module.

Ver1.0 (2008)61한국기술교육대학교 정보기술공학부

Page 62: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스구조적모델링

다른모듈의인스턴스와포트매핑을통한모델링다른모듈의인스턴스와포트매핑을통한모델링

범위지정을통한인스턴스배열의생성가능

모듈인스턴스이름은생략할수없음

게이트프리미티브의인스턴스이름은생략가능

포트순서에의한포트매핑

모듈의포트목록에나열된포트순서와 1:1로대응되어연결포트에연결되는신호가없는경우에는해당위치를빈칸으로남겨둔다

포트이름에의한포트매핑포트이름에의한포트매핑

포트이름과그포트에연결되는신호이름을명시적으로지정

포트의비트선택 부분선택 결합등을사용할수없음포트의비트선택, 부분선택, 결합등을사용할수없음

.port_name([expression])

Ver1.0 (2008)62한국기술교육대학교 정보기술공학부

Page 63: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

module modB(wa, wb, c, d);순서에의한포트매핑 ( , , , );inout wa, wb;input c, d;

tranif1 g1(wa wb cinvert);

module topmod;wire [4:0] v;wire c w;

순서에의한포트매핑

코드 6.3

tranif1 g1(wa, wb, cinvert);not #(2, 6) n1(cinvert, int);and #(6, 5) g2(int, c, d);

endmodule

wire c, w;

modB b1(v[0], v[3], w, v[4]);endmodule

이름에의한포트매핑

module topmod;wire [4:0] v;wire a,b,c,w;

modB b1(.wb(v[3]), .wa(v[0]), .d(v[4]), .c(w));endmodule 코드 6.4

Ver1.0 (2008)63한국기술교육대학교 정보기술공학부

Page 64: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

module bus_driver(busin, bushigh, buslow, enh, enl);input [15:0] busin;input enh enl;input enh, enl;output [7:0] bushigh, buslow;

driver busar3(busin[15:12], bushigh[7:4], enh);2 11 8 3 0driver 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);

endmodule 코드 6.2-(a)

driver busar[3:0] (.in(busin),t({b hi h b l })

모듈인스턴스의배열을이용

( )

.out({bushigh, buslow}),

.en({enh, enh, enl, enl}) );endmodule 코드 6.2-(b)

Ver1.0 (2008)64한국기술교육대학교 정보기술공학부

Page 65: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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.);

endmodule 코드 6.4

Ver1.0 (2008)65한국기술교육대학교 정보기술공학부

Page 66: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

HalfAdder

ab sum

temp_sum

Half Adder

sum

coutcin temp_c2

temp_c1

module half_adder(a, b, sum, cout);input a b;

반가산기모듈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);

endmodule 코드 6.6-(a)

Ver1.0 (2008)66

( )

한국기술교육대학교 정보기술공학부

Page 67: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

module full_adder(a, b, cin, sum, cout);i t b iinput a, b, cin;output sum, cout;wire temp_sum, temp_c1, temp_c2; //생략 가능

// half_adder 모듈의 instantiationhalf_adder u0(a, b, temp_sum, temp_c1); // 순서에 의한 포트 연결half_adder u1(.a(temp_sum),

b( i ).b(cin), .sum(sum), .cout(temp_c2) ); // 이름에 의한 포트 연결

or u2(cout, temp c1, temp c2); // 게이트 프리미티브 인스턴스( , p_ , p_ ); // 게이 리미티

endmodule 코드 6.6-(b)

Ver1.0 (2008)67한국기술교육대학교 정보기술공학부

Page 68: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

// 1비트 full_adder 모듈의 시뮬레이션 testbenchmodule tb_full_adder ;

reg a, b, cin; // initial 블록에서 값을 받으므로 reg로 선언integer k;

// full_adder 모듈의 instantiationfull_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;

endend

endmodule 코드 6.7

Ver1.0 (2008)68

endmodule 코드 6.7

한국기술교육대학교 정보기술공학부

Page 69: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스

Ver1.0 (2008)69한국기술교육대학교 정보기술공학부

Page 70: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.2모듈인스턴스실수형값의포트연결

real 자료형은직접포트에연결될수없음시스템함수인 $realtobit와 $bittoreal를통해 real 자료형을비트자료형으로변환한후모듈포트에적용

module driver(net_r);output net_r;real r;real r;wire [64:1] net_r = $realtobits(r);

endmodule 코드 6.8

module receiver(net r);module receiver(net_r);input net_r;wire [64:1] net_r;real r;

initial assign r = $bitstoreal(net_r);

endmodule 코드 6.9

Ver1.0 (2008)70한국기술교육대학교 정보기술공학부

Page 71: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter모듈 parameter

variable 또는 net 범주에속하지않는상수모듈이인스턴스될때값을변경시킬수있음

구조적설계에서모듈인스턴스의개별화(customize)를위한유용한수단l l 으로선언된 t 는그값을변경할수없음localparam으로선언된 parameter는그값을변경할수없음

모듈 parameter 값의변경defparam문을이용하는방법defparam문을이용하는방법

모듈인스턴스를통해 parameter 값을변경하는방법위의두가지방법에의한 parameter 값변경이충돌되는경우,defparam문에의해설정된값이사용됨

Ver1.0 (2008)71한국기술교육대학교 정보기술공학부

Page 72: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter모듈 parameter 값의변경

module foo(a, b);real r1, r2;parameter [2:0] A = 3'h2; //자료형과 범위가 지정된 parameter 선언parameter B = 3'h2; //자료형과 범위가 지정되지 않은 parameter 선언parameter B 3 h2; //자료형과 범위가 지정되지 않은 parameter 선언initial begin

r1 = A;r2 = B;$display("r1 is %f, r2 is %f",r1,r2);

endendmodule 코드 6.10-(a)

module bar; // parameter overriding using defparamwire a, b;defparam U0.A = 3.1415; // A는 3으로 변경됨

// 는 로 변경됨defparam U0.B = 3.1415; // B는 3.1415로 변경됨

foo U0(a, b); // module instantiationendmodule 코드 6.10-(b)

Ver1.0 (2008)72

endmodule 코드 6.10 (b)

한국기술교육대학교 정보기술공학부

Page 73: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameterdefparam문

parameter의계층적이름을사용하여전체설계에걸친모듈인스턴스의pparameter 값을변경

인스턴스배열의하부계층구조에있는 defparam문은계층구조밖의

t 값을변경시킬수없음parameter 값을변경시킬수없음모든 parameter 변경문들을함께묶어독립된모듈로정의할때유용

Ver1.0 (2008)73한국기술교육대학교 정보기술공학부

Page 74: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

모듈 parameterdefparam문에의한 parameter 값의변경

module top;reg clk;reg [0:4] in1;reg [0:9] in2;

module vdff(out, in, clk);parameter size = 1, delay = 1;input [0:size-1] in;input clk;reg [0:9] in2;

wire [0:4] o1;wire [0:9] o2;

input clk;output [0:size-1] out;reg [0:size-1] out;

vdff m1(o1, in1, clk);vdff m2(o2, in2, clk);

endmodule

always @(posedge clk)# delay out = in;

endmodule

module annotate;defparam

top.m1.size = 5,top.m1.delay = 10,top.m1.delay 10,top.m2.size = 10,top.m2.delay = 20;

endmodule 코드 6.10

Ver1.0 (2008)74한국기술교육대학교 정보기술공학부

Page 75: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter모듈인스턴스의 parameter 값변경순서화된 parameter 목록에의한방법(ordered parameter assignment)p ( _p _ g )

#(expression {, expression,} )

parameter 이름에의한방법 (named_parameter_assignment)

#(.parameter_name([expression]))

단일모듈인스턴스문에서이들두가지방법을혼용하여사용할수없음

기호 # : delay operator로도사용됨

Ver1.0 (2008)75한국기술교육대학교 정보기술공학부

Page 76: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter

모듈 parameter 값의변경

module dffn(q, d, clk);parameter BITS = 1;input [BITS-1:0] d;input clk;output [BITS-1:0] q;

DFF dff_array [BITS-1:0] (q, d, clk); // instance array

module MxN_pipeline(in, out, clk);parameter M = 3, N = 4; // M=width,N=depthinp t [M 1 0] in

_endmodule

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);

endmodule 코드 6.12

Ver1.0 (2008)76한국기술교육대학교 정보기술공학부

Page 77: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter

모듈 parameter 값의변경

Ver1.0 (2008)77한국기술교육대학교 정보기술공학부

Page 78: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.3모듈 parameter

d l dff( t i lk)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 임

endmodule

module m;reg clk;

코드 6.13-(a)

reg clk;wire [0:4] out_c, in_c;wire [1:10] out_a, in_a;wire [1:5] out_b, in_b;

vdff #(10,15) mod_a(out_a, in_a, clk);vdff mod_b(out_b, in_b, clk); // default parameter valuesvdff #(.delay(12)) mod_c(out_c, in_c, clk);d d l 코드 6 13 (b)

Ver1.0 (2008)78

endmodule 코드 6.13-(b)

한국기술교육대학교 정보기술공학부

Page 79: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4생성문생성문 (Generate statement)

generate-endgenerate블록으로모델링g g반복생성문 (generate-for)조건생성문 (generate-if)case생성문 (generate case)case 생성문 (generate-case)

모듈, 사용자정의프리미티브(UDP), 게이트프리미티브, 연속할당문, initial 블록과 always 블록등의인스턴스를하나또는다수개생성net, reg, integer, real, time, realtime, event 등의자료형선언가능생성된인스턴스와자료형은고유의식별자를가지며계층적으로참조가능

순서또는이름에의한 t 값의변경또는 문에의한순서또는이름에의한 parameter 값의변경또는 defparam문에의한

parameter 재정의가능defparam문은생성범위내에서선언된 parameter의값에만영향을미침p p

생성문에서 parameter, local parameter, input, output, inout, specify block 등의선언은허용되지않음

Ver1.0 (2008)79한국기술교육대학교 정보기술공학부

Page 80: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.1 genvar선언genvar 선언생성문내에서만사용될수있는인덱스변수의선언에사용

genvar로선언되는변수는정수형선언된변수를인덱스로갖는반복생성문내에서만사용되는지역변수

의값은 t 값이참조될수있는어떤문장에서도참조가능genvar의값은 parameter 값이참조될수있는어떤문장에서도참조가능시뮬레이터또는논리합성툴의 elaboration 과정동안에만정의되며, 시뮬레이션또는합성이진행되는동안에는존재하지않음

elaboration 과정 : 시뮬레이션이나합성을위해모듈을분석하는과정구문의오류검출 인스턴스된모듈의연결(link) parameter값의전달구문의오류검출, 인스턴스된모듈의연결(link), parameter 값의전달, 계층적인참조에대한분해등을수행하는과정

Ver1.0 (2008)80한국기술교육대학교 정보기술공학부

Page 81: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문반복생성문 (generate-for문)

generate-endgenerate구문내부에 for 문을사용하여특정모듈또는g g

블록을반복적으로인스턴스

variable 선언, 모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, l 블록등을인스턴스할수있음always 블록등을인스턴스할수있음

생성문내부의 for-loop에서사용되는인덱스변수는 genvar로선언

for 문의 begin 뒤에생성문블록식별자 (:identifier)를붙여야함g ( )

Ver1.0 (2008)81한국기술교육대학교 정보기술공학부

Page 82: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

10진수 순환 2진부호 이진부호

표 6.2 순환 2진부호(gray code)와이진부호

0 0000 0000

1 0001 0001

2 0011 00102 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

9 1101 1001

한국기술교육대학교 정보기술공학부

Page 83: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

module gray2bin1(bin, gray);parameter SIZE = 4; // this module is parameterizable

generate-for 문을이용한 gray-to-binary 변환기

parameter SIZE 4; // this module is parameterizableoutput [SIZE-1:0] bin;input [SIZE-1:0] gray;genvar i;

generatefor(i=0; i<SIZE; i=i+1) begin :bit

assign bin[i] = ^gray[SIZE-1:i];assign bin[i] gray[SIZE 1:i];end

endgenerateendmodule 코드 6.14

Ver1.0 (2008)83한국기술교육대학교 정보기술공학부

Page 84: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

generate-for 문을이용한 gray-to-binary 변환기

module gray2bin2(bin, gray);parameter SIZE = 4; output [SIZE-1:0] bin;output [SIZE 1:0] bin;input [SIZE-1:0] gray;reg [SIZE-1:0] bin;genvar i;

generatefor(i=0; i<SIZE; i=i+1) begin :bit

always @(gray[SIZE-1:i])always @(gray[SIZE 1:i]) bin[i] = ^gray[SIZE-1:i];

end endgenerate

코드 6 15endmodule 코드 6.15

Ver1.0 (2008)84한국기술교육대학교 정보기술공학부

Page 85: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

generate-for 문을이용한 gray-to-binary 변환기

Ver1.0 (2008)85한국기술교육대학교 정보기술공학부

Page 86: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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;integer i;

always @(gray) begintmp = gray;for (i=0; i<SIZE; i=i+1)

bin[i] = ^tmp[SIZE-1:i]; // i should be constantend

endmoduleendmodule

always 문을사용하는경우의올바른코드는 ?

Ver1.0 (2008)86한국기술교육대학교 정보기술공학부

Page 87: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

module adder gen1(co, sum, a, b, ci);

생성루프외부에 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 [SIZE 1:0] a, b; input ci; wire [SIZE :0] c; wire [SIZE-1:0] t [1:3]; // 2차원 net 선언genvar i;genvar i;

assign c[0] = ci; generatefor(i=0; i<SIZE; i=i+1) begin :bit( ; ; ) g :

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]); g ( [ ][ ], [ ][ ], [ ]);or g5( c[i+1], t[2][i], t[3][i]);

end endgenerateassign co = c[SIZE];

코드

Ver1.0 (2008)87

g [ ];endmodule 코드 6.16

한국기술교육대학교 정보기술공학부

Page 88: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

module adder gen2(co, sum, a, b, ci);

생성루프내부에 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 [SIZE 1:0] a, b; input ci; wire [SIZE :0] c; genvar i;

assign c[0] = ci;generatefor(i=0; i<SIZE; i=i+1) begin :bit

wire t1, t2, t3; // generated net declaration, , ; // gxor 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]); g ( , , [ ]);or g5( c[i+1], t2, t3);

end endgenerateassign co = c[SIZE];

Ver1.0 (2008)88

g [ ];endmodule 코드 6.17

한국기술교육대학교 정보기술공학부

Page 89: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.2반복생성문

code 6.16, code 6.17의시뮬레이션결과

Ver1.0 (2008)89한국기술교육대학교 정보기술공학부

Page 90: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.3조건생성문조건생성문 (generate-if 문)

generate-endgenerate블록내에 if-else-if의조건문을generate endgenerate블록내에 if else if의조건문을

사용하여조건에따라특정모듈또는블록을선택적으로인스턴스

모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, always 블록등을인스턴스할수있음

인스턴스가선택되는조건은 elaboration되는시점에서의값에의해결정

Ver1.0 (2008)90한국기술교육대학교 정보기술공학부

Page 91: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.3조건생성문if 생성문을이용한파라미터화된곱셈기

module multiplier(a, b, product); parameter a_width = 8, b_width = 8; localparam product_width = a_width+b_width;

// b difi d di l i h d f// can not be modified directly with defparam or // module instance statement #

input [a_width-1:0] a; input [b width-1:0] b; put [b_ dt :0] b;output [product_width-1:0] product;

generateif(( idth 8) ||(b idth 8))if((a_width < 8) ||(b_width < 8))

CLA_mul #(a_width, b_width) u1(a, b, product); // instance a CLA multiplier

elseWALLACE_mul #(a_width, b_width) u1(a, b, product); // instance a Wallace-tree multiplier

endgenerated d l 코드 6 19

Ver1.0 (2008)91

endmodule 코드 6.19

한국기술교육대학교 정보기술공학부

Page 92: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.4 case 생성문case 생성문 (generate-case문)

generate-endgenerate블록내에 case문을사용하여조건에따라generate endgenerate블록내에 case 문을사용하여조건에따라특정모듈또는블록을선택적으로인스턴스

모듈, UDP, 게이트프리미티브, 연속할당문, initial 블록, always 블록등을인스턴스할수있음

인스턴스가선택되는조건은 elaboration되는시점에서의값에의해결정

Ver1.0 (2008)92한국기술교육대학교 정보기술공학부

Page 93: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

6.4.4 case 생성문

3이하의비트폭을처리하기위한 case생성문

generatecase(WIDTH)

3 이하의비트폭을처리하기위한 case 생성문

1: adder_1bit x1(co, sum, a, b, ci); // 1-bit adder2: adder_2bit x1(co, sum, a, b, ci); // 2-bit adderdefault: adder_cla #(WIDTH) x1(co, sum, a, b, ci);

// carry look-ahead adder endcase

endgenerate 코드 6.20

Ver1.0 (2008)93한국기술교육대학교 정보기술공학부

Page 94: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

Verilog HDL을이용한디지털시스템설계및실습

7 task와 함수7. task와 함수

Ver1.0 (2008)94한국기술교육대학교 정보기술공학부

Page 95: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.1 Task와함수Task와함수

반복되는행위수준모델링부분을독립된코드의 task나함수(function)로반복되는행위수준모델링부분을독립된코드의 task나함수(function)로정의하고, 이들을호출하여사용규모가큰행위수준모델링을작은부분들로분할하여 task 또는함수로표현함

장점

소스코드의가독성 (readability)과디버깅을용이하게함

종류

사용자정의 task, 함수시스템 task, 함수

Ver1.0 (2008)95한국기술교육대학교 정보기술공학부

Page 96: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.1 Task와함수Function

적어도 개이상의 인수가필요

Task

•적어도 1개이상의 input 인수가필요• output, inout 인수를가질수없음•항상 1개의결과값을 return 함•함수명을통해값을 return

• 0개이상의 input, output, inout 인수포함•값을 return하지않을수있음• output, inout을통해다수개의값을 return

함수명을통해값을 return

zero delay를갖는조합회로구현

• delay, timing, event를갖고, multiple output을반환하는 source code에적용가능t k의 I/O에정의되지않은 d l 내

다른 function 호출가능 (task는불가)

y를갖 회 구

다른 task나 function 호출가능

• task의 I/O에정의되지않은module 내reg로선언된변수 access 가능

zero simulation delay

delay, event, timing control 문포함불가

non-zero simulation time 수행가능

delay, event, timing control 문포함가능

variable 자료형만가질수있으며, net 자료형은가질수없음assign 문, 게이트프리미티브와모듈인스턴스는사용할수없음initial 문과 always 문을포함할수없음b h i l문만포함가능함

Ver1.0 (2008)96

behavioral 문만포함가능함

한국기술교육대학교 정보기술공학부

Page 97: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.1 Task와함수function과 task의정의및호출

module test (……..);……………

module test (……..);……………

t k t k // t k정의function [n-1:0] func_name; // 함수정의

input ……; // 인수순서중요………….begin

task task_name; // task 정의input ……; // 인수순서중요output ….;inout ……;

begin……….func_name = ……;…….

end

………….begin

……….…….dend

endfunction…….

= func name( ); //함수호출

end endtask…….

t k ( ) // t k호출….. func_name(…); // 함수호출…………endmodule

task_name(…); // task 호출…………endmodule

Ver1.0 (2008)97한국기술교육대학교 정보기술공학부

Page 98: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 TaskTask의정의

task task_identifier(task_port_list);{block_item_declaration}statement;dt kendtask

task task_identifier;{task item declaration} // task의 입력 출력 인수를 선언{task_item_declaration} // task의 입력, 출력 인수를 선언

statement;endtask

Task의호출

인수의순서는 task 정의에서선언된인수목록의순서와일치되어야함

task_enable ::= task_identifier [(expression {, expression} )];

Ver1.0 (2008)98한국기술교육대학교 정보기술공학부

Page 99: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 Task

task my_task;input a, b;inout c;

선언부에서인수를선언

output d, e;begin

. . . // task의 기능을 수행하는 문장들c = foo1; // 결과 값을 reg 변수에 할당하는 문장들c = foo1; // 결과 값을 reg 변수에 할당하는 문장들d = foo2;e = foo3;

endendtask

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한국기술교육대학교 정보기술공학부

Page 100: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 Taskmodule bit_counter (data_word, bit_count);input [7:0] data_word;output [3:0] bit count;p _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;begincount=0;temp_reg=reg_a; while (temp_reg) begin

if (temp_reg[0]) count=count+ 1;

temp_reg = temp_reg >> 1;end

endendtask

코드

Ver1.0 (2008)100

endmodule 코드 7.1

한국기술교육대학교 정보기술공학부

Page 101: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 Task

코드 7.1의시뮬레이션결과코드 7.1의시뮬레이션결과

Ver1.0 (2008)101한국기술교육대학교 정보기술공학부

Page 102: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 Task

module traffic_lights;reg clock, red, amber, green;parameter on = 1, off = 0, red_tics = 350,

amber tics = 30 green tics = 200;amber_tics = 30, green_tics = 200;//initialize colors.

initial red = off;initial amber = off;initial green = off;

always begin // sequence to control the lights.red = on; // turn red light on and waitred = 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);

end코드 7 2

Ver1.0 (2008)102

코드 7.2

한국기술교육대학교 정보기술공학부

Page 103: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.2 Task

// task to wait for 'tics' positive edge clocks before turning 'color' light off.

task light;output color;input [31:0] tics;

beginrepeat(tics) @(posedge clock);repeat(tics) @(posedge clock);color = off; // turn light off.

endendtask

always begin // waveform for the clock.#100 clock = 0;#100 clock = 1;#100 clock 1;

endendmodule 코드 7.2

Ver1.0 (2008)103한국기술교육대학교 정보기술공학부

Page 104: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수함수의정의

function [signed][range_type] function_identifier(function_port_list);{block_item_declaration}statement;

endfunction

function [signed][range_type] function_identifier ;{function_item_declaration}statement;

함수결과값의속성및범위지정 [ i d][ t ]

statement;endfunction

함수결과값의속성및범위지정 : [signed][range_type]별도의지정이없으면, default로 1비트 reg형이됨

함수가정의되면함수이름과동일한이름의변수가함수내부에선언됨수가정의되 수이 과동일 이 의 수가 수내부에

함수가정의되는영역에서함수이름과동일한이름의다른객체를선언하는

것이허용되지않음

Ver1.0 (2008)104한국기술교육대학교 정보기술공학부

Page 105: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수함수의호출

함수의규칙

ftn_call ::= hierarchical_ftn_identifier{attribute_inst}(expr {,expr})

함수의규칙

함수는적어도하나이상의입력인수를포함해야한다.함수는 output과 inout으로선언된어떠한인수도가질수없다.함수는시간제어문장을가질수없다.

함수내부의어떠한구문도타이밍제어(#, @ 또는 wait 등)를포함할수없다.

함수는 task를호출할수없다.함수는함수이름과동일한이름의내부변수에함수의결과값을할당하는

문장을포함한다문장을포함한다.함수는 nonblocking 할당을가질수없다.

Ver1.0 (2008)105한국기술교육대학교 정보기술공학부

Page 106: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수

function [7:0] getbyte;input [15:0] address;begin // code to extract low-order byte from addressed word

선언부에서인수를선언

. . .getbyte = result_expression;

endendfunction

function [7:0] getbyte(input [15:0] address);begin // code to extract low-order byte from addressed word

. . .getbyte = result_expression;

endendfunction

d t l ? { tb t ( b t ) tb t (l b t )} 0

함수호출

Ver1.0 (2008)106

word = control ? {getbyte(msbyte), getbyte(lsbyte)}:0;

한국기술교육대학교 정보기술공학부

Page 107: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수

module word_aligner (word_in, word_out);input [7:0] word_in;output [7:0] word out;p [ ] _ ;

function [7:0] word_align;input [7:0] word;b ibegin

word_align = word;if (word_align != 0)while (word align[7] == 0) word align=word align << 1;( _ g [ ] ) _ g _ g ;

endendfunction

i d t d li ( d i ) // 함수 호출assign word_out = word_align (word_in); // 함수 호출

endmodule 코드 7.3

Ver1.0 (2008)107한국기술교육대학교 정보기술공학부

Page 108: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수

코드 7.3의시뮬레이션결과코드 7.3의시뮬레이션결과

Ver1.0 (2008)108한국기술교육대학교 정보기술공학부

Page 109: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

7.3함수module tryfact;// define the function

function automatic integer factorial;function automatic integer factorial;input [31:0] operand;integer i;if(operand >= 2)

factorial = factorial(operand - 1) * operand;else

factorial = 1;endfunctionendfunction

// test the functioninteger result;

0 factorial=11 factorial=12 factorial=2

integer n;initial begin

for(n = 0; n <= 7; n = n+1) beginresult = factorial(n);

2 factorial 23 factorial=64 factorial=245 factorial=120

result factorial(n);$display("%0d factorial=%0d", n, result);

endend

코드

6 factorial=7207 factorial=5040

Ver1.0 (2008)109

endmodule 코드 7.4

한국기술교육대학교 정보기술공학부

Page 110: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

Verilog HDL을이용한디지털시스템설계및실습

8 컴파일러 지시어8. 컴파일러 지시어

Ver1.0 (2008)110한국기술교육대학교 정보기술공학부

Page 111: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

컴파일러지시어

컴파일러지시어 (Compiler directive)Verilog소스코드의컴파일과정에영향을미치는명령어Verilog 소스코드의컴파일과정에영향을미치는명령어accent grave 문자( ` )로시작된위치에서부터다른컴파일러지시어에의해대체되거나또는컴파일이완료되기까지전체소스파일에영향을미침

단일인용부호( ' )와혼동하지않도록주의

표 8 1 Verilog컴파일러지시어

‘celldefine‘default nettype

‘ifndef‘include

표 8.1 Verilog 컴파일러지시어

_ yp‘define‘else‘elsif

‘line‘nounconnected_drive‘resetallelsif

‘endcelldefine‘endif‘ifdef

resetall‘timescale‘unconnected_drive‘undef

Ver1.0 (2008)111

ifdef undef

한국기술교육대학교 정보기술공학부

Page 112: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.1 `define과 `undefine‘define

문자치환을위한문자매크로생성에사용문자치환을위한문자매크로생성에사용

C 프로그래밍언어의 #define과유사

문자매크로치환

자주사용되는문자또는상수를의미있는이름으로정의하고, 문자매크로치환을통해정의된값을사용

특정상수 (비트폭 지연등)가회로모델링전체에걸쳐반복적으로사용되는특정상수 (비트폭, 지연등)가회로모델링전체에걸쳐반복적으로사용되는경우에, 문자매크로정의를사용하면소스코드의수정및관리가용이‘macro_name을이용하여소스코드에사용

인수를갖는문자매크로를정의할수있으며, 매크로사용의개별화가가능

‘define wait_state 3'b010 // No semicolon

Ver1.0 (2008)112한국기술교육대학교 정보기술공학부

Page 113: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

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 identifiersimple_identifier

text_macro_usage ::=‘t t id tifi [ ( li t f t l t ) ]‘text_macro_identifier [ ( list_of_actual_arguments ) ]

list_of_actual_arguments ::=actual_argument { , actual_argument }

actual argument ::=actual_argument ::=expression 문자매크로사용

Ver1.0 (2008)113한국기술교육대학교 정보기술공학부

Page 114: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.1 `define과 `undefine

‘define wordsize 8reg [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한국기술교육대학교 정보기술공학부

Page 115: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.1 `define과 `undefine‘undefine

이전에정의된문자매크로를해제이전에정의된문자매크로를해제

'define으로정의되지않은문자매크로에대해 ‘undef를정의하면컴파일

시경고메시지가출력

undefine_compiler_directive ::=d f id ifi‘undef text_macro_identifier

Ver1.0 (2008)115한국기술교육대학교 정보기술공학부

Page 116: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.2 `ifdef, `else, `elsif 등‘ifdef, 'else, 'elsif, 'endif, 'ifndef

Verilog HDL소스코드의일부를조건적으로컴파일하기위해사용Verilog HDL 소스코드의일부를조건적으로컴파일하기위해사용소스의어느곳에서든사용될수있음

모듈에대한여러가지(행위적모델링, 구조적모델링, 스위치수준모델링등) 모델링중하나를선택하여컴파일하는경우

여러가지의타이밍정보나구조적정보(비트폭등) 중하나를선택하여컴파일하는경우컴파일하는경우

시뮬레이션을위해여러가지입력벡터들중하나를선택하는경우

‘ifdef

매크로이름이정의되어있으면, ‘ifdef 이후의소스코드가컴파일에포함매크로이름이정의되어있지않고 ‘else가있으면, ‘else이후의소스코드가컴파일에포함컴파일에포함

‘endif

조건적으로컴파일되는소스코드의경계를나타냄

Ver1.0 (2008)116한국기술교육대학교 정보기술공학부

Page 117: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.2 `ifdef, `else, `elsif 등‘ifndef

매크로이름이정의되어있지않으면, ‘ifndef이후의코드가컴파일에포함매크로이름이정의되어있고 ‘else지시어가있으면, ‘else이후의코드가컴파일에포함

conditional_compilation_directive ::=ifdef_directive | ifndef_directive

ifdef_directive ::=‘ifdef text_macro_identifierifdef_group_of_lines{ ‘elsif text_macro_identifier elsif_group_of_lines }[ ‘else else group of lines ][ else else_group_of_lines ]‘endif

ifndef_directive ::=‘ifndef text_macro_identifierifndef_group_of_lines{ ‘elsif text_macro_identifier elsif_group_of_lines }[ ‘else else_group_of_lines ]‘endif

Ver1.0 (2008)117

endif

한국기술교육대학교 정보기술공학부

Page 118: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.2 `ifdef, `else, `elsif 등

module and_op(a, b, c);output a;i t binput b, c;

‘ifdef behavioralwire a = b & c;;

‘elseand a1(a,b,c);

‘endifd d l 코드 8 1endmodule 코드 8.1

Ver1.0 (2008)118한국기술교육대학교 정보기술공학부

Page 119: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.2 `ifdef, `else, `elsif 등module test(out);

output out;‘define wow‘d fi t‘define nest_one‘define second_nest‘define nest_two

‘ifdef wowinitial $display(“wow is defined”);‘ifdef nest_one

initial $display(“nest_one is defined”);‘ifdef nest_two

initial $display(“nest two is defined”);initial $display( nest_two is defined );‘else

initial $display(“nest_two is not defined”);‘endif‘else

initial $display(“nest one is not defined”);initial $display(“nest_one is not defined”);‘endif

‘elseinitial $display(“wow is not defined”);‘ifdef second_nest

initial $display(“nest_two is defined”);‘else

initial $display(“nest_two is not defined”);‘endif

‘endif코드 8 2

Ver1.0 (2008)119

endmodule 코드 8.2

한국기술교육대학교 정보기술공학부

Page 120: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.3 `include‘include

파일삽입컴파일러지시어파일삽입컴파일러지시어

소스파일의내용전체를다른소스파일에포함시켜컴파일할때사용

자주사용되는정의나 task 등을별도의파일에만든후, 컴파일과정에서포함시킬때사용

Verilog 소스코드내의어느곳에서든지정의될수있음삽입되는파일은또다른 ‘include컴파일러지시어를포함할수있음삽입되는파일은또다른 include컴파일러지시어를포함할수있음

설계전체에대한구성관리를통합적으로처리할수있음

Verilog 소스코드의효율적인구성및관리가능

include_compiler_directive ::=‘include “filename”

‘include “parts/count.v”‘include “fileB” // including fileB

Ver1.0 (2008)120

// g

한국기술교육대학교 정보기술공학부

Page 121: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.6 `timescale‘timescale

시간과지연값의측정단위와정밀도를지정시간과지연값의측정단위와정밀도를지정

다른 ‘timescale 지시어가 나타나기 전까지 효력을 유지

timescale_compiler_directive ::=‘timescale time_unit / time_precision

Character string Unit of measurement

d

표 8.2 시간정밀도단위

s seconds

ms milliseconds

us microseconds

ns nanoseconds

ps picoseconds

fs femtoseconds

Ver1.0 (2008)121

fs femtoseconds

한국기술교육대학교 정보기술공학부

Page 122: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.6 `timescale

‘timescale 1 ns / 1 ps

‘timescale 10 us / 100 ns

‘timescale 10 ns / 1 nsmodule test;

reg set;reg set;parameter d = 1.55; //16ns의 지연으로 변환initial begin

#d set = 0; //16ns에서 set에 0이 할당#d set = 1; //32ns에서 set에 1이 할당

endendmodule 코드 8.3

Ver1.0 (2008)122한국기술교육대학교 정보기술공학부

Page 123: 5 5. 행위수준모델링 - KOREATECH · 5.1.2 initial 구문 initial 구문 initial begin blocking_or_nonblocking statements; end 시뮬레이션이실행되는동안한번만실행

8.6 `timescale

Timescale directive

(unit/precision)

Delayspecification

Simulatortime step

delay valueused 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 / 100 #4 100 40 0 4 1010 ns / 100 ps #4 100 ps 40.0 ns 4 x 10

10 ns / ns #4 1 ns 40 ns 4 x 10

100 ns / ns #4 1 ns 400 ns 4 x 100100 ns / ns #4 1 ns 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한국기술교육대학교 정보기술공학부