fdvmDDe (1158418)

Файл №1158418 fdvmDDe (Раздаточные материалы)fdvmDDe (1158418)2019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла

34


Keldysh Institute of Applied Mathematics

Russian Academy of Sciences

Fortran DVM compiler

Detailed design

Mart 2000

Contents

1 Compiler role 3

2 Command line format 3

3 The general scheme of compiler 5

3.1 Parsing 5

3.2 Transforming parse tree 5

3.3 Generating code in Fortran 77 5

3.4 Generating code in HPF 5

4 Basic data structures 5

4.1 Parse tree 6

4.2 Symbol and Type table 6

5 Detailed description of compiler modules 8

5.1 Translating Fortran DVM constructs (module dvm.cpp) 8

5.1.1 Distributed array creation and remapping 13

5.1.2 Distributed array referencing 17

5.1.3 Parallel loop 19

5.2 Translating input/output statements (module io.cpp) 22

5.3 Restructuring parse tree (module stmt.cpp) 25

5.4 Translating HPF-DVM constructs (module hpf.cpp) 29

5.4.1 Processing distributed array references in HPF-DVM 29

5.4.2 INDEPENDENT loop 30

This report presents the detailed description of the Fortran-DVM (FDVM) compiler implementation. The basic data structures, the control scheme, and the functions of compiler modules are considered.

1Compiler role

Fortran DVM (FDVM) language is an extension of the Fortran 77 language for parallel programming. The extension is implemented as special comments (directives) that annotate sequential program in Fortran 77.

The input to the compiler is source code in Fortran DVM or HPF-DVM language. The compiler produces the following output programs.

  • Parallel program in Fortran 77 language including runtime system function calls (Lib-DVM) for parallel execution.

  • Sequential program in Fortran 77 language which includes calls of functions accumulating information for debugging and performance analyzing.

  • HPF program.

2Command line format

The format of the FDVM compiler command line is illustrated below:

dvm fdv [ <options> ] <file-name>

Source program is placed in input file <file-name>.fdv or <file-name>.hpf.

On the command-line <options> are the compiler options:

-o file

Place output in the file file.

-s

Produce sequential program;

-p

Produce parallel program;

-hpf1

Produce HPF1 program;

-hpf2

Produce HPF2 program;

-v

Display the invocations of compiler phases and version number;

-w

Display all the warning messages;

-Idir

Add directory dir to the list of directories searched for include files;

-bindk

Specifies the compatibility of data types between Fortan and C,

k is an integer pointing to compatibility table number;

-dleveld[:fr-list]

Produce additional code for the program debugging,

leveld specifies debug level, fr-list is fragment number list;

-elevele[:fr-list]

Produce additional code for program performance analyzing,

levele specifies level of performance debug.

3The general scheme of compiler

Sage ++ system is used as a tool for designing FDVM compiler.

Sage++ is an object oriented toolkit for building program transformation systems for Fortran 77, Fortran 90, C and C++ languages. It is designed as an open C++ class library that provides the user with a set of parsers, a structured parse tree, a symbol and type table. The heart of the system is a set of functions that allow to restructure the parse tree and a mechanism (called unparsing) for generating new source code from the restructured internal form.

The FDVM compiler consists of four components:

  • Parsing

  • Transforming parse tree

  • Generating code in Fortran 77

  • Generating code in HPF

3.1Parsing

The Fortran parser of Sage++ which is based on the GNU Bison version of YACC is extended to add language extensions (DVM directives) to Fortran system. It consists of the following modules:

ftn.gram

- grammar rules for Fortran

fdvm.gram

- grammar rules for Fortran DVM

lexfdvm.c

- lexical analyzer

tag

- variant tag list

tokens

- lexeme list

gram1.tab.c

- parser generated by Bison

cftn.c

- main routine (calls parser, opens and closes the files that are

needed)

init.c

- initialization routines

stat.c

- routines for creating internal form of statements (bif node of

parse tree)

errors.c

- printing error messages

sym.c

-Symbol table routines

types.c

- routines to handle the variable declarations

lists.c

- routines to build the lists

misc.c

- miscellaneous help routines

hash.c

- hash table routines

The parser reads the source, checks the concrete syntax, constructs a parse tree, and writes its internal representation in a .dep file.

3.2Transforming parse tree

Second phase of compiling involves analyzing and restructuring internal representation of FDVM program. A DVM directive is substituted for a sequence of Lib‑DVM function calls. Afterwards new source code is generated from restructured internal form.

Back-end of the compiler is written in C++ language using Sage++ class library.

The Sage++ library is organized as a class hierarchy that provides access to the parse tree, symbol table and type table for each file in an application project. There are five basic families of classes in the library: Project and Files, Statements, Expressions, Symbols, and Types.

Project and Files correspond to source files. Statements correspond to the basic source statements in Fortran 77 and DVM directives. Expressions are contained within statements. Symbols are the basic user defined identifiers. Types are associated with each identifier and expression.

The file libSage++.h contains all the class definitions.

Seven modules compound the translator:

dvm.cpp

- analyzing and translating FDVM constucts

funcall.cpp

- generating LibDVM library calls

stmt.cpp

- restucturing parse tree

io.cpp

- translating I/O statements

debug.cpp

- support of debugging mode

help.cpp

- miscellaneous help routines

hpf.cpp

- translating HPF-DVM constucts

3.3Generating code in Fortran 77

Generating new source code from the restructured internal form is implemented by the File class member function (unparse( )) of Sage++ class library.

3.4Generating code in HPF

When the source FDVM program is converted in HPF program the following routines and tables are used for unparsing:

unparse_hpf.c

- routines for generation HPF code

low_hpf.c

- low-level routines for unparsing

unparse.hpf

- table driving the generation of HPF2 code

unparse1.hpf

- table driving the generation of HPF1 code

4Basic data structures

The definitions of data structures of internal representation are contained in the files:

  • bif.h (parse tree node for statement)

  • ll.h (parse tree node for expression)

  • symb.h (Symbol and Type Table elements)

4.1Parse tree

The structures of parse tree nodes for a statement and an expression are given in Fig. 4.1 and Fig.4.2 accordingly. The Fig. 4.4 illustrates the fragment of parse tree.

4.2Symbol and Type table

The Fig.4.3 presents the Symbol and Type Table entries.

variant tag

identification tag

index

global line number

local line number

declaration specifier

pointer to the label

pointer to the next statement node

pointer to the source filename

pointer to the control parent node

property list

list of nodes(list of procedures)

pointer to the comment

symbol table entry

L-value expr tree

R-value expr tree

spare expr tree

do-label (used by do)

null

null

null

null

Fig. 4.1. Parse tree node representing a statement (bif node).

variant tag

identification tag

pointer to the next node (by allocation order)

pointer to the Type table element

constant value

pointer to the Symbol table element

L-value expr tree

R-value expr tree

Fig. 4.2. Parse tree node representing an expression (low level node).

variant tag

variant tag

identification tag

identification tag

length

identifier

spare field

Hash table entry

spare field

special list

use-definition chain

special list

base type entry(for array)

special list

ranges(for array)

next Symbol table entry

Type table entry

scope

use-definition chain

attributes (mask)

do-variable flag

parser used

pointer to value ( for constants)

Fig.4.3. Type and Symbol table entries

special fields

Parse Tree

Характеристики

Тип файла документ

Документы такого типа открываются такими программами, как Microsoft Office Word на компьютерах Windows, Apple Pages на компьютерах Mac, Open Office - бесплатная альтернатива на различных платформах, в том числе Linux. Наиболее простым и современным решением будут Google документы, так как открываются онлайн без скачивания прямо в браузере на любой платформе. Существуют российские качественные аналоги, например от Яндекса.

Будьте внимательны на мобильных устройствах, так как там используются упрощённый функционал даже в официальном приложении от Microsoft, поэтому для просмотра скачивайте PDF-версию. А если нужно редактировать файл, то используйте оригинальный файл.

Файлы такого типа обычно разбиты на страницы, а текст может быть форматированным (жирный, курсив, выбор шрифта, таблицы и т.п.), а также в него можно добавлять изображения. Формат идеально подходит для рефератов, докладов и РПЗ курсовых проектов, которые необходимо распечатать. Кстати перед печатью также сохраняйте файл в PDF, так как принтер может начудить со шрифтами.

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7026
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее