Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução...

44
Tutorial sobre VHDL Alexandre Mendonça Professor das disciplinas: Circuitos Combinacionais e Seqüenciais, Eletrônica Digital e Microprocessadores do IME Instituto Militar de Engenharia - 2002

Transcript of Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução...

Page 1: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre

VHDL

Alexandre MendonçaProfessor das disciplinas:Circuitos Combinacionais eSeqüenciais, Eletrônica Digital eMicroprocessadores do IME

Instituto Militar de Engenharia - 2002

Page 2: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

2 Alexandre Mendonça

1. Introdução

A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma linguagem

de alto nível para descrever a funcionalidade de um hardware.

Certamente, a opção por projeto via HDL, como no pacote Foundation da Xilinx (fig. 1) para

desenvolvimento com FPGA, implica num grau de complexidade maior a nível de projeto, pois

este passa a ser desenvolvido utilizando uma linguagem de programação, contrapondo-se às

facilidades do uso de diagramas de esquemáticos. Contudo, existem algumas vantagens

interessantes de um projeto em HDL, dentre elas:

� portabilidade: um projeto escrito em HDL pode ser aproveitado por qualquer

ferramenta de desenvolvimento de FPGA ou mesmo para a confecção de um

integrado VLSI;

� atualização: versões do projeto são facilmente readaptáveis, bastando alterar o

código fonte;

� interface de alto nível com a eletrônica: um projeto HDL não trabalha diretamente

com os elementos básicos da eletrônica digital, como flip-flops, contadores,

registradores, etc., já que todo o cadenciamento de sinais é estabelecido a nível de

software.

Existe um bom número de linguangens descritivas de hardware, contudo, no presente texto,

será abordado o VHDL.

2. HDL no Foundation

O Foundation oferece algumas facilidades no projeto usando HDL, como a criação de macros,

a conexão com blocos escritos em diagrama de esquemáticos, a possibilidade de simulações,

a identação automática e um assistente de linguagem (fig. 2). Este assistente facilita a inserção

de linhas de código, como declarações de entidades (fig. 3), repetições, etc., bem como a

rápida declaração dos dispositivos digitais mais comuns, tais como contadores e flip-flops. Isto

tudo será visto mais adiante.

Page 3: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 3

Figura 1. Como optar por um projeto via HDL no Foundation.

Figura 2. Como chamar o assistente HDL.

Page 4: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

4 Alexandre Mendonça

Figura 3. Com o assistente, facilita-se o uso de declarações (basta clicar em "Use").

O assistente traz também as funcionalidades dos componentes digitais mais comuns, que

podem ser rapidamente acrescentados a um projeto. A figura 4 mostra um exemplo com um

registrador de deslocamento.

Figura 4. O assistente facilita também o uso dos componentes digitais mais comuns.

Page 5: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 5

3. Pacotes

Um pacote é útil para permitir que módulos e projetos distintos compartilhem das declarações

realizadas dentro de um arquivo. A definição de um pacote é referenciada pela palavra

reservada package, conforme modelo a seguir.

package nome_package is...

end nome_package;

4. Entidades e Arquiteturas

Um dispositivo digital é definido através do uso simultâneo de entidades e arquiteturas. A

entidade, declarada via palavra reservada entity, amarra a interface do dispositivo com os

outros dispositivos, enquanto que a arquitetura (declarada pela palavra reservada

architecture) descreve o comportamento lógico do dispositivo.

entity nome_entity is-- declarações de generics e ports-- declarações de constants, types e signals...

end nome_entity;

architecture nome_architecture of nome_entity is-- declarações...

end nome_architecture;

Sejam os exemplos a seguir que definem entidades para comparadores de 1 e 10 bits. Nota-se

que o comparador de 1 bit possui 2 sinais de entrada (do tipo bit) e 1 sinal de saída (também

do tipo bit), enquanto que o comparador de 10 bits tem como entradas 2 palavras (tipo integer)

de 10 bits e tem 1 bit como saída.

entity comparador_1bit isport (A, B: in bit;

C: out bit);end comparador_1bit;

Exemplo 1. Entidade para um comparador de 1 bit.

Page 6: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

6 Alexandre Mendonça

entity comparador_10bits isport (A, B: in integer range 0 to 9 :=0;

C: out boolean);end comparador_10bits;

Exemplo 2. Entidade para um comparador de até 10 bits.

Para descrever o comportamento, as interconexões e a lógica do dispositivo declarado por uma

entidade, é necessária então a descrição de uma arquitetura. Assim, possíveis implementações

de arquiteturas para os comparadores de 1 e 10 bits estão exemplificadas em conformidade

com as declarações de entidades apresentadas.

architecture comportamento of comparador_1bit isbegin

C <= not (A xor B);end comportamento;

Exemplo 3. Arquitetura para um comparador de 1 bit.

architecture comportamento of comparador_10bits isbegin

process(A, B)begin

if (A = B) thenC <= '1';

elseC <= '0';

end if;end process;

end comportamento;

Exemplo 4. Arquitetura para um comparador de até 10 bits.

Em VHDL, é permitido também especificar um retardo para uma função lógica, através da

palavra reservada after. Vide exemplo 5.

architecture comportamento of comparador_1bit isbegin

C <= not (A xor B) after 10 ns;end comportamento;

Exemplo 5. Arquitetura para um comparador de 1 bit.

Um oscilador de 20 MHz poderia então ser implementado com o código "clk <= not (clk)after 50 ns;"

Page 7: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 7

5. Conexão de Componentes

Uma forma alternativa de implementar-se um comparador de 1 bit é conectar a saída de uma

porta XOR à entrada de um inversor. Em VHDL, isto é possível graças ao uso do recurso

"componente" (palavra reservada component). Os exemplos 6 e 7 definem as entidades e

arquiteturas das portas XOR e INV, que são aproveitados no exemplo 8, que redefine a

arquitetura do comparador (a entidade do exemplo 1 é mantida). Deve-se notar os usos das

palavras reservadas generic, para a definição de constantes, signal, para a declaração de

variáveis fisicamente implemenadas, e port map, para definir as conexões dos componentes.

entity xor2 isgeneric (atraso: time := 7 ns);port (A, B: in bit;

C: out bit);end xor2

architecture comportamento of xor2 isbegin

C <= A xor B after atraso;end comportamento;

Exemplo 6. Entidade e arquitetura de uma porta XOR.

entity inv isgeneric (atraso: time := 3 ns);port (A: in bit;

B: out bit);end inv

architecture comportamento of inv isbegin

B <= not (A) after atraso;end comportamento;

Exemplo 7. Entidade e arquitetura de uma porta inversora.

architecture comportamento of comparador_1bit issignal: saida_xor;component xor2 port(A,B:in bit;C:out bit); end component;component inv port(A:in bit;B:out bit); end component;begin

U0: xor2 port map (A,B,saida_xor);U1: inv port map (saida_xor,C);

end comportamento;

Exemplo 8. Nova arquitetura para um comparador de 1 bit.

Page 8: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

8 Alexandre Mendonça

6. Configurações

As configurações são úteis para definir a abrangência do escopo de entidades. Por exemplo,

supõe-se que estejam disponíveis para o projeto várias bibliotecas e que cada uma delas tenha

definido seu próprio par entidade/arquitetura para uma porta XOR. Através do uso de labels e

das palavras reservadas configuration, for e use, pode-se definir escopos locais para cada

componente. Seja o exemplo 9. Nele, o label U0 indica que a porta XOR está definida na

biblioteca capalex. Idem para o inversor.

entity comparador_1bit isport (A, B: in bit;

C: out bit);end comparador_1bit;

configuration minha_configuração of comparador_1bit isfor comportamento

for U0: xor2 use entity capalex.xor2(comportamento);end for;for U1: inv use entity capalex.inv(comportamento);end for;

end for;end minha_configuração;

architecture comportamento of comparador_1bit issignal: saida_xor;component xor2 port(A,B:in bit;C:out bit); end component;component inv port(A:in bit;B:out bit); end component;begin

U0: xor2 port map (A,B,saida_xor);U1: inv port map (saida_xor,C);

end comportamento;

Exemplo 9. Nova arquitetura para um comparador de 1 bit.

7. Tipos e Objetos

Esta seção se destina a apresentar os tipos escalares e matriciais da linguagem VHDL, bem

como alguns dos objetos também disponíveis. A figura 5 tabela e descreve os tipos:

� character,

� bit,

� std_logic,

� boolean,

� real,

� integer,

� time,

� string,

� bit_vector e

� std_logic_vector.

Page 9: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 9

Já a figura 6 descreve os objetos:

� variable,

� signal,

� type;

� array,

� range e

� constant.

TipoEscalar

ouMatricial

Exemplos Comentários

bit escalar '0' , '1' , bit'('1') correspondem aos níveis lógicos 0 e 1

std_logic escalar

'U' ,'X' ,'0' ,'1' ,'Z' ,'W' ,'L' ,'H' ,'-'

(correspondem aos níveis de sinal do padrão IEEE 1164)

→ não inicializado→ valor desconhecido→ nível digital 1→ nível digital 0→ alta impedância→ sinal fraco com nível digital desconhecido→ sinal fraco com nível digital 0→ sinal fraco com nível digital 1→ don't care

boolean escalarTRUE ,FALSE

→ verdadeiro→ falso

character escalarcharacter'('1') ,

'A' , 's' , '4' ,FF , ESC

→ caracter '1', que é diferente do bit '1'→ caracteres entre ' '→ Form Feed, escape, etc.

integer escalar1 , -245 ,

16#2A3E# ,8#3477#

→ inteiros na base 10 (decimal)→ inteiros na base 16 (hexadecimal)→ inteiros na base 8 (octal)

real escalar -1.0 , 2.0E+38 → números a ponto-flutuante

time escalar1 ns , 10 us ,

1000 ms, 2 sec→ nanossegundos, microssegundos→ milissegundos, segundos

string matricial "start bit" → seqüência de caracteres entre aspas

bit_vector matricial"00110000" ,

"0011_0000" ,x"A32A"

→ vetor de 8 bits→ idem (o underscore é para identação)→ vetor de 16 bits (representado em hexa)

std_logic_vector matricial "00Z1" → vetor de níveis de sinal

Figura 5. Tipos do VHDL.

Com relação aos sinais do tipo std_logic, vale ressaltar que, como hierarquia, vale o que

acontece num curto elétrico. Assim, se um processo possuir as seguintes linhas de código:

Page 10: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

10 Alexandre Mendonça

...B <= '1';B <= 'Z';B <= 'L';...

O sinal B ficará com o nível '1', visto que, em VHDL, as atribuições não são seqüenciais, mas

sim em paralelo. Estas linhas de código equivalem a dizer que, num ponto B, existe um curto

entre +Vcc, a saída em alta impedância de um buffer tri-state e um resistor de pull-down.

Objeto Exemplos Comentários

variable variable x: integer; define uma variável meramente computacional

signal signal x: integer; define um sinal implementado eletricamente

type earray

type rom3x3 is array (0 to 2, 0 to 2) of std_logic;

define um tipo matricial 3x3 de sinais do tipostd_logic

range D: in integer range 0 to 255; restinge os possíveis valores de uma variável ousinal

constant constant PI: real := 3.14159; define uma constante

Figura 6. Alguns objetos do VHDL.

Seguem alguns exemplos de declarações com os objetos da figura 6.

signal contador: integer range 1 to 50;variable atraso: time range 10 ns to 500 ns;variable terra: bit:= '0';signal barramento_dados: std_logic_vector (7 downto 0);type rom5x5 is array (0 to 4, 0 to 4) of std_logic;constant minha_rom: rom5x5:= ( ('0','1','0','1','0'),

('1','1','0','1','0'),('1','1','0','1','0'),('1','0','0','1','0'),

('0','0','0','1','0') );variable A: bit;

A <= minha_rom(3,4);type rom2Kx8 is array (0 to 2047)

of std_logic_vector(7 downto 0); barramento_dados <= minha_rom(endereço);

7. Operadores

A figura 7 apresenta os operadores definidos em VHDL em ordem decrescente de hierarquia.

Page 11: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 11

Símbolo Exemplos Comentários

**absnot

A <= B ** 10;A <= abs B;A <= not B;

→ exponenciação→ valor absoluto→ complemento

*/

modrem

A <= B * 10;A <= 120 / B;A <= A mod B;A <= A rem B;

→ multiplicação→ divisão→ módulo→ resto

&+-

A <= B & "0110";A <= 10 ns + 1 us;A <= B - C;

→ concatenação→ soma→ subtração

>= , <= , > , < ,/= , = ,

xor , nor

if A >= Bif A/= BA <= B xor C;

→ maior ou igual, menor ou igual, maior, menor→ não igual, igual→ porta XOR, porta NOR

and , or , nand A <= B and C; → porta AND, porta OR, porta NAND

Figura 7. Operadores do VHDL (ordem decrescente de hierarquia).

A revisão da linguagem VHDL de 1993 incorporou ainda os seguintes operadores:

� sll (deslocamento lógico à esquerda),

� sla (deslocamento aritméticoà esquerda),

� rol (roda à esquerda),

� ror (roda à direita),

� srl (deslocamento lógico à direita),

� sra (deslocamento aritmético à direita),

� xnor (comparação).

8. Controle Seqüencial

Como toda linguagem de programação, o VHDL também prevê palavras reservadas com o

objetivo de realizar o controle seqüencial do hardware. São elas: process, if, wait, case, loop,

next, exit, assert, dentre outras. Seja o exemplo de uma entidade e de uma arquitetura que

implementem um barramento mutiplexado, onde exista um sinal de interface AouB que decida

se o barramento D será carregado com a palavra A ou com a palavra B, com a condição do

sinal habilitador G estar ativado. A primeira novidade do exemplo 10 é a palavra process,

relativa a um processo. Uma arquitetura pode conter vários processos, que são implementados

a nível de hardware de forma paralela. No caso do exemplo, existe apenas um processo, onde

uma alteração no estado do hardware só pode acontecer quando houver alguma variação nos

sinais de entrada AouB ou G, isto graças à linha de código "wait on AouB, G;" . Quando

Page 12: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

12 Alexandre Mendonça

esta variação ocorrer, o processo pode então decidir por qual vetor de sinais que carregará a

saída D: A, B ou "ZZZZ_ZZZZ" (alta impedância nas 8 linhas). A título didático, foram usadas

duas variáveis (foiA e foiB) que informam se os vetores A e B estão ou não sendo copiados

momentaneamente para a saída D. Deve-se notar a diferença nos conectivos de atribuição:

" := " e " <= ".

O exemplo 11 refaz o exemplo 10 com o uso da palavra reservada case e de uma operação de

concatenação. Nota-se que, dentro da declaração do case, existem as possibilidades de

seqüências de códigos, marcadas por cada when. O conectivo " | " significa "ou". O trecho de

código "when "01" | "00" =>" poderia ser naturalmente substituído pelo código

"when others =>", que cobre todas as outras possibilidades.

entity mux_barramento isport (A,B: in std_logic_vector (7 downto 0);

AouB: in bit; G: in bit; D: out std_logic_vector (7 downto 0));

end mux_barramento;

architecture comportamento of mux_barramento isbegin

processo1: processvariable foiA, foiB: bit;begin

wait on AouB, G;if G='1'

then if AouB='1'then D<=A;

foiA:='1';foiB:='0';

else D<=B;foiA:='0';foiB:='1';

end if;else D<="ZZZZ_ZZZZ";

foiA:='0';foiB:='0';

end if;end process;

end comportamento;

Exemplo 10. Entidade e arquitetura de uma multiplexador de barramento.

entity mux_barramento isport (A,B: in std_logic_vector (7 downto 0);

AouB: in bit; G: in bit; D: out std_logic_vector (7 downto 0));

end mux_barramento;

architecture comportamento of mux_barramento is

Page 13: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 13

beginprocesso1: processvariable concatena: bit_vector;begin

wait on AouB, G;concatena := bit_vector(G)&bit_vector(AouB);case concatena is

when "11" => D<=A;when "10" => D<=B;when "01" | "00" => D<="ZZZZ_ZZZZ";

end case;end process;

end comportamento;

Exemplo 11. Repetição do exemplo anterior com o uso do case.

O uso do wait não está limitado apenas a alterações no estado de uma variável (vide linha de

código "wait on AouB, G"). Outras formas de uso do wait estão exemplificadas abaixo.

wait on a,b; -- espera por uma alteração em a ou bwait until clk' event and clk = '1'; -- espera por borda de subida de clkwait until D>10; -- espera até que D seja maior que 10wait for 150 ns; -- espera por 150 ηswait; -- suspende indefinidamente um processo

As palavras reservadas loop e next juntas possibilitam a implementação de repetições num

código VHDL. Seja o caso do exemplo 12, onde aparecem algumas possibilidades diferentes

do uso do loop junto com outras palavras reservadas, como na repetição com o label

REPETE0 (for), REPETE1 (while) e REPETE2/REPETE3 (duplo while). A palavra reservada

exit equivale ao "break" da linguagem C.

...REPETE0: for i in 1 to 12 loop

...end loop;

...REPETE1: while (i<100) loop

...if (D(i) = '1') then next;end if;...

end loop;...

REPETE2: while i<3 loopREPETE3: while j>i loop

...end loop REPETE3;end loop REPETE2;

...

Exemplo 12. Possibilidades de uso do loop.

Page 14: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

14 Alexandre Mendonça

Repetições podem ser muito úteis para a definição do comportamento de componentes, como

no caso do exemplo 13, que ilustra códigos em VHDL para a entidade e para a arquitetura de

um registrador de deslocamento de 4 bits. Deve-se notar o uso da palavra reservada generate,

que significa "gere os sinais a partir de um processo repetitivo". No exemplo, supõe-se que já

esteja definido o componente dff, representativo de um flip-flop D com entradas d e clk e saída

q. Com uma rápida inspeção, verifica-se que a repetição simplesmente conecta a saída de um

flip-flop à entrada do outro. Para isto, foi criado um vetor auxiliar BITSHIFT de 5 posições: a

primeira é a entrada serial do registrador e as outras 4 são as saídas do registrador.

entity shiftregister4 isport (entrada_serial, clk: in bit;

saida_serial: out bit);end shiftregister4;

architecture comportamento of shiftregister4 iscomponent dff port (d, clk: in bit; q: out bit);end component;signal BITSHIFT: bit_vector (0 to 4);begin

BITSHIFT(0) <= entrada_serial;loop_shift: for i in 0 to 3 generate

U: dff port map (BITSHIFT(i), clk, BITSHIFT(i+1));end generate;saida_serial <= BITSHIFT(4);

end comportamento;

Exemplo 13. Uso do generate.

9. Funções

A linguagem VHDL prevê também o uso de funções e procedimentos, como nas linguagens C

e Pascal. As declarações de funções e procedimentos estão mostradas a seguir.

...process

function nome_da_funcao (entrada: integer) integer isvariable aux: integer;begin

aux:= entrada + 3;return(aux);

end nome_da_funcao;...

Exemplo 14. Uso de funções.

Page 15: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 15

...process

procedure nome_do_procedimento ( A: in bit_vector(1 to 8);ZF: out bit;Q: inout bit) is

variable aux: bit;begin

aux:= A(6) nand Q;Q:= aux xor A(3);ZF:= Q nor aux;

end nome_do_procedimento;...

Exemplo 15. Uso de procedimentos.

10. Comunicação entre Processos

Processos são comportamentos realizados em paralelo para uma arquitetura. Seja o exemplo

16 uma reestruturação do exemplo 10, agora implementada com mais de um processo.

entity mux_barramento isport (A,B: in std_logic_vector (7 downto 0);

AouB: in bit; G: in bit; D: out std_logic_vector (7 downto 0));

end mux_barramento;

architecture comportamento of mux_barramento isbegin

processo1: processbegin

wait on AouB, G;if (G and AouB) ='1' then D<=A;end if;

end process;processo2: processbegin

wait on AouB, G;if (G and (not (AouB))) ='1' then D<=B;end if;

end process;processo3: processbegin

wait on G;if (not(G)) then D<="ZZZZ_ZZZZ";end if;

end process;end comportamento;

Exemplo 16. Entidade e arquitetura de uma multiplexador de barramento (múltiplos processos).

Page 16: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

16 Alexandre Mendonça

Com múltiplos processos, existe o conceito de resolução. Imaginar que um processo faça

"C <= '1';" e que um outro processo em paralelo faça "C <= 'Z';". Neste caso, vale a

regra da hierarquia (vide seção 6), ou seja, o sinal C fica com o nível lógico '1'.

11. Bibliotecas

Bibliotecas facilitam o trabalho de desenvolvimento do hardware, já que oferecem entidades,

arquiteturas, componentes, constantes e outros muito comuns para qualquer tipo de projeto.

Como já foi dito na seção 3, um pacote, referenciado pela palavra reservada package, pode

ser usado para condensar um código a ser disponibilizado. Por exemplo, deseja-se criar um

pacote com as declarações Vcc, GND, retardo e clk além da função converte. O seguinte

código se encarrega disto:

package componentes issignal Vcc: bit := '1';signal GND: bit := '0';signal clk: bit := '1';constant retardo: time := 20 ns;function converte(a: real) return real is

beginreturn(a*1.32);

end converte;end componentes;

As bibliotecas padrões são WORK e STD. Para declarar uma biblioteca, usa-se a palavra

library. O código a seguir permite o uso de todas as declarações do padrão IEEE-1164.

library IEEE;use IEEE.STD_LOGIC_1164.all;

Para compilar em uma biblioteca, basta executar no prompt do sistema operacional:

nome_do_compilador -w nome_library fonte.vhd

Para usar a biblioteca alex_digital_lib:

library alex_digital_lib;

Para usar a constante retardo do pacote componentes da biblioteca alex_digital_lib:

use alex_digital_lib.componentes.retardo;

Para usar a função converte do pacote componentes da biblioteca alex_digital_lib:

Page 17: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 17

use alex_digital_lib.componentes.converte;

Para usar da biblioteca alex_digital_lib todo pacote componentes:

use alex_digital_lib.componentes.all;

Para usar toda a biblioteca alex_digital_lib:

use alex_digital_lib.all;

12. Sobrecarga

A sobrecarga é um recurso que permite a declaração de operadores, funções, etc. com o

mesmo nome. O exemplo a seguir mostra um caso para a função soma. Nesta caso, a linha

"B := soma(A);" usará a primeira declaração, pois os argumentos passado e retornado são

inteiros.

function soma (a: integer) return integer;function soma (a: real) return real;

...variable A,B : integer;B := soma(A);

13. Exemplos

Contador decrescente de 4 Bits:

library IEEE;use IEEE.std_logic_1164.all;use IEEE.std_logic_unsigned.all;

entity counter4 isport ( data_in : in std_logic_vector(3 downto 0); clk,load,down : in std_logic;

max_val : in std_logic_vector(3 downto 0); count : inout std_logic_vector(3 downto 0); zero : out std_logic);end counter4;

architecture comportamento of counter4 isbegin

Page 18: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

18 Alexandre Mendonça

process begin

wait until clk'event and clk = '1'; if (load = '1') then

count <= data_in; elsif (down = '1') then if (count="0000") then

count <= max_val; else

count <= count - "0001"; end if; else count <= count;

end if;if (count = "0000") then

zero <= '1'; else zero <= '0'; end if;end process;

end comportamento;

Exemplo 17. Contador decrescente de 4 bits.

Display de 7 segmentos:

library IEEE;use IEEE.std_logic_1164.all;use IEEE.std_logic_unsigned.all;

entity convsegs isport ( I : in std_logic_vector(3 downto 0);

segs : out std_logic_vector(6 downto 0));end convsegs;

architecture comportamento of convsegs issignal a,b,c,d,e,f,g,I0,I1,I2,I3 : std_logic;begin

segs <= a & b & c & d & e & f & g; I0 <= I(0); I1 <= I(1); I2 <= I(2);

I3 <= I(3);

a <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and not(I2) and not(I1) and I0) or (not(I3) and not(I2) and I1 and not(I0)) or (not(I3) and not(I2) and I1 and I0) or (not(I3) and I2 and not(I1) and not(I0)) or (not(I3) and I2 and I1 and I0) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and not(I1) and I0) or (I3 and not(I2) and I1 and not(I0)) or (I3 and I2 and not(I1) and I0));

Page 19: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 19

b <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and not(I2) and not(I1) and I0) or (not(I3) and not(I2) and I1 and I0) or (not(I3) and I2 and not(I1) and not(I0)) or (not(I3) and I2 and not(I1) and I0) or (not(I3) and I2 and I1 and not(I0)) or (not(I3) and I2 and I1 and I0) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and not(I1) and I0) or (I3 and not(I2) and I1 and not(I0)) or (I3 and not(I2) and I1 and I0) or (I3 and I2 and not(I1) and not(I0)));

c <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and not(I2) and I1 and not(I0)) or (not(I3) and not(I2) and I1 and I0) or (not(I3) and I2 and not(I1) and I0) or (not(I3) and I2 and I1 and not(I0)) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and not(I1) and I0) or (I3 and not(I2) and I1 and not(I0)) or (I3 and not(I2) and I1 and I0)

or (I3 and I2 and not(I1) and I0));

d <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and not(I2) and I1 and not(I0)) or (not(I3) and I2 and I1 and not(I0)) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and I1 and not(I0)) or (I3 and not(I2) and I1 and I0) or (I3 and I2 and not(I1) and not(I0)) or (I3 and I2 and not(I1) and I0) or (I3 and I2 and I1 and not(I0)));

e <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and I2 and not(I1) and not(I0)) or (not(I3) and I2 and not(I1) and I0) or (not(I3) and I2 and I1 and not(I0)) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and not(I1) and I0) or (I3 and I2 and not(I1) and I0) or (I3 and I2 and I1 and not(I0)));

f <= (( not(I3) and not(I2) and not(I1) and not(I0)) or (not(I3) and not(I2) and I1 and not(I0)) or (not(I3) and not(I2) and I1 and I0) or (not(I3) and I2 and not(I1) and I0) or (not(I3) and I2 and I1 and not(I0)) or (not(I3) and I2 and I1 and I0) or (I3 and not(I2) and not(I1) and not(I0)) or (I3 and not(I2) and not(I1) and I0) or (I3 and I2 and not(I1) and I0) or (I3 and I2 and I1 and not(I0)));

g <= (( not(I3) and not(I2) and I1 and not(I0)) or (not(I3) and not(I2) and I1 and I0) or (not(I3) and I2 and not(I1) and not(I0)) or (not(I3) and I2 and not(I1) and I0) or (not(I3) and I2 and I1 and not(I0)) or (I3 and not(I2) and not(I1) and not(I0))

Page 20: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

20 Alexandre Mendonça

or (I3 and not(I2) and not(I1) and I0) or (I3 and not(I2) and I1 and not(I0)) or (I3 and not(I2) and I1 and I0) or (I3 and I2 and not(I1) and not(I0)) or (I3 and I2 and not(I1) and I0) or (I3 and I2 and I1 and not(I0)) or (I3 and I2 and I1 and I0));

end comportamento;

Exemplo 18. Display de 7 segmentos.

Contador de 8 bits com Enable, Clear, Load e Up/Down:

library IEEE;use IEEE.STD_LOGIC_1164.all;use IEEE.STD_LOGIC_UNSIGNED.all;

entity counter isport ( CLK, NCLR, CE, NL, UP: in std_logic; D: in std_logic_vector (7 downto 0); NQ: out std_logic_vector (7 downto 0));

end counter;

architecture comportamento of counter issignal QOUT: std_logic_vector (7 downto 0);begin

process (NCLR, C, CE, NL) begin if (NCLR = '0') then

QOUT <= "00000000"; elsif (CLK'event and CLK='1') then if (NL = '0') then

QOUT <= D; elsif (CE = '1') then

if UP = '1' then QOUT <= QOUT + "00000001"; else QOUT <= QOUT - "00000001"; end if;

else QOUT <= QOUT; end if;

end if; end process;

NQ <= not(QOUT);end comportamento;

Exemplo 19. Contador de 8 bits completo.

Page 21: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 21

Uso de um Registrador de Deslocamento:

library IEEE;use IEEE.std_logic_1164.all;use IEEE.std_logic_arith.all;use IEEE.std_logic_unsigned.all;

entity inv isport ( A: in std_logic;

B: out std_logic);end inv;

architecture comportamento of inv isbegin

B <= not A;end comportamento;

entity shifter_4 isport ( CLK: in std_logic;

DIN: in std_logic;DOUT: out std_logic_vector(3 downto 0));

end shifter_4;

architecture comportamento of shifter_4 issignal REG: std_logic_vector(3 downto 0);process (CLK)begin

if CLK'event and CLK='1' then REG <= DIN & REG(3 downto 1); end if; DOUT <= REG;end process;

end comportamento;

entity uso_shifter_4 isport ( botao: in std_logic;

DOUT: out std_logic_vector(3 downto 0));end uso_shifter_4;

architecture comportamento of uso_shifter_4 issignal REG: std_logic_vector(3 downto 0);signal reg0inv: std_logic;component inv port (A: in std_logic;B: out std_logic);component shifter_4 port (

CLK: in std_logic; DIN: in std_logic; DOUT: out std_logic_vector(3 downto 0));

begin U0: inv port map (REG(0),reg0inv); U1: shifter_4 port map (botao,reg0inv,REG); DOUT <= REG;

end comportamento;

Exemplo 20. Uso de um registrador de deslocamento.

Page 22: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

22 Alexandre Mendonça

O exemplo 20 pode ser utilizado num projeto digital genérico feito a partir de esquemáticos, de

forma que o componente "uso_shifter_4" seja incorporado ao editor de esquemáticos como

uma macro, ou seja, uma caixa-preta, cujo sinal de entrada é botao e cujos sinais de saída são

DOUT[3..0]. A figura 8 ilustra o procedimento para fazer isto no Foundation. Já a figura 9

mostra como usar esta macro dentro do editor de esquemáticos.

Figura 8. Como criar uma macro no Foundation.

Page 23: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 23

Figura 9. Como usar uma macro no Foundation.

13. Biblioteca IEEE 1164

O código a seguir representa a biblioteca IEEE 1164, de domínio público.

-- Title : std_logic_1164 multi-value logic system-- Library : This package shall be compiled into a library-- : symbolically named IEEE.-- Developers: IEEE model standards group (par 1164)-- Purpose : This packages defines a standard for designers-- : to use in describing the interconnection data types-- : used in vhdl modeling.-- Limitation: The logic system defined in this package may-- : be insufficient for modeling switched transistors,-- : since such a requirement is out of the scope of this-- : effort. Furthermore, mathematics, primitives,-- : timing standards, etc. are considered orthogonal-- : issues as it relates to this package and are therefore-- : beyond the scope of this effort.-- :-- Note : No declarations or definitions shall be included in,-- : or excluded from this package. The "package declaration"

Page 24: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

24 Alexandre Mendonça

-- : defines the types, subtypes and declarations of-- : std_logic_1164. The std_logic_1164 package body shall-- : be considered the formal definition of the semantics of-- : this package. Tool developers may choose to implement-- : the package body in the most efficient manner available-- : to them.-- ---------------------------------------------------------------------- modification history :-- ---------------------------------------------------------------------- version | mod. date:|-- v4.200 | 01/02/92 |-- v4.200 | 02/26/92 | Added Synopsys Synthesis Comments-- v4.200 | 06/01/92 | Modified the "xnor"s to be xnor functions.-- | | (see Note bellow)-- v5.000 | 05/15/98 | Modifications to make-- VHDL93 related changes-- ---------------------------------------------------------------------- Note: Before the VHDL'92 language being officially adopted as-- containing the "xnor" functions, Synopsys will support-- the xnor functions (non-overloaded).---- GongWen Huang Synopsys, Inc.

library SYNOPSYS;use SYNOPSYS.ATTRIBUTES.ALL;

package std_logic_1164 is

------------------------------------------------------------------- -- logic state system (unresolved) ------------------------------------------------------------------- type std_ulogic is ( 'U', -- Uninitialized 'X', -- Forcing Unknown '0', -- Forcing 0 '1', -- Forcing 1 'Z', -- High Impedance 'W', -- Weak Unknown 'L', -- Weak 0 'H', -- Weak 1 '-' -- Don't care );

attribute ENUM_ENCODING of std_ulogic: type is "U D 0 1 Z D 0 1 D";

--------------------------------------------------------------------- unconstrained array of std_ulogic for use with the resolutionfunction------------------------------------------------------------------- type std_ulogic_vector is array ( natural range <> ) of std_ulogic;

------------------------------------------------------------------- -- resolution function ------------------------------------------------------------------- function resolved ( s : std_ulogic_vector ) return std_ulogic; --synopsys translate_off attribute REFLEXIVE of resolved: function is TRUE; attribute RESULT_INITIAL_VALUE of resolved: function is std_ulogic'POS('Z');

--synopsys translate_on

-------------------------------------------------------------------

Page 25: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 25

-- *** industry standard logic type*** ------------------------------------------------------------------- subtype std_logic is resolved std_ulogic;

------------------------------------------------------------------- -- unconstrained array of std_logic for use in declaring signal arrays ------------------------------------------------------------------- type std_logic_vector is array (natural range <>) of std_logic;

------------------------------------------------------------------- -- common subtypes -------------------------------------------------------------------subtype X01 is resolved std_ulogic range 'X' to '1'; -- ('X','0','1')subtype X01Z is resolved std_ulogic range 'X' to 'Z'; -- ('X','0','1','Z')subtype UX01 is resolved std_ulogic range 'U' to '1'; -- ('U','X','0','1')subtype UX01Z is resolved std_ulogic range 'U' to 'Z';

-- ('U','X','0','1','Z')

------------------------------------------------------------------- -- overloaded logical operators -------------------------------------------------------------------

function "and" ( l : std_ulogic; r : std_ulogic ) return UX01; function "nand" ( l : std_ulogic; r : std_ulogic ) return UX01; function "or" ( l : std_ulogic; r : std_ulogic ) return UX01; function "nor" ( l : std_ulogic; r : std_ulogic ) return UX01; function "xor" ( l : std_ulogic; r : std_ulogic ) return UX01; function "xnor" ( l : std_ulogic; r : std_ulogic ) return ux01; function "not" ( l : std_ulogic ) return UX01;

------------------------------------------------------------------- -- vectorized overloaded logical operators -------------------------------------------------------------------function "and" ( l, r : std_logic_vector ) return std_logic_vector;function "and" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "nand" ( l, r : std_logic_vector ) return std_logic_vector;function "nand" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "or" ( l, r : std_logic_vector ) return std_logic_vector;function "or" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "nor" ( l, r : std_logic_vector ) return std_logic_vector;function "nor" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "xor" ( l, r : std_logic_vector ) return std_logic_vector;function "xor" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "xnor" ( l, r : std_logic_vector ) return std_logic_vector;function "xnor" ( l, r : std_ulogic_vector ) return std_ulogic_vector;

function "not" ( l : std_logic_vector ) return std_logic_vector;function "not" ( l : std_ulogic_vector ) return std_ulogic_vector;

------------------------------------------------------------------- -- conversion functions -------------------------------------------------------------------function To_bit ( s : std_ulogic; --synopsys synthesis_off

xmap : bit := '0'; --synopsys synthesis_on ) return bit;

Page 26: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

26 Alexandre Mendonça

function To_bitvector (s : std_logic_vector; --synopsys synthesis_offxmap : bit := '0'; --synopsys synthesis_on

) return bit_vector;

function To_bitvector ( s : std_ulogic_vector; --synopsys synthesis_off

xmap : bit := '0'; --synopsys synthesis_on ) return bit_vector;

function To_StdULogic ( b : bit) return std_ulogic;function To_StdLogicVector ( b : bit_vector) return std_logic_vector;function To_StdLogicVector (s : std_ulogic_vector) return std_logic_vector;function To_StdULogicVector ( b : bit_vector) return std_ulogic_vector;function To_StdULogicVector (s:std_logic_vector) return std_ulogic_vector;

------------------------------------------------------------------- -- strength strippers and type convertors -------------------------------------------------------------------

function To_X01 ( s : std_logic_vector ) return std_logic_vector;function To_X01 ( s : std_ulogic_vector ) return std_ulogic_vector;function To_X01 ( s : std_ulogic) return X01;function To_X01 ( b : bit_vector) return std_logic_vector;function To_X01 ( b : bit_vector) return std_ulogic_vector;function To_X01 ( b : bit) return X01;

function To_X01Z ( s : std_logic_vector ) return std_logic_vector;function To_X01Z ( s : std_ulogic_vector ) return std_ulogic_vector;function To_X01Z ( s : std_ulogic ) return X01Z;function To_X01Z ( b : bit_vector) return std_logic_vector;function To_X01Z ( b : bit_vector) return std_ulogic_vector;function To_X01Z ( b : bit) return X01Z;

function To_UX01 ( s : std_logic_vector) return std_logic_vector;function To_UX01 ( s : std_ulogic_vector ) return std_ulogic_vector;function To_UX01 ( s : std_ulogic) return UX01;function To_UX01 ( b : bit_vector) return std_logic_vector;function To_UX01 ( b : bit_vector) return std_ulogic_vector;function To_UX01 ( b : bit) return UX01;

------------------------------------------------------------------- -- edge detection ------------------------------------------------------------------- function rising_edge (signal s : std_ulogic) return boolean; function falling_edge (signal s : std_ulogic) return boolean;

------------------------------------------------------------------- -- object contains an unknown ------------------------------------------------------------------- --synopsys synthesis_off function is_X ( s : std_ulogic_vector ) return boolean; function is_X ( s : std_logic_vector ) return boolean; function is_X ( s : std_ulogic ) return boolean; --synopsys synthesis_on

end std_logic_1164;

package body std_logic_1164 is -------------------------------------------------------------------

Page 27: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 27

-- local types ------------------------------------------------------------------- --synopsys synthesis_off type stdlogic_1d is array (std_ulogic) of std_ulogic; type stdlogic_table is array(std_ulogic, std_ulogic) of std_ulogic;

------------------------------------------------------------------- -- resolution function ------------------------------------------------------------------- constant resolution_table : stdlogic_table := ( -- --------------------------------------------------------- -- | U X 0 1 Z W L H - | | -- --------------------------------------------------------- ( 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U' ), -- | U | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ), -- | X | ( 'U', 'X', '0', 'X', '0', '0', '0', '0', 'X' ), -- | 0 | ( 'U', 'X', 'X', '1', '1', '1', '1', '1', 'X' ), -- | 1 | ( 'U', 'X', '0', '1', 'Z', 'W', 'L', 'H', 'X' ), -- | Z | ( 'U', 'X', '0', '1', 'W', 'W', 'W', 'W', 'X' ), -- | W | ( 'U', 'X', '0', '1', 'L', 'W', 'L', 'W', 'X' ), -- | L | ( 'U', 'X', '0', '1', 'H', 'W', 'W', 'H', 'X' ), -- | H | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ) -- | - | ); --synopsys synthesis_on

function resolved ( s : std_ulogic_vector ) return std_ulogic is -- pragma resolution_method three_state -- pragma subpgm_id 183 --synopsys synthesis_off variable result : std_ulogic := 'Z'; -- weakest state default --synopsys synthesis_on begin -- the test for a single driver is essential otherwise the -- loop would return 'X' for a single driver of '-' and that -- would conflict with the value of a single driver unresolved -- signal. --synopsys synthesis_off if (s'length = 1) then return s(s'LOW); else for i in s'range loop result := resolution_table(result, s(i)); end loop; end if; return result; --synopsys synthesis_on end resolved;

------------------------------------------------------------------- -- tables for logical operations -------------------------------------------------------------------

--synopsys synthesis_off -- truth table for "and" function constant and_table : stdlogic_table := ( -- ---------------------------------------------------- -- | U X 0 1 Z W L H - | | -- ---------------------------------------------------- ( 'U', 'U', '0', 'U', 'U', 'U', '0', 'U', 'U' ), -- | U | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | X | ( '0', '0', '0', '0', '0', '0', '0', '0', '0' ), -- | 0 |

Page 28: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

28 Alexandre Mendonça

( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | 1 | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | Z | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | W | ( '0', '0', '0', '0', '0', '0', '0', '0', '0' ), -- | L | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | H | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ) -- | - | );

-- truth table for "or" function constant or_table : stdlogic_table := ( -- ---------------------------------------------------- -- | U X 0 1 Z W L H - | | -- ---------------------------------------------------- ( 'U', 'U', 'U', '1', 'U', 'U', 'U', '1', 'U' ), -- | U | ( 'U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X' ), -- | X | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | 0 | ( '1', '1', '1', '1', '1', '1', '1', '1', '1' ), -- | 1 | ( 'U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X' ), -- | Z | ( 'U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X' ), -- | W | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | L | ( '1', '1', '1', '1', '1', '1', '1', '1', '1' ), -- | H | ( 'U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X' ) -- | - | );

-- truth table for "xor" function constant xor_table : stdlogic_table := ( -- ---------------------------------------------------- -- | U X 0 1 Z W L H - | | -- ---------------------------------------------------- ( 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U' ), -- | U | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ), -- | X | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | 0 | ( 'U', 'X', '1', '0', 'X', 'X', '1', '0', 'X' ), -- | 1 | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ), -- | Z | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ), -- | W | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | L | ( 'U', 'X', '1', '0', 'X', 'X', '1', '0', 'X' ), -- | H | ( 'U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ) -- | - | );

-- truth table for "not" function constant not_table: stdlogic_1d := -- ------------------------------------------------- -- | U X 0 1 Z W L H - | -- ------------------------------------------------- ( 'U', 'X', '1', '0', 'X', 'X', '1', '0', 'X' ); --synopsys synthesis_on

------------------------------------------------------------------- -- overloaded logical operators ( with optimizing hints ) -------------------------------------------------------------------

function "and" ( l : std_ulogic; r : std_ulogic ) return UX01 is -- pragma built_in SYN_AND -- pragma subpgm_id 184 begin --synopsys synthesis_off return (and_table(l, r)); --synopsys synthesis_on end "and";

Page 29: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 29

function "nand" ( l : std_ulogic; r : std_ulogic ) return UX01 is -- pragma built_in SYN_NAND -- pragma subpgm_id 185 begin --synopsys synthesis_off return (not_table ( and_table(l, r))); --synopsys synthesis_on end "nand";

function "or" ( l : std_ulogic; r : std_ulogic ) return UX01 is -- pragma built_in SYN_OR -- pragma subpgm_id 186 begin --synopsys synthesis_off return (or_table(l, r)); --synopsys synthesis_on end "or";

function "nor" ( l : std_ulogic; r : std_ulogic ) return UX01 is -- pragma built_in SYN_NOR -- pragma subpgm_id 187 begin --synopsys synthesis_off return (not_table ( or_table( l, r ))); --synopsys synthesis_on end "nor";

function "xor" ( l : std_ulogic; r : std_ulogic ) return UX01 is -- pragma built_in SYN_XOR -- pragma subpgm_id 188 begin --synopsys synthesis_off return (xor_table(l, r)); --synopsys synthesis_on end "xor";

function "xnor" ( l : std_ulogic; r : std_ulogic ) return ux01 is -- pragma built_in SYN_XNOR -- pragma subpgm_id 189 begin --synopsys synthesis_off return not_table(xor_table(l, r)); --synopsys synthesis_on end "xnor";

function "not" ( l : std_ulogic ) return UX01 is -- pragma built_in SYN_NOT -- pragma subpgm_id 190 begin --synopsys synthesis_off return (not_table(l)); --synopsys synthesis_on end "not";

------------------------------------------------------------------- -- and ------------------------------------------------------------------- function "and" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_AND

Page 30: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

30 Alexandre Mendonça

-- pragma subpgm_id 198 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if ( l'length /= r'length ) then assert false report "arguments of overloaded 'and' operator are not of the same length" severity failure; else for i in result'range loop result(i) := and_table (lv(i), rv(i)); end loop; end if; return result; --synopsys synthesis_on end "and"; --------------------------------------------------------------------- function "and" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_AND

-- pragma subpgm_id 191 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'and' operator are not of the same length" severity failure; else for i in result'range loop result(i) := and_table (lv(i), rv(i)); end loop; end if; return result; --synopsys synthesis_on end "and"; ------------------------------------------------------------------- -- nand ------------------------------------------------------------------- function "nand" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_NAND

-- pragma subpgm_id 199 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false

Page 31: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 31

report "arguments of overloaded 'nand' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(and_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "nand"; --------------------------------------------------------------------- function "nand" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_NAND

-- pragma subpgm_id 192 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'nand' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(and_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "nand"; ------------------------------------------------------------------- -- or ------------------------------------------------------------------- function "or" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_OR

-- pragma subpgm_id 200 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'or' operator are not of the same length" severity failure; else for i in result'range loop result(i) := or_table (lv(i), rv(i)); end loop; end if; return result; --synopsys synthesis_on

Page 32: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

32 Alexandre Mendonça

end "or"; --------------------------------------------------------------------- function "or" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_OR

-- pragma subpgm_id 193 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'or' operator are not of the same length" severity failure; else for i in result'range loop result(i) := or_table (lv(i), rv(i)); end loop; end if; return result; --synopsys synthesis_on end "or"; ------------------------------------------------------------------- -- nor ------------------------------------------------------------------- function "nor" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_NOR

-- pragma subpgm_id 201 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'nor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(or_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "nor"; --------------------------------------------------------------------- function "nor" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_NOR

-- pragma subpgm_id 194 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on

Page 33: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 33

begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'nor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(or_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "nor"; --------------------------------------------------------------------- -- xor ------------------------------------------------------------------- function "xor" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_XOR

-- pragma subpgm_id 202 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'xor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := xor_table (lv(i), rv(i)); end loop; end if; return result; --synopsys synthesis_on end "xor"; --------------------------------------------------------------------- function "xor" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_XOR

-- pragma subpgm_id 195 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'xor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := xor_table (lv(i), rv(i));

Page 34: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

34 Alexandre Mendonça

end loop; end if; return result; --synopsys synthesis_on end "xor"; ------------------------------------------------------------------- -- xnor ------------------------------------------------------------------- function "xnor" ( l,r : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_XNOR -- pragma subpgm_id 203 --synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; alias rv : std_logic_vector ( 1 to r'length ) is r; variable result : std_logic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'xnor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(xor_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "xnor"; --------------------------------------------------------------------- function "xnor" ( l,r : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_XNOR -- pragma subpgm_id 196 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; alias rv : std_ulogic_vector ( 1 to r'length ) is r; variable result : std_ulogic_vector ( 1 to l'length ); --synopsys synthesis_on begin --synopsys synthesis_off if( l'length /= r'length ) then assert false report "arguments of overloaded 'xnor' operator are not of the same length" severity failure; else for i in result'range loop result(i) := not_table(xor_table (lv(i), rv(i))); end loop; end if; return result; --synopsys synthesis_on end "xnor";

------------------------------------------------------------------- -- not ------------------------------------------------------------------- function "not" ( l : std_logic_vector ) return std_logic_vector is

Page 35: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 35

-- pragma built_in SYN_NOT -- pragma subpgm_id 204

--synopsys synthesis_off alias lv : std_logic_vector ( 1 to l'length ) is l; variable result: std_logic_vector ( 1 to l'length ) := (others => 'X'); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := not_table( lv(i) ); end loop; return result; --synopsys synthesis_on end; --------------------------------------------------------------------- function "not" ( l : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_NOT

-- pragma subpgm_id 197 --synopsys synthesis_off alias lv : std_ulogic_vector ( 1 to l'length ) is l; variable result : std_ulogic_vector ( 1 to l'length ) := (others => 'X'); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := not_table( lv(i) ); end loop; return result; --synopsys synthesis_on end; ------------------------------------------------------------------- -- conversion tables ------------------------------------------------------------------- --synopsys synthesis_off

type logic_x01_table is array (std_ulogic'LOW to std_ulogic'HIGH) of X01; type logic_x01z_table is array (std_ulogic'LOW to std_ulogic'HIGH) of X01Z; type logic_ux01_table is array (std_ulogic'LOW to std_ulogic'HIGH) of UX01; ---------------------------------------------------------- -- table name : cvt_to_x01 -- -- parameters : -- in : std_ulogic -- some logic value -- returns : x01 -- state value of logic value -- purpose : to convert state-strength to state only -- -- example : if(cvt_to_x01 (input_signal) = '1' ) then ... -- ---------------------------------------------------------- constant cvt_to_x01 : logic_x01_table := ( 'X', -- 'U' 'X', -- 'X' '0', -- '0' '1', -- '1' 'X', -- 'Z' 'X', -- 'W' '0', -- 'L' '1', -- 'H' 'X' -- '-' );

Page 36: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

36 Alexandre Mendonça

---------------------------------------------------------- -- table name : cvt_to_x01z -- -- parameters : -- in : std_ulogic -- some logic value -- returns : x01z -- state value of logic value -- purpose : to convert state-strength to state only -- -- example : if(cvt_to_x01z (input_signal) = '1' ) then ... -- ---------------------------------------------------------- constant cvt_to_x01z : logic_x01z_table := ( 'X', -- 'U' 'X', -- 'X' '0', -- '0' '1', -- '1' 'Z', -- 'Z' 'X', -- 'W' '0', -- 'L' '1', -- 'H' 'X' -- '-' );

---------------------------------------------------------- -- table name : cvt_to_ux01 -- -- parameters : -- in : std_ulogic -- some logic value -- returns : ux01 -- state value of logic value -- purpose : to convert state-strength to state only -- -- example : if(cvt_to_ux01 (input_signal) = '1' ) then ... -- ---------------------------------------------------------- constant cvt_to_ux01 : logic_ux01_table := ( 'U', -- 'U' 'X', -- 'X' '0', -- '0' '1', -- '1' 'X', -- 'Z' 'X', -- 'W' '0', -- 'L' '1', -- 'H' 'X' -- '-' ); --synopsys synthesis_on

------------------------------------------------------------------- -- conversion functions ------------------------------------------------------------------- function To_bit ( s : std_ulogic; xmap : bit := '0') return bit is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 205 begin --synopsys synthesis_off case s is when '0' | 'L' => return ('0'); when '1' | 'H' => return ('1'); when others => return xmap; end case;

Page 37: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 37

--synopsys synthesis_on end; -------------------------------------------------------------------- function To_bitvector ( s : std_logic_vector; xmap : bit := '0') return bit_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 206 --synopsys synthesis_off alias sv : std_logic_vector ( s'length-1 downto 0 ) is s; variable result : bit_vector ( s'length-1 downto 0 ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case sv(i) is when '0' | 'L' => result(i) := '0'; when '1' | 'H' => result(i) := '1'; when others => result(i) := xmap; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_bitvector ( s : std_ulogic_vector; xmap : bit := '0') return bit_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 207 --synopsys synthesis_off alias sv : std_ulogic_vector ( s'length-1 downto 0 ) is s; variable result : bit_vector ( s'length-1 downto 0 ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case sv(i) is when '0' | 'L' => result(i) := '0'; when '1' | 'H' => result(i) := '1'; when others => result(i) := xmap; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_StdULogic ( b : bit ) return std_ulogic is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 208 begin --synopsys synthesis_off case b is when '0' => return '0'; when '1' => return '1'; end case; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_StdLogicVector ( b : bit_vector) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 209

Page 38: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

38 Alexandre Mendonça

--synopsys synthesis_off alias bv : bit_vector ( b'length-1 downto 0 ) is b; variable result : std_logic_vector ( b'length-1 downto 0 ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_StdLogicVector ( s : std_ulogic_vector )

return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 210 --synopsys synthesis_off alias sv : std_ulogic_vector ( s'length-1 downto 0 ) is s; variable result : std_logic_vector ( s'length-1 downto 0 ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := sv(i); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_StdULogicVector ( b : bit_vector) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 211 --synopsys synthesis_off alias bv : bit_vector ( b'length-1 downto 0 ) is b; variable result : std_ulogic_vector ( b'length-1 downto 0 ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_StdULogicVector ( s : std_logic_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 212 --synopsys synthesis_off alias sv : std_logic_vector ( s'length-1 downto 0 ) is s; variable result : std_ulogic_vector ( s'length-1 downto 0 );

Page 39: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 39

--synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := sv(i); end loop; return result; --synopsys synthesis_on end;

------------------------------------------------------------------- -- strength strippers and type convertors ------------------------------------------------------------------- -- to_x01 ------------------------------------------------------------------- function To_X01 ( s : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 213 --synopsys synthesis_off alias sv : std_logic_vector ( 1 to s'length ) is s; variable result : std_logic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_x01 (sv(i)); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01 ( s : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 214 --synopsys synthesis_off alias sv : std_ulogic_vector ( 1 to s'length ) is s; variable result : std_ulogic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_x01 (sv(i)); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01 ( s : std_ulogic ) return X01 is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 215 begin --synopsys synthesis_off return (cvt_to_x01(s)); --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01 ( b : bit_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 216

Page 40: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

40 Alexandre Mendonça

--synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_logic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01 ( b : bit_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 217 --synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_ulogic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01 ( b : bit ) return X01 is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 218 begin --synopsys synthesis_off case b is when '0' => return('0'); when '1' => return('1'); end case; --synopsys synthesis_on end; -------------------------------------------------------------------- -- to_x01z ------------------------------------------------------------------- function To_X01Z ( s : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 219 --synopsys synthesis_off alias sv : std_logic_vector ( 1 to s'length ) is s; variable result : std_logic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_x01z (sv(i));

Page 41: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 41

end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01Z ( s : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 220 --synopsys synthesis_off alias sv : std_ulogic_vector ( 1 to s'length ) is s; variable result : std_ulogic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_x01z (sv(i)); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01Z ( s : std_ulogic ) return X01Z is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 221 begin --synopsys synthesis_off return (cvt_to_x01z(s)); --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01Z ( b : bit_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 222 --synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_logic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01Z ( b : bit_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 223 --synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_ulogic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop

Page 42: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

42 Alexandre Mendonça

case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_X01Z ( b : bit ) return X01Z is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 224 begin --synopsys synthesis_off case b is when '0' => return('0'); when '1' => return('1'); end case; --synopsys synthesis_on end; -------------------------------------------------------------------- -- to_ux01 ------------------------------------------------------------------- function To_UX01 ( s : std_logic_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 225 --synopsys synthesis_off alias sv : std_logic_vector ( 1 to s'length ) is s; variable result : std_logic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_ux01 (sv(i)); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_UX01 ( s : std_ulogic_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 226 --synopsys synthesis_off alias sv : std_ulogic_vector ( 1 to s'length ) is s; variable result : std_ulogic_vector ( 1 to s'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop result(i) := cvt_to_ux01 (sv(i)); end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_UX01 ( s : std_ulogic ) return UX01 is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 227 begin

Page 43: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

Tutorial sobre VHDL 43

--synopsys synthesis_off return (cvt_to_ux01(s)); --synopsys synthesis_on end; -------------------------------------------------------------------- function To_UX01 ( b : bit_vector ) return std_logic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 228 --synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_logic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_UX01 ( b : bit_vector ) return std_ulogic_vector is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 229 --synopsys synthesis_off alias bv : bit_vector ( 1 to b'length ) is b; variable result : std_ulogic_vector ( 1 to b'length ); --synopsys synthesis_on begin --synopsys synthesis_off for i in result'range loop case bv(i) is when '0' => result(i) := '0'; when '1' => result(i) := '1'; end case; end loop; return result; --synopsys synthesis_on end; -------------------------------------------------------------------- function To_UX01 ( b : bit ) return UX01 is -- pragma built_in SYN_FEED_THRU -- pragma subpgm_id 230 begin --synopsys synthesis_off case b is when '0' => return('0'); when '1' => return('1'); end case; --synopsys synthesis_on end;

------------------------------------------------------------------- -- edge detection ------------------------------------------------------------------- function rising_edge (signal s : std_ulogic) return boolean is -- pragma subpgm_id 231

Page 44: Tutorial sobre VHDL - dsif.fee.unicamp.brjuvenilj/apostilas_vhdl/vhdl_alexmend.pdf · Introdução A sigla HDL vem do inglês "Hardware Description Language", ou seja, designa uma

44 Alexandre Mendonça

begin --synopsys synthesis_off return (s'event and (To_X01(s) = '1') and (To_X01(s'LAST_VALUE) = '0')); --synopsys synthesis_on end;

function falling_edge (signal s : std_ulogic) return boolean is -- pragma subpgm_id 232 begin --synopsys synthesis_off return (s'event and (To_X01(s) = '0') and (To_X01(s'LAST_VALUE) = '1')); --synopsys synthesis_on end;

------------------------------------------------------------------- -- object contains an unknown ------------------------------------------------------------------- --synopsys synthesis_off function Is_X ( s : std_ulogic_vector ) return boolean is -- pragma subpgm_id 233 begin for i in s'range loop case s(i) is when 'U' | 'X' | 'Z' | 'W' | '-' => return TRUE; when others => NULL; end case; end loop; return FALSE; end; -------------------------------------------------------------------- function Is_X ( s : std_logic_vector ) return boolean is -- pragma subpgm_id 234 begin for i in s'range loop case s(i) is when 'U' | 'X' | 'Z' | 'W' | '-' => return TRUE; when others => NULL; end case; end loop; return FALSE; end; -------------------------------------------------------------------- function Is_X ( s : std_ulogic ) return boolean is -- pragma subpgm_id 235 begin case s is when 'U' | 'X' | 'Z' | 'W' | '-' => return TRUE; when others => NULL; end case; return FALSE; end; --synopsys synthesis_on

end std_logic_1164;