Livro_The VHDL Cookbook - 1ed

Embed Size (px)

Citation preview

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    1/111

    Th e

    VHDLCookbook

    First Edition

    Pe ter J . Ashe nde n

    ftp://ftp.cs.adelaide.edu.au/pub/VHDL-Cookbook/ftp://ftp.cs.adelaide.edu.au/pub/VHDL-Cookbook/ftp://ftp.cs.adelaide.edu.au/pub/VHDL-Cookbook/http://www.cs.adelaide.edu.au/~peterahttp://www.cs.adelaide.edu.au/~peteraftp://ftp.cs.adelaide.edu.au/pub/VHDL-Cookbook/
  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    2/111

    The VHDL Cookbook

    First EditionJuly, 1990

    Peter J . Ashenden

    Dept. Computer ScienceUniversity of Adelaide

    South Australia

    1990, Pet er J . Ashen den

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    3/111

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    4/111

    Con ten ts i i i

    Contents

    1. In t r oduct ion . . .. .. . .. .. . .. . .. .. . .. . .. .. . .. .. . .. . .. .. . .. . .. .. . .. . .. .. . .. .. . .. . .. .. . .. . .. .1-1

    1.1. Describing Structure . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .1-2

    1.2. Describing Behaviour . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .1-2

    1.3. Discrete Event Time Model. . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . .1-3

    1.4. A Quick Example. . . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . 1-3

    2. VHDL is Like a Programming Language . . .. . .. . .. . .. . .. . .. . .. .. . .. . .. . .. . .2-1

    2.1. Lexical Elements . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .2-12.1.1 . Comm ent s . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . 2-1

    2.1.2 . Iden t if iers . . . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .2-1

    2.1.3 . Nu mber s . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .2-1

    2.1.4 . Cha r act er s . . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . . 2-2

    2.1.5 . Strings . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . 2-2

    2.1.6. Bit St r ings . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . 2-2

    2.2. Data Types and Objects . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .2-2

    2.2.1 . Integer Types . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .2-3

    2.2.2. Ph ysical Types. . . . .. . .. . .. . .. . .. . .. . .. . .. . .. . . .. . .. . .. . .. . .. . .. . .. .2-3

    2.2.3. Float ing P oin t Types.... .. . .. . .. . . .. . .. . . .. . .. . .. . . .. . .. . .. . . .. . .2-4

    2.2.4. En um er a tion Types. . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .2-4

    2.2.5 . Arr a ys . . . .. . . .. . . .. . . .. . . .. . . .. . .. . . .. . .. . . .. . .. . . .. . .. . . .. . . .. . . .. . . .2-5

    2.2.6 . Records . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . 2-7

    2.2.7 . Subtypes . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. 2-7

    2.2.8. Object Declarat ions . . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. 2-8

    2.2.9 . Attr ibutes . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . 2-8

    2.3. Expressions and Operat ors . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .2-9

    2.4. Sequentia l Sta tements . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .2-10

    2.4.1. Var iable Assignm ent . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . . . .2-102.4.2. If Statement . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . .2-11

    2.4.3. Cas e St at emen t . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .2-11

    2.4.4. Loop Statements . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . .2-12

    2.4.5. Null Stat ement . . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . .2-13

    2.4.6. Assert ions . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . ..2-13

    2.5. Subprograms and Packages . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .2-13

    2.5.1. Procedures and Functions . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .2-14

    2.5.2. Overloading .. . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . .2-16

    2.5.3. Package and Package Body Declarations . . . . . . . . . . . . . . .2-172.5.4. Package Use and Name Visibility . . . . . . . . . . . . . .. . . . . . . . . . .2-18

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    5/111

    i v T he VHDL Cookbook

    Contents (cont'd)

    3. VHDL Describes Structure . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .3-1

    3.1. Ent ity Declarations . . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . . . .3-13.2. Architectur e Declarat ions . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .3-3

    3.2.1. Signal Declara tions . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. .3-3

    3.2.2. Blocks . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . .3-4

    3.2.3. Component Declara tions . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . .3-5

    3.2.4 . Component Ins tant ia t ion . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .3-6

    4. VHDL Describes Behaviour . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .4-1

    4.1. Signal Assignment . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .4-1

    4.2. Processes and the Wait Sta t ement . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . ..4-2

    4.3. Concur ren t Signal Assignment St at ement s. .. .. .. .. .. .. .. .. .. .. .. .4-4

    4.3.1 . Condit ional Signal Assignment . . . .. . . .. . . .. . . .. . . .. . . .. . . ..4-5

    4.3.2. Selected Signal Assignment . . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .4-6

    5. Model Organisation . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .5-1

    5.1. Design Un its an d Libra ries. . .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .5-1

    5.2. Configura tions . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .5-2

    5.3. Complete Design Example. . . . . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .5-5

    6. Advanced VHDL .. . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. .6-1

    6.1. Signal Resolution and Buses. . . . . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . . .6-1

    6.2. Null Transactions . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .6-2

    6.3. Gen er at e St at em ent s. . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . ..6-2

    6.4. Concurr ent Assert ions a nd P rocedur e Calls .. .. .. .. .. .. .. .. .. .. .. .6-3

    6.5. Enti ty Statements . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .6-4

    7. Sample Models: The DP32 Processor . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .7-1

    7.1. Ins truction Set Architectur e . . . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .7-1

    7.2. Bus Architectu re . . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . .7-4

    7.3. Types and Entity. . . . . . . . . . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . .7-67.4. Behavioura l Description .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . .7-9

    7.5. Test Bench .. . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .7-18

    7.6. Regis ter Transfer Architectur e . . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . 7-24

    7.6.1. Multiplexor . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . .7-25

    7.6.2. Transparent Latch . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. 7-25

    7.6.3. Buffer . . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . . . . .. . . . . . . . . .. . . . . . . . . .. . . . . 7-26

    7.6.4. Sign Ext en din g Bu ffer .... . . .. . .. . .. . . .. . .. . .. . . .. . .. . .. . . .. . .. 7-28

    7.6.5. La t ching Bu ffer . . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . .. . . .. . .. . .. 7-28

    7.6.6. Program Count er Register . . . .. . . .. . . .. . . .. . . .. . . .. . . .. . . .. . 7-287.6.7. Register File . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . .7-29

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    6/111

    Con ten ts v

    Contents (cont'd)

    7.6.8. Arithm etic & Logic Unit . . . . . . . . . . .. . . . . . . . . . . .. . . . . . . . . . .. . . .7-30

    7.6.9. Condition Code Compar ator . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .7-34

    7.6.10. Str uctur al Architectu re of th e DP32 .... . . . . . . . . . . . . . . . . . .7-34

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    7/111

    1-1

    1 . Introduction

    VHDL is a langu age for describing digita l electr onic system s. It a roseout of the U nited St at es Govern ment s Very H igh Speed Integra ted Circuits(VHSI C) program , initia ted in 1980. In t he cour se of th is progra m, itbecam e clear th at th ere was a n eed for a sta nda rd lan guage for describingth e stru ctu re an d fun ction of integrat ed circuits (ICs). Hence the VHSICHardware Description Language (VHDL) was developed, and subsequentlyadopted as a stan dar d by the Inst itut e of Electr ical an d Electr onic

    Engineers (IEE E) in t he US.VHDL is designed t o fill a nu mber of needs in t he design pr ocess.

    Fir stly, it allows descript ion of th e str uctu re of a design, th at is how it isdecomposed into sub-designs, and how those sub-designs areint erconn ected. Second ly, it allows the specificat ion of the function ofdesigns using fam iliar pr ogram ming langua ge form s. Thirdly, as aresult, it allows a design to be simulated before being manufactured, so thatdesigners can quickly compa re alter na tives and test for corr ectn ess withoutth e delay and expense of har dware pr ototyping.

    The pu rpose of this booklet is to give you a quick int roduction t o VHDL.This is done by informally describing the facilities provided by the

    lan guage, an d using examples to illust ra te th em. This booklet does notfully describe every aspect of th e langua ge. For su ch fine deta ils, youshould consu lt t he IEEE Standard VHDL Language Reference Manual.However, be warn ed: th e sta ndar d is like a legal docum ent, a nd is verydifficult t o read u nless you a re alr eady fam iliar with th e language. Thisbooklet does cover enough of th e langua ge for su bsta nt ial model writ ing. Itassu mes you know how to writ e compu ter progra ms u sing a convent iona lprogramming language such as Pascal, C or Ada.

    The remaining chapters of this booklet describe the various aspects ofVHDL in a bott om-up ma nn er. Cha pter 2 describes th e facilities of VHDLwhich most resemble norma l sequent ial program ming langua ges. These

    include dat a t ypes, var iables, expressions, sequential st at ement s an dsubprogra ms. Chapt er3 th en examines the facilities for describing thestructure of a module and how it it decomposed into sub-modules.Chapt er4 covers a spects of VHDL th at integrat e the pr ogram minglanguage features with a discrete event timing model to allow simulation ofbehaviour . Chapt er5 is a key cha pter t ha t sh ows how all these facilities arecombined t o form a complet e model of a system . Then Ch apt er6 is a pot-pourri of more advanced features which you may find useful for modelingmore complex systems.

    Throughout th is booklet, th e synta x of lan guage featu res is pr esented inBackus-Nau r Form (BNF). The synt ax specificat ions ar e drawn from t he

    IEE E VHDL Sta ndar d. Concrete exam ples ar e also given t o illustr at e thelangua ge feat ur es. In some cases, some alter na tives ar e omitt ed from BNF

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    8/111

    1-2 T he VHDL Cookbook

    A

    B

    Y

    F

    A

    BY

    G

    A

    BY

    H

    A

    B

    Y

    I

    FA

    B

    Y

    (a)

    (b)

    Figure 1-1. Exam ple of a structural description.

    productions where th ey ar e not directly relevant t o th e cont ext. For th is

    reason, the full syntax is included in AppendixA, and should be consultedas a reference.

    1.1. Describing Structure

    A digital electronic system can be described as a module with inputsan d/or out put s. The electr ical values on th e out put s are some fun ction ofth e values on th e input s. Figur e1-1(a) shows an exam ple of th is view of adigita l system . The module F ha s two input s, A and B, and an output Y.Usin g VHDL t erm inology, we call t he m odule F a design entity, and theinputs and outputs are called ports .

    One way of describing the function of a module is to describe how it iscomposed of sub-modules. Ea ch of th e sub-modules is an instance of someentit y, an d th e port s of th e insta nces ar e conn ected u sing signals.Figur e1-1(b) shows how th e ent ity F migh t be comp osed of inst an ces ofentities G, H and I. This kin d of descript ion is called a structuraldescript ion. Note th at each of th e ent ities G, H and I might also ha ve astructural description.

    1.2. Describing Behaviour

    In m an y cases, it is not appr opriat e to describe a m odule str uctur ally.One such case is a module which is at the bottom of the hierarchy of some

    oth er st ru ctu ra l description. For example, if you a re designing a systemusin g IC packages bought from a n I C shop, you do not n eed to describe t heinter na l stru ctu re of an IC. In su ch cases, a description of th e fun ctionperformed by the module is required, without reference to its actualinter nal str uctur e. Such a description is called a functional or behaviouraldescription.

    To illustra te t his, suppose th at th e function of the ent ity F inFigur e1-1(a) is the exclusive-or fun ction. Then a beha viour al description ofF could be th e Boolean function

    Y = A . B + A. B

    More complex beha viour s cann ot be described pu rely as a fun ction ofinput s. In systems with feedback, the out put s ar e also a function of time.VHDL s olves t his p roblem by allowing description of beha viour in t he form

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    9/111

    1. In trod u ction 1-3

    of an execut able progra m. Chapt ers2 and4 describe th e progra mm inglanguage facilities.

    1.3. Discrete Event Time Model

    Once the st ru ctu re a nd beha viour of a m odule ha ve been specified, it ispossible to simulat e the m odule by execut ing its beviour al descript ion. Thisis done by simu lat ing the pas sage of tim e in discret e steps. At somesimulat ion t ime, a m odule input m ay be stimulat ed by chan ging th e valueon a n inpu t port. The module reacts by run ning th e code of its behaviour aldescription and scheduling new values to be placed on the signalsconn ected to its out put port s at some later simu lat ed tim e. This is calledscheduling a transaction on th at signa l. If th e new valu e is differen t fromth e previous value on t he signal, an event occurs, and other modules withinput port s conn ected t o th e signa l may be activat ed.

    The simulation st art s with an initialisation phase, and th en pr oceeds byrepeat ing a t wo-sta ge simulation cycle. In the initialisation pha se, allsigna ls ar e given init ial values, the simu lation time is set t o zero, an d eachmodules beha viour pr ogra m is execut ed. This usu ally res ult s intr an sactions being scheduled on outpu t signa ls for some later time.

    In th e first sta ge of a simulat ion cycle, th e simulat ed time is a dvanced toth e ear liest time at wh ich a t ra nsaction ha s been scheduled. Alltransactions scheduled for that time are executed, and this may causeevents to occur on some signals.

    In th e second sta ge, all modules which rea ct to event s occur ring in th efirst st age have their behaviour progra m execut ed. These program s willusu ally schedule fur th er tr an sactions on th eir out put signals. When all ofth e behaviour progra ms ha ve finished execut ing, the simulat ion cyclerepeat s. If th ere are no more scheduled tra nsa ctions, the whole simu lationis completed.

    The pur pose of the simulat ion is t o gat her inform at ion a bout th echa nges in system sta te over t ime. This can be done by ru nn ing thesimulat ion un der t he cont rol of a simu lation m onitor. The monit or allowssignals an d oth er st at e inform at ion t o be viewed or st ored in a tr ace file forlat er an alysis. It ma y also allow int era ctive steppin g of th e simu lat ionprocess, much like an interactive program debugger.

    1.4. A Quick Example

    In th is section we will look a t a s ma ll exam ple of a VHDL descript ion ofa t wo-bit coun ter to give you a feel for t he lan guage an d how it is used. Westa rt th e descript ion of an ent ity by specifying its ext ern al int erface, whichincludes a description of its ports. So th e coun ter might be defined as:

    entity count2 isgeneric (prop_delay : Time := 10 ns);port (clock : in bit;

    q1, q0 : out bit);end count2;

    This specifies t ha t th e entity count2 ha s one input an d two out put s, all ofwhich ar e bit values, th at is, th ey can t ake on the values '0' or '1'. It a lsodefines a generic const an t called prop_delay which can be used t o cont rol th eopera tion of th e entit y (in th is case its pr opagat ion delay). If no value is

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    10/111

    1-4 T he VHDL Cookbook

    T_FLIPFLOP

    CK Q

    INVERTER

    A Y

    T_FLIPFLOP

    CK Q

    COUNT2

    CLOCK Q0

    Q1FF1

    FF0

    INV_FF0

    BIT_0

    BIT_1INV

    Figure1-2. S tru cture of coun t2.

    explicitly given for t his value wh en t he ent ity is used in a design, the defaultvalue of 10ns will be used .

    An implementation of the entity is described in an architecture body.There may be more than one architecture body corresponding to a singleentity specification, each of which describes a different view of the entity.For example, a behavioural description of the counter could be written as:

    architecture behaviour of count2 is

    begin

    count_up: process (clock)

    variable count_value : natural := 0;begin

    if clock = '1' thencount_value := (count_value + 1) mod 4;q0

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    11/111

    1. In trod u ction 1-5

    architecture structure of count2 is

    component t_flipflopport (ck : in bit; q : out bit);

    end component;

    component inverter

    port (a : in bit; y : out bit);end component;

    signal ff0, ff1, inv_ff0 : bit;

    begin

    bit_0 : t_flipflop port map (ck => clock, q => ff0);

    inv : inverter port map (a => ff0, y => inv_ff0);

    bit_1 : t_flipflop port map (ck => inv_ff0, q => ff1);

    q0

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    12/111

    2-1

    2 . VHD L is Lik e a P ro gra m min g La n gu a ge

    As m entioned in Section 1.2, the beha viour of a module may be describedin progra mm ing lan guage form . This cha pter describes the facilities inVHDL which are drawn from the familiar programming languagerepert oire. If you ar e fam iliar with t he Ada pr ogram ming langua ge, youwill notice th e similar ity with t ha t lan guage. This is both a conveniencean d a nuisa nce. The convenience is tha t you dont h ave much to lear n touse th ese VHDL facilities. The problem is tha t t he facilities ar e not a s

    comprehensive as those of Ada, though they are certainly adequate for mostmodeling purposes.

    2.1. Lexical Elements

    2.1 .1 . Comments

    Comm ent s in VHDL sta rt with t wo adjacent hyph ens (--) an d extend t oth e end of th e line. They have no par t in t he mea ning of a VHDLdescription.

    2.1.2. Identifiers

    Identifiers in VHDL are used as reserved words and as programmerdefined nam es. They mu st conform to the rule:

    ident ifier ::= lett er { [ und erline ] letter _or_digit }

    Note th at case of lett ers is n ot considered significan t, so the ident ifiers catand Cat ar e th e sam e. Under line cha ra cter s in ident ifiers are significan t,so This_Name and ThisName are different identifiers.

    2.1 .3 . Numbers

    Literal nu mbers m ay be expressed eith er in decimal or in a ba sebetween t wo and sixteen. If the litera l includes a point , it r epresents a realnu mber, oth erwise it represent s an integer. Decimal liter als are defined

    by:decima l_litera l ::= int eger [ . int eger ] [ exponen t ]

    int eger ::= digit { [ und er line ] digit }

    exponent ::= E [ + ] integer | E - integer

    Some examples are:

    0 1 123_456_789 987E6 -- integer literals

    0.0 0.5 2.718_28 12.4E-9 -- real literals

    Based liter al nu mbers a re defined by:

    based_liter al ::= base # ba sed_int eger [ . based_int eger ] # [ exponent ]

    base ::= integer

    based_int eger ::= exten ded_digit { [ und erline ] extended_digit }

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    13/111

    2-2 T he VHDL Cookbook

    extended_digit ::= digit | letter

    The base an d the exponent ar e expressed in decima l. The exponentindicat es the power of th e base by which the litera l is mu ltiplied. Thelett ers A to F (upper or lower case) ar e used as exten ded digits t o repr esent10 to 15. Some examples:

    2#1100_0100# 16#C4# 4#301#E1 -- the integer 196

    2#1.1111_1111_111#E+11 16#F.FF#E2 -- the real number 4095.0

    2.1.4. Characters

    Literal characters are formed by enclosing an ASCII character insingle-quote ma rk s. For example:

    'A' '*' ''' ' '

    2.1.5. Strings

    Literal st rings of cha ra cter s ar e form ed by enclosing th e cha ra cter s indouble-quote ma rk s. To include a double-quote ma rk it self in a str ing, a

    pair of double-quote ma rks m ust be put t ogeth er. A str ing can be used as avalue for an object which is an a rr ay of cha ra cter s. Exa mples of st rin gs:

    "A string""" -- empty string"A string in a string: ""A string"". " -- contains quote marks

    2.1.6. Bit Strings

    VHDL p rovides a convenient way of specifying litera l values for ar ra ys oftype bit ('0's an d '1's, see Section 2.2.5). The synt ax is:

    bit_string_literal ::= base_specifier " bit_value "

    base_specifier ::= B | O | X

    bit_value ::= extended_digit { [ un derlin e ] exten ded_digit }

    Base specifier B st an ds for bin ar y, O for octa l an d X for h exadecima l. Someexamples:

    B"1010110" -- length is 7O"126" -- length is 9, equivalent to B"001_010_110"X"56" -- length is 8, equivalent to B"0101_0110"

    2.2. Data Types and Objects

    VHDL p rovides a nu mber of basic, or scalar, types, and a mean s offorming com posite types. The scalar t ypes include num bers, physical

    quantities, and enumerations (including enumerations of characters), andth ere ar e a nu mber of sta nda rd pr edefined basic types. The composite typespr ovided ar e ar ra ys an d record s. VHDL also pr ovides access types(pointers) and files, alth ough th ese will not be fully described in t his booklet.

    A dat a t ype can be defined by a t ype declara tion:

    full_type_declar at ion ::= type identifier i s type_definition ;

    type_definition ::=

    scalar_type_definit ion

    | composite_type_definition

    | access_type_definition

    | file_type_definit ion

    scalar_type_definition ::=enum erat ion_type_definit ion | integer_type_definit ion

    | floating_type_definition | physical_type_definition

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    14/111

    2. VHDL is L ike a Program m in g Lan guage 2-3

    composite_type_definition ::=

    array_type_defini t ion

    | record_type_definit ion

    Exam ples of differen t kinds of type declar at ions ar e given in th e followingsections.

    2.2.1. Integer Types

    An integer type is a range of integer values within a specified range.The synt ax for specifying integer types is:

    integer_type_definition ::= range_constraint

    range_constraint ::= range range

    range ::= simple_expression direction simple_expression

    direction ::= to | downto

    The expressions that specify the range must of course evaluate to integernu mbers. Types declared with t he keyword to are called ascending ranges,an d th ose declared with th e keyword downto ar e called descending ranges.

    The VHDL standard allows an implementation to restrict the range, butrequir es that it mu st a t least allow the ran ge 2147483647 to +2147483647.

    Some examples of integer type declarations:

    type byte_int isrange 0 to 255;

    type signed_word_int isrange 32768 to 32767;

    type bit_index is range 31 downto 0;

    Ther e is a predefined integer t ype called integer. The ra nge of th is type isimplement at ion defined, th ough it is gua ra nt eed to include 2147483647 to+2147483647.

    2.2.2. Physical TypesA physical type is a numeric type for representing some physical

    qua nt ity, such as ma ss, length , tim e or volta ge. The declar at ion of aphysical t ype includes th e specificat ion of a ba se un it, a nd possibly anu mber of seconda ry un its, being mult iples of th e base un it. The synta x fordeclaring physical types is:

    physical_type_definition ::=

    range_cons t ra in t

    units

    base_uni t_declara t ion

    { seconda ry_un it_declar at ion }

    end units

    base_unit_declaration ::= identifier ;

    secondary_unit_declaration ::= identifier = physical_literal ;

    physical_literal ::= [ abstract_literal ] un i t _name

    Some examples of physical type declarations:

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    15/111

    2-4 T he VHDL Cookbook

    type length isrange 0 to 1E9units

    um;mm = 1000 um;cm = 10 mm;m = 1000 mm;

    in = 25.4 mm;ft = 12 in;yd = 3 ft;rod = 198 in;chain = 22 yd;furlong = 10 chain;

    end units;

    type resistance isrange 0 to 1E8units

    ohms;kohms = 1000 ohms;Mohms = 1E6 ohms;

    end units;

    The pr edefined ph ysical t ype time is import an t in VHDL, as it is usedextensively to specify delays in simu lat ions. It s definition is:

    type time is rangeimplementation_definedunits

    fs;ps = 1000 fs;ns = 1000 ps;us = 1000 ns;ms = 1000 us;sec = 1000 ms;min = 60 sec;hr = 60 min;

    end units;

    To writ e a value of some p hysical t ype, you writ e th e nu mber followed byth e un it. For exam ple:

    10 mm 1 rod 1200 ohm 23 ns

    2.2.3. Floating Point Types

    A float ing point type is a discrete a pproxima tion to th e set of rea lnu mber s in a specified ra nge. The precision of th e appr oximat ion is notdefined by th e VHDL language sta ndar d, but m ust be at least six decimaldigits. The ran ge mu st include at least 1E38 to +1E38. A float ing pointtype is declared u sing the synt ax:

    floating_type_definition := range_constraintSome examples are:

    type signal_level is range 10.00 to +10.00;

    type probability isrange 0.0 to 1.0;

    Ther e is a pr edefined float ing point type called real. The ran ge of th istype is implementation defined, though it is guaranteed to include 1E38 to+1E38.

    2.2.4. Enumeration Types

    An enu mera tion t ype is an ordered set of identifiers or char acters. Theidentifiers and characters within a single enumeration type must bedistinct, h owever t hey ma y be reused in several different enum erat iontypes.

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    16/111

    2. VHDL is L ike a Program m in g Lan guage 2-5

    The synta x for declar ing an enum erat ion t ype is:

    enum era tion_type_definition ::= ( enu mer at ion_liter al { , enu mer at ion_liter al } )

    enum erat ion_literal : := identifier | char acter_li teral

    Some examples are:

    type logic_level is (unknown, low, undriven, high);

    type alu_function is (disable, pass, add, subtract, multiply, divide);

    type octal_digit is ('0', '1', '2', '3', '4', '5', '6', '7');

    There are a number of predefined enumeration types, defined as follows:

    type severity_level is (note, warning, error, failure);

    type boolean is (false, true);

    type bit is ('0', '1');

    type character is (NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL,BS, HT, LF, VT, FF, CR, SO, SI,DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB,CAN, EM, SUB, ESC, FSP, GSP, RSP, USP,' ', '!', '"', '#', '$', '%', '&', ''','(', ')', '*', '+', ',', '-', '.', '/','0', '1', '2', '3', '4', '5', '6', '7','8', '9', ':', ';', '', '?','@', 'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'I', 'J', 'K', 'L', 'M', 'N', 'O','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z', '[', '\', ']', ' ', '_','`', 'a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n', 'o','p', 'q', 'r', 's', 't', 'u', 'v', 'w','x', 'y', 'z', '{', '|', '}', '~', DEL);

    Note th at type character is an exam ple of an en um erat ion type cont aining amixtur e of identifiers and char acters. Also, the cha ra cter s '0' and '1' ar emembers of both bit and character . Where '0' or '1' occur in a pr ogram , th econt ext will be used t o deter min e which t ype is being used.

    2.2.5. Arrays

    An array in VHDL is an indexed collection of elements all of the sametype. Arra ys may be one-dimensional (with one index) or m ult i-dimensiona l (with a nu mber of indices). In a ddition, an ar ra y type may beconst ra ined, in which th e boun ds for a n index ar e established when th etype is defined, or un const ra ined, in which th e boun ds a re established

    subsequently.The synta x for declar ing an a rr ay type is:

    array_type_definition ::=

    uncons tr a ined_ar ray_defini t ion | cons t r a ined_arra y_defini t ion

    uncons tra ined_array_defini t ion : :=

    array ( ind ex_subt ype_definit ion { , index_su bt ype_definit ion } )

    o felem ent_subtype_indication

    constrained_array_definit ion : :=

    array index_constraint o felement_subtype_indication

    index_subtype_definition ::= type_mark range

    index_constr ain t ::= ( discret e_ran ge { , discrete_ra nge } )

    discrete_range ::= discrete_subtype_indica t ion | range

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    17/111

    2-6 T he VHDL Cookbook

    Subt ypes, referr ed to in t his synt ax specificat ion, will be discussed in deta ilin Section2.2.7.

    Some exam ples of const ra ined ar ra y type declara tions:

    type word is array (31 downto 0) of bit;

    type memory is array (address) of word;

    type transform is array (1 to 4, 1 to 4) of real;

    type register_bank is array (byte range 0 to 132) of integer;

    An example of an unconstrained array type declaration:

    type vector is array (integer range ) of real;

    The symbol (called a box) can be t hough t of as a place-holder for theindex ran ge, which will be filled in later wh en th e arr ay type is used. Forexample, an object might be declared to be a vector of 20 elements by givingits type as:

    vector(1 to 20)

    There a re t wo predefined ar ra y types, both of which ar e un const ra ined.They ar e defined as:

    type string is array (positive range ) of character;

    type bit_vector is array (natural range ) of bit;

    The types positive and natural ar e subtypes ofinteger, defined in Section2.2.7below. The type bit_vector is par ticular ly useful in m odeling bina ry codedrepr esenta tions of values in simulat ions of digital system s.

    An element of an array object can referred to by indexing the name ofth e object. For exam ple, supp ose a and b are one- and two-dimensionalar ra y objects respectively. Then th e indexed na mes a(1) and b(1, 1) refer t o

    element s of th ese ar ra ys. Fu rt her more, a cont iguous slice of a one-dimensiona l arr ay can be referr ed to by using a ra nge as an index. Forexample a(8 to 15) is an eight-element array which is part of the array a.

    Somet imes you ma y need to writ e a liter al value of an a rr ay type. Thiscan be done u sing an ar ra y aggregat e, which is a list of element values.Suppose we have an a rr ay type declared as:

    type a is array (1 to 4) of character;

    and we want to write a value of this type containing the elements 'f', 'o', 'o','d' in th at order. We could write an a ggregate with positional associationas follows:

    ('f', 'o', 'o', 'd')

    in which t he element s ar e listed in th e order of th e index ra nge, sta rt ingwith t he left boun d of th e ran ge. Alter na tively, we could writ e an aggregat ewith named association:

    (1 => 'f', 3 => 'o', 4 => 'd', 2 => 'o')

    In this case, the index for each element is explicitly given, so the elementscan be in any order . Positiona l an d nam ed associat ion can be mixed with inan aggregat e, pr ovided all th e positional as sociat ions come first. Also, theword others can be used in place of an index in a named association,indicat ing a value to be used for a ll element s not explicitly ment ioned. Forexample, the same value as above could be written as:

    ('f', 4 => 'd', others => 'o')

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    18/111

    2. VHDL is L ike a Program m in g Lan guage 2-7

    2.2.6. Records

    VHDL provides basic facilities for records, which are collections ofna med element s of possibly differen t t ypes. The synt ax for declarin g recordtypes is:

    record_type_definition ::=

    recordelement_declara t ion

    { elemen t_declar at ion }

    end record

    element_declaration ::= identifier_list : element_subtype_definition ;

    ident ifier_list ::= ident ifier { , ident ifier )

    element_subtype_definition ::= subtype_indication

    An example r ecord type declara tion:

    type instruction isrecord

    op_code : processor_op;

    address_mode : mode;operand1, operand2: integer range 0 to 15;end record;

    When you n eed to refer t o a field of a record object, you use a selectedna me. For exam ple, suppose th at r is a record object containing a fieldcalled f. Then the name r.f refers to that field.

    As for arrays, aggregates can be used to write literal values for records.Both positiona l and na med association can be u sed, and t he sam e ru lesapply, with record field names being used in place of array index names.

    2.2.7. Subtypes

    The u se of a su btype allows th e values t ak en on by an object to berest ricted or const ra ined subset of some base type. The synta x for declar inga su btype is:

    subt ype_declar at ion ::= subtype identifier is subtype_indication ;

    subtype_indication ::= [ resolution_function_name ] type_mark [ constraint ]

    type_ma rk ::= type_name | subtype_n a m e

    constr aint : := ran ge_constraint | index_constr aint

    Ther e are two cases of subt ypes. Fir stly a subtype may const ra in valuesfrom a scalar t ype to be with in a specified ran ge (a r an ge const ra int ). Forexample:

    subtype pin_count is integer range 0 to 400;

    subtype digits is character range '0' to '9';

    Secondly, a subtype may constrain an otherwise unconstrained arraytype by specifying boun ds for t he indices. For exam ple:

    subtype id is string(1 to 20);

    subtype word is bit_vector(31 downto 0);

    There a re t wo predefined nu meric subtypes, defined as:

    subtype natural is integer range 0 tohighest_integer

    subtype positive is integer range 1 tohighest_integer

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    19/111

    2-8 T he VHDL Cookbook

    2.2.8. Object Declarations

    An object is a named item in a VHDL description which has a value of aspecified type. Ther e ar e th ree classes of objects: const an ts, var iables andsignals. Only th e first two will be discusses in t his section; signa ls will becovered in Section3.2.1. Declar at ion a nd u se of const an ts a nd var iables is

    very much like their use in programming languages.A const an t is an object which is initia lised to a specified value wh en it is

    crea ted, an d which ma y not be subsequent ly modified. The synta x of aconstant declaration is:

    const an t_declara tion : :=

    constant ident ifier_list : subt ype_indication [ := expression ] ;

    Constant declarations with the initialising expression missing are calleddeferr ed const an ts, an d m ay only appear in pa ckage declara tions (seeSection2.5.3). The initia l valu e mus t be given in th e corr espondin g packa gebody. Some exam ples:

    constant e : real := 2.71828;

    constant delay : Time := 5 ns;

    constant max_size : natural;

    A var iable is an object wh ose value m ay be cha nged after it is creat ed.The syntax for declaring variables is:

    variable_declaration : :=

    variable ident ifier_list : subt ype_indication [ := expression ] ;

    The initial value expression, if present, is evaluated and assigned to thevar iable when it is crea ted. If th e expression is absent, a defau lt value isassigned when t he varia ble is crea ted. The defau lt value for scalar t ypes isth e leftm ost value for t he t ype, that is the first in th e list of an enum erat ion

    type, the lowest in a n a scending ran ge, or t he highest in a descendingra nge. If th e var iable is a composite type, th e defau lt value is th ecomposition of th e defau lt valu es for each element , based on th e elementtypes.

    Some examples of variable declarations:

    variable count : natural := 0;

    variable trace : trace_array;

    Assuming t he t ype trace_array is an ar ra y ofboolean, then th e initial value ofth e var iable trace is an ar ra y with a ll element s having the value false.

    Given a n existing object, it is possible to give an alt ern at e na me t o th e

    object or part of it. This is done using an d alias declar at ion. The synta x is:alias_declaration ::= al ias identifier : su btype_indication i s name ;

    A reference to an alias is int erpr eted as a reference to th e object or par tcorr esponding to th e alias. For exam ple:

    variable instr : bit_vector(31 downto 0);

    alias op_code : bit_vector(7 downto 0) is instr(31 downto 24);

    declares the na me op_code to be an alias for t he left-most eight bits ofinstr.

    2.2.9. Attributes

    Types and objects declared in a VHDL description can have additional

    inform at ion, called at tr ibutes, associated with t hem. There are a num berof standa rd pre-defined at tr ibut es, and some of those for types and ar ra ys

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    20/111

    2. VHDL is L ike a Program m in g Lan guage 2-9

    ar e discussed her e. An at tr ibut e is referenced usin g th e ' nota tion. Forexample,

    thing'attr

    refers to the att ribute attr of the type or object thing.

    Fir stly, for a ny scalar t ype or su btype T, th e following at tr ibutes can beused:

    At t r ibute Resu lt

    T'left Left bound of T

    T'r igh t Right bound of T

    T'low Lower bound of T

    T 'h igh Upper bound of T

    For an a scendin g ra nge, T'left = T'low, an d T'right = T'high. For adescending range, T'left = T'high, and T'right = T'low.

    Secondly, for any discrete or physical type or subtype T, X a member of T,

    an d N a n int eger, th e following att ributes can be u sed:At t r ibute Resu lt

    T'pos(X) Posit ion num ber of X in T

    T'va l(N) Value a t posit ion N in T

    T 'le ftof(X) Value in T which is one pos it ion left from X

    T'rightof(X) Value in T which is one posit ion r ight from X

    T 'p red (X) Va lue in T wh ich is one pos it ion lower than X

    T 's u cc(X) Va lu e in T wh ich is on e p os it ion h igh er t h a n X

    For an ascending range, T'leftof(X) = T'pred(X), and T'rightof(X) =T'succ(X). For a de scendin g ra nge, T'leftof(X) = T'succ(X), an d T'righ tof(X)

    = T'pred(X).Thirdly, for a ny ar ra y type or object A, an d N a n int eger between 1 an d

    the number of dimensions of A, the following attributes can be used:

    At t r ibute Resu lt

    A'left (N) Left bound of index range of dimn N of A

    A'r igh t(N) Right bound of index range of dimn N of A

    A'low(N ) Lower bound of index range of dimn N of A

    A'h igh (N ) Upper bound of index range of dimn N of A

    A'r a n ge(N ) Index range of dimn N of A

    A'revers e_ra nge(N) Reverse of index range of dimn N of A

    A'len gt h(N) Length of index range of dimn N of A

    2.3. Expressions and Operators

    Expressions in VHDL are much like expressions in other programminglangua ges. An expression is a form ula combining prima ries withopera t ors . Pr ima ries include na mes of objects , liter als, function calls andpar enth esized expressions. Operat ors ar e listed in Table 2-1 in order ofdecreasing precedence.

    The logical opera tors and, or, nand, nor, xor and not operate on values oftype bit or boolean, an d also on one-dimen siona l arr ays of th ese types. Forar ra y operan ds, th e operat ion is applied between corr esponding elements ofeach ar ra y, yielding an arr ay of th e same length a s the result. For bit and

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    21/111

    2-10 T he VHDL Cookbook

    Highest precedence: ** abs not

    * / mod rem

    + (s ign ) (s ign )

    + &

    = /= < >=Lowest precedence: and or nand nor xor

    T able 7-1. Operators and precedence.

    boolean operands, and, or, nand, and nor ar e sh or t-cir cuit operat or s, th atis they only evalua te t heir r ight opera nd if th e left opera nd does notdeterm ine th e result. So and and nand only evalua te t he r ight operan d ifthe left operand is true or '1', and or and nor only evalua te t he r ightopera nd if th e left opera nd is false or '0'.

    The r elational operat ors =, /=, = mu st h ave both opera ndsof the sa me t ype, an d yield boolean resu lts. The equa lity opera tors (= an d /=)can ha ve opera nds of an y type. For composite types, two values ar e equa l ifall of th eir corr esponding element s ar e equal. The rema ining operat orsmust have operands which are scalar types or one-dimensional arrays ofdiscrete types.

    The sign operators (+ and ) and the addition (+) and subtraction ()operat ors have th eir usu al mean ing on num eric opera nds. Theconcatenation operator (&) operates on one-dimensional arrays to form anew array with the contents of the right operand following the contents ofth e left opera nd. It can also concatena te a single new element t o an a rr ay,or two individual elemen ts to form a n ar ra y. The concat ena tion opera tor is

    most commonly used with strings.

    The m ult iplicat ion (*) and division (/) opera tors work on int eger, float ingpoint a nd physical types types. The modulus (mod) and r emainder (rem)opera tors only work on integer t ypes. The absolut e valu e (abs) operatorwork s on a ny nu mer ic type. Fin ally, th e exponent iat ion (**) opera tor canha ve an int eger or float ing point left operand, but mu st h ave an integerright opera nd. A negat ive right opera nd is only allowed if th e left operan dis a float ing point nu mber.

    2.4. Sequential Statements

    VHDL contains a number of facilities for modifying the state of objectsan d cont rolling t he flow of execut ion of models. These a re discussed in t hissection.

    2.4.1. Variable Assignment

    As in other progra mm ing languages, a var iable is given a new valueusing an assignment st atement . The synta x is:

    variable_assignment_statement ::= target := expression ;

    tar get : := name | aggregate

    In t he simplest case, the ta rget of th e assignm ent is an object n am e, an dth e valu e of th e expression is given t o th e nam ed object. The object a nd t he

    value must h ave the sam e base type.

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    22/111

    2. VHDL is L ike a Program m in g Lan guage 2-11

    If th e tar get of th e assignm ent is an aggregat e, th en th e element s listedmust be object names, and the value of the expression must be a compositevalue of th e same type as th e aggregate. First ly, all the nam es in th eaggregat e are evaluat ed, th en th e expression is evalua ted, and last ly th ecomponents of the expression value are assigned to the named variables.

    This is effectively a pa ra llel assignm ent . For example, if a var iable r is arecord with two fields a and b, then th ey could be excha nged by writing

    (a => r.b, b => r.a) := r

    (Note that this is an example to illustrate how such an assignment works;it is not an example of good programming practice!)

    2.4.2. If Statement

    The if stat ement allows selection of sta tem ent s to execut e depending onone or more condit ions. The synta x is:

    if_statement ::=

    ifcondition then

    sequence_of_statements{elsif condition then

    sequence_of_statements }

    [ else

    sequence_of_statements ]

    end if ;

    The condit ions ar e expressions resu lting in boolean values. Theconditions are evaluated successively until one found that yields the valuetr ue. In tha t case the corr esponding sta temen t list is execut ed. Other wise,if the else clause is present, its statement list is executed.

    2.4.3. Case Statement

    The case statement allows selection of statements to execute dependingon t he value of a selection expr ession. The synt ax is:

    case_statement ::=

    case expression is

    case_s ta tement_al te rna t ive

    { case_sta temen t_alter na tive }

    end case ;

    case_statement_alternative : :=

    w h e n choices =>

    sequence_of_statements

    choices ::= choice { | choice }

    choice ::=simple_expression

    | d iscre te_ran ge

    | el emen t_s i m p l e _ n a m e

    | others

    The selection expression must result in either a discrete type, or a one-dimen siona l ar ra y of cha ra cters. The alter na tive whose choice listincludes the value of the expression is selected and the statement listexecut ed. Note tha t all th e choices must be distinct, tha t is, no value ma y beduplicat ed. Fu rt herm ore, all values must be represented in the choicelists, or the special choice others mu st be included as the last alter na tive. Ifno choice list includes t he valu e of the expression, th e oth ers a lter na tive is

    selected. If th e expression resu lts in an ar ra y, th en th e choices may bestrings or bit strings.

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    23/111

    2-12 T he VHDL Cookbook

    Some exam ples of case st at ement s:

    case element_colour ofwhen red =>

    statements for red;when green | blue =>

    statements for green or blue;

    when orange to turquoise =>statements for these colours;

    end case;

    case opcode ofwhen X"00" => perform_add;when X"01" => perform_subtract;when others => signal_illegal_opcode;

    end case;

    2.4.4. Loop Statements

    VHDL ha s a basic loop sta temen t, which can be augment ed to form th eusu al while and for loops seen in oth er progra mm ing lan guages. The

    synt ax of th e loop sta tem ent is:loop_statement ::=

    [ loop_label : ]

    [ iteration_scheme ] loop

    sequence_of_statements

    end loop [ loop_label ] ;

    iteration_scheme ::=

    whi le condition

    | fo r loop_parameter_specification

    parameter_specification ::=

    identifier in discrete_range

    If the iter at ion scheme is omitt ed, we get a loop which will repeat th eenclosed sta tem ent s indefinit ely. An exam ple of such a ba sic loop is:

    loopdo_something;

    end loop;

    The while itera tion schem e allows a t est condit ion t o be evalu at ed beforeeach iter at ion. The iter at ion only proceeds if th e test evalua tes to tr ue. Ifth e test is false, th e loop stat ement t ermina tes. An example:

    while index < length and str(index) /= ' ' loopindex := index + 1;

    end loop;

    The for iter at ion scheme allows a specified num ber of iter at ions. Theloop parameter specification declares an object which takes on successivevalues from th e given r an ge for each iter at ion of th e loop. Within t hesta tement s enclosed in t he loop, the object is tr eated a s a const an t, an d soma y not be ass igned to. The object does not exist beyond execution of theloop sta tem ent. An example:

    for item in 1 to last_item looptable(item) := 0;

    end loop;

    There ar e two additional st at ements which can be used inside a loop tomodify th e basic pat ter n of iter at ion. The next sta tem ent t erm ina tes

    execut ion of th e cur rent it erat ion and sta rt s the subsequent iter at ion. The

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    24/111

    2. VHDL is L ike a Program m in g Lan guage 2-13

    exit sta tem ent ter mina tes execut ion of the curr ent itera tion a ndterm inat es the loop. The synt ax of these stat ements is:

    next_statem ent ::= next [ loop_label ] [ w h e n condition ] ;

    exit_stat ement ::= exit [ loop_label ] [ w h e n condition ] ;

    If th e loop label is omit ted, th e stat ement applies to th e inner -most

    enclosing loop, oth erwise it a pplies to th e na med loop. If the wh en clau se ispresent but th e condition is false, the itera tion cont inues norma lly. Someexamples:

    for i in 1 to max_str_len loopa(i) := buf(i);exit when buf(i) = NUL;

    end loop;

    outer_loop : loopinner_loop : loop

    do_something;next outer_loop when temp = 0;do_something_else;

    end loop inner_loop;end loop outer_loop;

    2.4.5. Null Statement

    The nu ll sta tem ent h as no effect. It m ay be used to explicitly show tha tno action is required in cert ain cases. It is most often u sed in casestatements, where all possible values of the selection expression must belisted a s choices, but for some choices no action is requ ired . For exam ple:

    case controller_command iswhen forward => engage_motor_forward;when reverse => engage_motor_reverse;when idle => null;

    end case;

    2.4.6. Assertions

    An a ssert ion st at ement is used t o verify a specified condit ion a nd t oreport if th e condit ion is violat ed. The synta x is:

    assertion_stat ement ::=

    assert condition

    [ report expression ]

    [ severity expression ] ;

    If the report clau se is present, the r esult of th e expression m ust be a str ing.This is a m essage which will be report ed if th e condit ion is false. If it is

    omit ted, th e defau lt messa ge is "Assert ion violat ion". If the severity clau seis present th e expression mu st be of the t ype severity_level. If it is omit ted,th e defau lt is error. A simulat or ma y ter mina te execut ion if an a ssertionviolation occur s an d t he severity value is great er t ha n someimplementa tion dependent th reshold. Usua lly th e th reshold will be un deruser control.

    2.5. Subprograms and Packages

    Like other programming languages, VHDL provides subprogramfacilities in t he form of procedur es an d fun ctions. VHDL a lso provided apackage facility for collecting declarations and objects into modular units.

    Pa ckages also provide a m easur e of data abstr action a nd inform at ionhid ing .

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    25/111

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    26/111

    2. VHDL is L ike a Program m in g Lan guage 2-15

    parameter, in, the word constant could be omitt ed an d assumed. Theexpression after t he a ssignm ent opera tor is a defau lt expression, which isused if no actu al par am eter is a ssociated with incr in a call to the procedure.

    A call to a subprogram includes a list of actual parameters to beassociated with t he form al par am eters. This association list can be

    position, na med, or a combina tion of both . (Compa re t his with t he form at ofaggr egat es for valu es of composite types.) A call with p osit iona l associat ionlists th e actua l par am eters in the same order as th e form als. For example:

    increment_reg(index_reg, offset2); -- add value to index_reg

    increment_reg(prog_counter); -- add 1 (default) to prog_counter

    A call with na med a ssociation explicitly gives th e form al pa ra met er n am eto be associated with each actua l para meter , so th e para meter s can be inan y order . For exam ple:

    increment_reg(incr => offset2, reg => index_reg);

    increment_reg(reg => prog_counter);

    Note th at th e second call in each example does not give a value for t heforma l par ameter incr, so the default value is used.

    Thirdly, here is an example of function subprogram declaration:

    function byte_to_int(byte : word_8) return integer;

    The fun ction has one para met er. For fun ctions, th e par am eter mode mu stbe in, an d th is is assu med if not explicitly specified. If th e par am eter classis not specified it is a ssum ed t o be constant. The value retu rn ed by th e bodyof this fun ction m ust be an int eger.

    When the body of a subprogram is specified, the syntax used is:

    subprogram_body ::=

    subprogram_specification i ssubprogram_declarative_part

    begin

    subprogram_statement_part

    end [ designa tor ] ;

    subpr ogra m_declar at ive_par t ::= { subpr ogra m_declar at ive_item }

    subprogram _sta temen t_part ::= { sequential_stat ement }

    subprogram_declarative_item ::=

    subprogram_declara t ion

    | subprogram_body

    | type_declarat ion

    | subtype_declaration

    | cons tant _declara t ion| var iable_declara t ion

    | a l ias_declara t ion

    The declara tive items listed after th e subpr ogram specificat ion declareth ings which ar e to be used locally with in th e subprogram body. Thenam es of these items a re n ot visible out side of the subpr ogram, but ar evisible inside locally declared subpr ogram s. Fu rt her more, th ese item sshadow any things with the same names declared outside the subprogram.

    When th e subprogra m is called, th e stat ements in th e body are execut edunt il either t he end of th e stat ement list is encount ered, or a retu rnsta tement is execut ed. The synt ax of a retu rn st at ement is:

    retur n_statement ::= return [ expression ] ;

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    27/111

    2-16 T he VHDL Cookbook

    If a ret ur n st at ement occur s in a procedure body, it mu st n ot include anexpression. There must be at least one retur n sta tement in a fun ction body,it m ust ha ve an expression, an d t he function mu st complete by execut ing aretu rn st at ement. The value of th e expression is th e valued retu rn ed to th efunction call.

    Another point to note a bout function su bprogram s is th at th ey may notha ve an y side-effects. This mean s th at no visible var iable declar ed out sideth e fun ction body may be assigned to or a lter ed by th e fun ction. Thisincludes passing a non-local variable to a procedure as a variablepara meter with mode out or inout. The importa nt r esult of th is ru le is th atfunctions can be called without them having any effect on the environmentof the call.

    An example of a function body:

    function byte_to_int(byte : word_8) return integer isvariable result : integer := 0;

    beginfor index in 0 to 7 loop

    result := result*2 + bit'pos(byte(index));end loop;return result;

    end byte_to_int;

    2.5.2. Overloading

    VHDL allows two subprogra ms t o have the sa me n am e, provided th enu mber or base types of par am eters differs. The subprogra m na me is th ensaid to be overloaded. When a su bprogram call is ma de using anoverloaded name, the number of actual parameters, their order, their basetypes and the corresponding formal parameter names (if namedassociation is used) ar e used to determ ine which subpr ogram is mean t. Ifth e call is a function call, th e result t ype is also used. For example, supposewe declared the two subprograms:

    function check_limit(value : integer) return boolean;

    function check_limit(value : word_32) return boolean;

    Then which of the t wo functions is called depends on whet her a va lue oftype integer or word_8 is used as the actu al para meter . So

    test := check_limit(4095)

    would call the first function, and

    test := check_limit(X"0000_0FFF")

    would call the second function.The designa tor u sed to define a su bprogram can be eith er a n ident ifier

    or a str ing repr esent ing an y of th e opera tor symbols listed in Section2.3.The lat ter case a llows extra opera nd t ypes to be defined for t hose opera tors.For exam ple, th e addition opera tor m ight be overloaded t o add word_32operands by declaring a function:

    function "+" (a, b : word_32) return word_32 isbegin

    return int_to_word_32( word_32_to_int(a) + word_32_to_int(b) );end "+";

    Within t he body of th is fun ction, the a ddition opera tor is used t o add

    integers, since its operan ds ar e both integers. However, in th e expression:X"1000_0010" + X"0000_FFD0"

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    28/111

    2. VHDL is L ike a Program m in g Lan guage 2-17

    th e newly declar ed function is called, since the opera nds t o th e addit ionopera tor a re both of type word_32. Note th at it is also possible to calloperat ors using t he prefix notat ion used for ordina ry su bprogra m calls, forexample:

    "+" (X"1000_0010", X"0000_FFD0")

    2.5.3. Package and Package Body Declarations

    A package is a collection of types, constants, subprograms and possiblyoth er t hings, usually intended to implement some par ticular service or t oisolat e a group of relat ed item s. In par ticular , th e deta ils of const an t valuesand subprogram bodies can be hidden from users of a package, with onlyth eir int erfaces ma de visible.

    A package may be split into two parts: a package declaration, whichdefines its interface, and a package body, which defines the deferreddeta ils. The body par t ma y be omit ted if th ere ar e no deferr ed deta ils. Thesyntax of a package declaration is:

    package_declaration ::=package identifier is

    package_declarative_part

    e n d [package_simple_name ] ;

    package_declara tive_part ::= { package_declar at ive_item }

    package_declarative_item ::=

    subprogram_declara t ion

    | type_declaration

    | subtype_declaration

    | cons tant _declara t ion

    | a l ias_declara t ion

    | use_clause

    The declar at ions define th ings which a re t o be visible to user s of th epackage, and which ar e also visible inside th e package body. (Ther e arealso other kinds of declarations which can be included, but they are notdiscussed here.)

    An example of a package declaration:

    package data_types issubtype address is bit_vector(24 downto 0);subtype data is bit_vector(15 downto 0);constant vector_table_loc : address;function data_to_int(value : data) return integer;function int_to_data(value : integer) return data;

    end data_types;

    In th is exam ple, the value of the const an t vector_table_loc an d t he bodies ofth e two fun ctions ar e deferr ed, so a pa cka ge body needs t o be given.

    The synt ax for a p ackage body is:

    package_body ::=

    package body package_simple_name is

    package_body_declarative_part

    e n d [package_simple_name ] ;

    pa ckage_body_declar at ive_par t ::= { pa ckage_body_declar at ive_item }

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    29/111

    2-18 T he VHDL Cookbook

    package_body_declarative_item ::=

    subprogram_declara t ion

    | subprogram _body

    | type_declarat ion

    | subtype_declaration

    | cons tant _declara t ion

    | a l ias_declara t ion| use_clause

    Note that subprogram bodies may be included in a package body, whereasonly subprogram inter face declara tions ma y be included in t he pa ckageinterface declaration.

    The body for th e package data_types shown a bove might be written as:

    package body data_types is

    constant vector_table_loc : address := X"FFFF00";

    function data_to_int(value : data) return integer isbody of data_to_int

    end data_to_int;

    function int_to_data(value : integer) return data isbody of int_to_data

    end int_to_data;

    end data_types;

    In t his package body, th e value for t he const an t is specified, an d th efunction bodies ar e given. The subtype declar at ions ar e not repeat ed, asth ose in th e package declar at ions a re visible in th e package body.

    2.5.4. Package Use and Name Visibility

    Once a package has been declar ed, items declared with in it can be used

    by prefixing their na mes with th e package nam e. For exam ple, given t hepackage declar at ion in Section2.4.3 above, the it ems declared m ight be u sedas follows:

    variable PC : data_types.address;

    int_vector_loc := data_types.vector_table_loc + 4*int_level;

    offset := data_types.data_to_int(offset_reg);

    Often it is convenient to be able to refer t o na mes from a pa ckage with outha ving to qualify each use with t he package name. This may be done usinga use clau se in a declar at ion region. The synt ax is:

    use_clause ::= u s e selected _na me { , selected_na me } ;

    selected_name ::= prefix . suffixThe effect of th e use clau se is tha t a ll of th e listed n am es can subsequen tlybe used with out ha ving to prefix th em. If all of th e declar ed nam es in apackage ar e to be used in t his wa y, you can use t he special suffix all, forexample:

    use data_types.all;

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    30/111

    3-1

    3 . VHD L D es cribe s S tru ctu re

    In Section 1.1 we intr oduced some t erm inology for describing th estr uctur e of a digita l system. In t his cha pter, we will look at how str uctur eis described in VHDL.

    3.1. Entity Declarations

    A digital system is usually designed as a hierarchical collection of

    modules. Ea ch module has a set of port s which const itu te its int erface toth e out side world. In VHDL, an entity is such a module which may be usedas a component in a design, or which m ay be th e top level module of thedesign.

    The syntax for declaring an entity is:

    entity_declaration ::=

    ent ity identifier is

    entity_header

    entity_declarative_part

    [ begin

    entity_statement_part ]

    e n d [ entity_simple_name ] ;

    entity_header ::=

    [ formal_generic_clause ]

    [ formal_port_clause ]

    gener ic_clau se ::= g e n e r i c ( generic_list ) ;

    generic_list ::= generic_in terface_l is t

    port _clau se ::= port ( port_list ) ;

    port_list ::= port_interface_list

    ent ity_declar at ive_par t ::= { ent ity_declar at ive_item }

    The entity declara tive part may be u sed to declare items which ar e to beused in th e implement at ion of th e entity. Usua lly such declara tions will be

    included in the implementation itself, so they are only mentioned here forcompleteness. Also, the optiona l stat ements in th e entity declara tion m aybe used t o define some special beh aviour for monitoring opera tion of th eent ity. Discussion of these will be deferr ed un til Section6.5.

    The entity header is the most import an t par t of th e entity declara tion. Itmay include specification ofgeneric constants, which can be used to controlthe structure and behaviour of the entity, and ports , which cha nn elinform at ion int o an d out of th e entit y.

    The generic const an ts ar e specified using an inter face list similar toth at of a su bprogram d eclar at ion. All of th e item s mu st be of classconst an t. As a rem inder, the synta x of an in ter face const an t declara tion is:

    interface_constant_declaration : :=[ constant ] ident ifier_list : [ in ] subtype_indication [ := static_expression ]

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    31/111

    3-2 T he VHDL Cookbook

    A

    B

    Y

    ZDUT

    Y

    Z

    A

    BTG

    TEST_BENCH

    Figure 3-1. Test bench circuit.

    The actua l value for each generic const an t is passed in when th e entity isused a s a component in a design.

    The entity ports are also specified using an interface list, but the itemsin th e list m ust all be of class signal. This is a new kind of int erface itemnot previously discussed. The synt ax is:

    interface_signal_declaration : :=[ s ignal ] identifier_list : [ mode ] subtype_indication [ bus ]

    [ := static_expression ]

    Since the class must be signal, the word signal can be omitt ed and isassum ed. The word bus ma y be used if th e port is to be conn ected t o moreth an one out put (see Sections 6.1 and 6.2). As with generic const ant s theactu al signals t o be conn ected t o th e port s ar e specified when th e entit y isused a s a component in a design.

    To clarify this discussion, here are some examples of entitydeclarations:

    entity processor is

    generic (max_clock_freq : frequency := 30 MHz);port (clock : in bit;

    address : out integer;data : inout word_32;control : out proc_control;ready : in bit);

    end processor;

    In th is case, th e generic const an t max_clock_freq is used t o specify the t imingbeha viour of th e entit y. The code describing th e entit y's behaviour woulduse t his value to determ ine delays in chan ging signal values.

    Next, an exam ple showing how gener ic par am eters can be used tospecify a class of entities with varying structure:

    entity ROM isgeneric (width, depth : positive);port (enable : in bit;

    address : in bit_vector(depth1 downto 0);data : out bit_vector(width1 downto 0) );

    end ROM;

    Here, the two generic constants are used to specify the number of data bitsan d address bits respectively for th e rea d-only mem ory. Note tha t nodefau lt value is given for either of th ese const an ts. This means t ha t whenth e entity is used as a component, actua l values mu st be supplied for t hem.

    Finally an example of an entity declaration with no generic constants or

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    32/111

    3. VHDL Describes S tru cture 3-3

    ports:

    entity test_bench isend test_bench;

    Though this might at first seem to be a pointless example, in fact itillust ra tes a comm on u se of ent ities, shown in Figur e3-1. A top-level ent ity

    for a design u nder test (DUT) is used a s a component in a t est bench circuitwith an oth er ent ity (TG) whose pur pose is to genera te test valu es. Thevalues on signa ls can be tr aced u sing a simulat ion monitor, or checkeddirectly by th e test genera tor. No extern al conn ections from th e test benchar e needed, hence it h as n o port s.

    3.2. Architecture Declarations

    Once an entity h as h ad its int erface specified in an entit y declara tion,one or more implementations of the entity can be described in architecturebodies. Ea ch a rchitectur e body can describe a differen t view of th e entit y.For example, one architecture body may purely describe the behaviourusing the facili t ies covered in Chapters 2 and 4, whereas others maydescribe the structure of the entity as a hierarchically composed collectionof componen ts . In t his section, we will only cover st ru ctu ra l descr iptions,deferring behaviour descriptions until Chapter4.

    An ar chitectur e body is declared u sing th e synta x:

    architecture_body ::=

    architecture identifier ofentity_name is

    architecture_declarative_part

    begin

    architecture_statement_part

    end [ architecture_simple_name ] ;

    ar chitectu re_declara tive_par t ::= { block_declar at ive_item }

    ar chitectu re_statem ent_par t ::= { concurr ent_stat ement }

    block_declarative_item ::=

    subprogram_declara t ion

    | subprogram_body

    | type_declarat ion

    | subtype_declaration

    | cons tan t_declara t ion

    | s ignal_declara t ion

    | a l ias_declara t ion

    | component_declara tion

    | configurat ion_specificat ion

    | use_clause

    concurrent_statement : :=

    block_statement

    | component_ins tant ia t ion_sta tement

    The declara tions in th e ar chitectu re body define items t ha t will be used toconst ru ct th e design descript ion. In par ticular, signals and component sma y be declared h ere an d used t o const ru ct a str uctur al description inter ms of componen t inst an ces, as illust ra ted in Section1.4. These arediscussed in more deta il in th e next sections.

    3.2.1. Signal Declarations

    Signals ar e used to conn ect subm odules in a design. They ar e declar edusing the syntax:

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    33/111

    3-4 T he VHDL Cookbook

    signal_declaration : :=

    s ignal identifier_list : subtype_indication [ signal_kind ] [ := expression ] ;

    signal_kind ::= r e gi s te r | b u s

    Use of th e signa l kind specificat ion is covered in Section6.2. Omitt ing th esignal kind resu lts in an ord ina ry signa l of th e subtype specified. The

    expression in t he declara tion is used t o give th e signa l an initial valuedur ing the initialization ph ase of simulat ion. If th e expression is omitt ed,a default initial value will be assigned.

    One import an t point t o note is tha t port s of an object a re t rea ted exactlyas signals within t ha t object.

    3.2.2. Blocks

    The subm odules in an a rchitectu re body can be described as blocks. Ablock is a un it of module str uctu re, with its own int erface, conn ected t ooth er blocks or ports by signals. A block is specified using th e synta x:

    block_statement ::=

    block_label :block [ ( guard_express ion ) ]

    block_header

    block_declarative_part

    begin

    block_statement_part

    end block [ block_label ] ;

    block_header ::=

    [ generic_clause

    [ generic_map_aspect ; ] ]

    [ port_clau se

    [ port _map_aspect ; ] ]

    generic_map_aspect ::= gener ic map ( generic_association_list )port_map_aspect ::= port map (port_association_list )

    block_declar at ive_par t ::= { block_declar at ive_ite m }

    block_stat ement _part ::= { concur rent _statem ent }

    The gua rd expr ession is not covered in th is booklet, an d ma y be omit ted.The block hea der defines th e inter face to the block in m uch th e sam e way asan en tit y hea der defines the inter face to an en tit y. The gener ic associat ionlist specifies values for t he gener ic const an ts, evalua ted in th e cont ext of th eenclosing block or a rchitectu re body. The port ma p as sociat ion list specifieswhich actual signals or ports from the enclosing block or architecture bodyar e conn ected to the blocks port s. Note tha t a block sta tem ent pa rt ma y also

    cont ain block st at emen ts, so a design can be composed of a h iera rchy ofblocks, with behaviour al descriptions at th e bott om level of the h iera rchy.

    As an exam ple, suppose we want to describe a st ru ctu ra l ar chitectur e ofth e processor en tit y exam ple in Section3.1. If we separa te t he pr ocessorinto a cont rol unit a nd a dat a pa th section, we can write a description a s apair of interconnected blocks, as shown in Figure3-2.

    The control unit block has ports clk, bus_control and bus_ready, which a reconn ected t o th e processor ent ity port s. It a lso ha s an outpu t port forcont rolling t he da ta pat h, which is conn ected t o a signal declared in th ear chit ectu re. Tha t signal is also conn ected to a cont rol port on th e datapat h block. The address an d data port s of th e data pat h block ar e connected

    to th e corr espondin g ent ity port s. The advan ta ge of th is modulardecomposition is that each of the blocks can then be developed

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    34/111

    3. VHDL Describes S tru cture 3-5

    architecture block_structure of processor is

    type data_path_control is ;

    signal internal_control : data_path_control;

    begin

    control_unit : blockport (clk : in bit;

    bus_control : out proc_control;bus_ready : in bit;control : out data_path_control);

    port map (clk => clock,bus_control => control, bus_ready => ready;control => internal_control);

    declarations for control_unitbegin

    statements for control_unitend block control_unit;

    data_path : blockport (address : out integer;data : inout word_32;control : in data_path_control);

    port map (address => address, data => data,control => internal_control);

    declarations for data_pathbegin

    statements for data_pathend block data_path;

    end block_structure;

    Figu re3-2. S tru ctura l archit ectu re of processor exam ple.

    independently, with the only effects on other blocks being well definedth rough th eir interfaces.

    3.2.3. Component Declarations

    An architecture body can also make use of other entities describedsepara tely an d placed in design libra ries. In order to do th is, th ear chitectur e mu st declar e a component, which can be thought of as atemplat e defining a virt ual design ent ity, to be insta nt iated within t hear chit ectu re. Lat er, a configur at ion specificat ion (see Section3.3) can beused t o specify a mat ching librar y ent ity to use. The synt ax of a componentdeclaration is:

    component_declaration ::=

    component identifier

    [ local_generic_clause ]

    [ local_port_clause ]

    end component ;

    Some examples of component declarations:

    component nand3generic (Tpd : Time := 1 ns);port (a, b, c : in logic_level;

    y : out logic_level);end component;

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    35/111

    3-6 T he VHDL Cookbook

    component read_only_memorygeneric (data_bits, addr_bits : positive);port (en : in bit;

    addr : in bit_vector(depth1 downto 0);data : out bit_vector(width1 downto 0) );

    endcomponent;

    The first example declares a three-input gate with a generic parameterspecifying its propagat ion delay. Differen t inst an ces can la ter be used withpossibly differen t pr opagat ion delays. The second exam ple declar es a read -only memory component with addr ess depth a nd da ta width dependent ongeneric const an ts. This componen t could act as a tem plat e for t he ROMentity described in Section3.1.

    3.2.4. Component Instantiation

    A component defined in an architecture may be instantiated using thesyntax:

    component_instantiation_statement : :=

    instant ia t ion_label :component_n a m e

    [ generic_map_aspect ]

    [ port_map_aspect ] ;

    This indicates that the architecture contains an instance of the namedcomponent, with actual values specified for generic constants, and with thecomponent ports connected to actual signals or entity ports.

    The example components declared in the previous section might beinstantiated as:

    enable_gate: nand3port map (a => en1, b => en2, c => int_req, y => interrupt);

    parameter_rom: read_only_memorygeneric map (data_bits => 16, addr_bits => 8);port map (en => rom_sel, data => param, addr => a(7 downto 0);

    In the first instance, no generic map specification is given, so the defaultvalue for the generic constant Tpd is used. In th e second inst an ce, valuesar e specified for t he addr ess and data port sizes. Note th at th e actu al signalassociated with th e port addr is a slice of an a rr ay signal. This illustr at esth at a port which is an ar ra y can be conn ected t o par t of a signal which is alarger array, a very common practice with bus signals.

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    36/111

    4-1

    4 . VHDL D es cribe s B eh av io ur

    In Section 1.2 we sta ted th at th e behaviour of a digital system could bedescribed in ter ms of progra mm ing lan guage nota tion. The fam iliarsequential programming language aspects of VHDL were covered in detailin Chapter 2. In this chapt er, we describe how these are extended toinclude sta tem ents for modifying values on signals, and mean s ofresponding to the changing signal values.

    4.1. Signal Assignment

    A signal a ssignm ent schedules one or more tr an sactions t o a signal (orport ). The synt ax of a signal assignm ent is:

    signal_assignmen t_statemen t ::= target

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    37/111

    4-2 T he VHDL Cookbook

    20ns

    '1'

    36ns

    '0'

    Note t hat when mu ltiple tran sactions a re listed in a signal assignment , thedelay times specified must be in ascending order.

    If a signa l assignment is execut ed, and t here a re a lready oldtransactions from a previous assignmenton the projected output waveform,th en some of th e old tra nsa ctions ma y be deleted. The way this is donedepends on whether the word transport is included in the new assignment.If it is included, the a ssignm ent is said to use transport delay. In this case,all old tr an sactions scheduled to occur after t he first new tr an saction a redeleted before th e new tran sactions ar e added. It is as th ough th e newtr an sactions sup ercede th e old ones. So given th e projected out putwaveform shown imm ediately above, if th e assignm ent:

    s

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    38/111

    4. VHDL Describes B eh aviour 4-3

    tim e, they execut e concur ren tly. A pr ocess is specified in a pr ocessstat ement, with th e synta x:

    process_sta tem ent ::=

    [process_label : ]

    process [ ( sensitivity_list ) ]

    process_declarative_partbegin

    process_statement_part

    end process [process_label ] ;

    pr ocess_declara tive_par t ::= { pr ocess_declara tive_item }

    process_declarative_item ::=

    subprogram_declara t ion

    | subprogram_body

    | type_declarat ion

    | subtype_declaration

    | cons tant _declara t ion

    | var iable_declara t ion

    | a l ias_declara t ion| use_clause

    process_sta temen t_part ::= { sequential_statem ent }

    sequential_stat ement ::=

    wait_statement

    | asser t ion_s ta tement

    | s igna l_as s ignment_s ta tement

    | var iable_ass ignment _s ta t ement

    | procedure_call_stat ement

    | i f_s ta tement

    | case_s ta tement

    | loop_statement

    | next_s ta tement| exi t_s ta tement

    | r e tu rn_s ta tement

    | nu l l_s ta tement

    A process stat ement is a concurr ent st at ement which can be used in anar chit ectu re body or block. The declar at ions define item s which can beused locally within t he process. Note tha t var iables may be defined hereand u sed to store stat e in a model.

    A process may contain a number of signal assignment statements for agiven signal, which together form a driver for the signal. Normally th erema y only be one dr iver for a signal, an d so the code which deter min es a

    signals value is confined t o one pr ocess.A process is activated initially during the initialisation phase of

    simulat ion. It execut es all of th e sequential stat ement s, an d then repeat s,sta rt ing again with th e first sta temen t. A process may suspended itself byexecut ing a wait st at ement . This is of th e form :

    wait_statement ::=

    wait [ sensitivity_clause ] [ condition_clause ] [ timeout_clause ] ;

    sensitivity_clause ::= o n sensitivity_list

    sensitivity_list ::= signal_na me { , signal_name }

    condition_clause ::= unt i l condition

    timeout_clause ::= fo r time_expression

    The sensit ivity list of th e wait st at ement specifies a set of signals towhich the process is sensit ive while it is suspend ed. When an event occur s

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    39/111

    4-4 T he VHDL Cookbook

    on a ny of th ese signa ls (th at is, the valu e of the signa l cha nges), th e processresu mes an d evalua tes t he condit ion. If it is tr ue or if th e condit ion isomitt ed, execut ion procedes with th e n ext sta temen t, otherwise t he pr ocessresu spends. If th e sensit ivity clau se is omit ted, then t he process issensit ive to all of th e signa ls ment ioned in th e condit ion expression. The

    timeout expression m ust evalua te t o a positive dur at ion, an d indicat es th ema ximum t ime for which th e process will wait . If it is omit ted, th e processmay wait indefinitely.

    If a sensitivity list is included in the header of a process statement, thenth e process is assum ed to have an implicit wait st at ement at th e end of itssta tement par t. The sensitivity list of th is implicit wait stat ement is thesam e as tha t in th e process header. In t his case th e process may notcont ain a ny explicit wait sta temen ts.

    An example of a process statements with a sensitivity list:

    process (reset, clock)variable state : bit := false;

    beginif reset then

    state := false;elsif clock = true then

    state := not state;end if;q

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    40/111

    4. VHDL Describes B eh aviour 4-5

    concurr ent_s ignal_ass ignmen t_s ta tem ent ::=

    [ label : ] conditional_signal_assignment

    | [ label : ] selected_signa l_assignmen t

    For each kind of concurr ent signa l assignment , ther e is acorresponding process statement with the same meaning.

    4.3.1. Conditional Signal Assignment

    A conditional signal assignment statement is a shorthand for a processcont aining signal assignm ent s in an if sta tem ent. The synt ax is:

    conditional_signal_assignment ::= target

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    41/111

    4-6 T he VHDL Cookbook

    The degenerat e case of a conditional signal a ssignm ent , cont aining n oconditional parts, is equivalent to a process containing just a signalassignment stat ement. So:

    s

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    42/111

    4. VHDL Describes B eh aviour 4-7

    In t his example, the value of the signal alu_function is used to select whichsigna l assignment t o alu_result to execut e. The stat ement is sensitive to thesignals alu_function, op1 and op2, so whenever any of these change value, theselected signal assignment is resumed.

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    43/111

    5-1

    5. Mode l Organ isatio n

    The pr evious cha pter s ha ve described t he var ious facilities of VHDLsomewh at in isolat ion. The pur pose of th is cha pt er is to show how th ey ar eall tied t ogether to form a complet e VHDL description of a digita l system.

    5.1. Design Units and Libraries

    When you write VHDL descriptions, you write them in a design file,

    th en invoke a compiler to analyse them a nd insert th em into a designlibrary. A nu mber of VHDL const ru cts m ay be separ at ely an alysed forinclusion in a design librar y. These const ru cts ar e called library units.Th e primary libra ry un its ar e entity declara tions, package declara tions a ndconfigura tion declara tions (see Section 5.2). The secondary library u nitsar e ar chit ectu re bodies an d packa ge bodies. These libra ry unit s depend onth e specificat ion of their inter face in a corr esponding pr imar y librar y un it,so th e prima ry un it m ust be ana lysed before a ny corr esponding seconda ryun i t .

    A design file ma y cont ain a n um ber of librar y un its. The str uctu re of adesign file can be specified by the syntax:

    design _file ::= design_un it { design _un it }design_unit ::= context_clause library_unit

    cont ext_clau se ::= { cont ext _item }

    context_item ::= libra ry_clause | use_clause

    library_clause ::= l ibrary logical_name_list ;

    logical_n am e_list ::= logical_na me { , logical_na me }

    librar y_un it ::= primar y_un it | secondar y_unit

    primary_unit : :=

    entity_declara tion | configur ation_declarat ion | package_declara tion

    secondar y_un it ::= architectur e_body | package_body

    Libra ries ar e referr ed to usin g ident ifiers called logical nam es. Thisnam e must be tr an slated by th e host operat ing system into animplementa tion dependent st ora ge na me. For example, design libra riesma y be implement ed as da ta base files, and th e logical na me m ight be usedto determ ine the data base file nam e. Libra ry units in a given librar y can bereferr ed to by prefixing their n am e with th e librar y logical na me. So forexample, ttl_lib.ttl_10 would r efer t o th e unit ttl_10 in librar y ttl_lib.

    The context clause preceding each library unit specifies which otherlibrar ies it references and which packages it u ses. The scope of th e nam esma de visible by the cont ext claus e exten ds un til th e end of th e design u nit .

    There are two special libraries which are implicitly available to all

    design u nit s, and so do not need to be na med in a libra ry claus e. The first ofth ese is called work, and refers t o the working design librar y into which t he

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    44/111

  • 8/3/2019 Livro_The VHDL Cookbook - 1ed

    45/111

    5.M od el Organ isat ion 5-3

    entity processor isgeneric (max_clock_speed : frequency := 30 MHz);port ( port list);

    end processor;

    architecture block_structure of processor is

    declarations

    begin

    control_unit : blockport ( port list);port map ( association list);declarations for control_unit

    beginstatements for control_unit

    end block control_unit;

    data_path : blockport ( port list);

    port map ( association list);declarations for data_pathbegin

    statements for data_pathend block data_path;

    end block_structure;

    Figure 5-1. Exam ple processor entity and architecture body.

    port_map_aspect ::= port map (port_association_list )

    The declarative part of the configuration declaration allows theconfigura tion to use items from libra ries an d packages. The out erm ostblock configuration in the configuration declaration defines theconfigura tion for a n a rchitectu re of th e nam ed entity. For exam ple, inChapter 3 we had an example of a processor entity and ar chitectur e,out lined again in Figure5-1. The overall str uctu re of a configur at iondeclara tion for t his ar chitectur e might be:

    configuration test_config of processor is

    use work.processor_types.all

    for block_structureconfiguration items

    end for;end test_config;

    In this example, the contents of a package call