Introducing Modula-3modula3.org/threads/1/threads1.pdf · tion handling, concurrency,...

12

Transcript of Introducing Modula-3modula3.org/threads/1/threads1.pdf · tion handling, concurrency,...

Introducing Modula-3

Threads

We are pleased to bring you the first issue of

Threads, a newsletter for the Modula-3 com-munity. By publishing this newsletter we hopeto establish a forum of discussion and infor-mation sharing about Modula-3 and what vari-ous organizations – industrial or academic –are doing with Modula-3. We tried to makethe articles accessible to both currently activeand potential Modula-3 users. We hope toinvite those who now use other programminglanguages give Modula-3 a try, too.

We welcome your ideas and contribution inshaping the future of Threads. We imaginethat Threads will change with your input overthe next few issues. Please drop us a note [email protected]!

What is Modula-3?

Modula-3 is a simple and modular program-ming language, providing facilities for excep-tion handling, concurrency, object-orientedprogramming, automatic garbage collection,and systems programming without involvingthe complexities forced by other languages ofits class. Modula-3 is both a practical imple-mentation language for large software projectsand an excellent teaching language.

An implementation of Modula-3 is availablefree of charge from Digital Systems ResearchCenter. For more information visit the Mod-ula-3 home page:

http://www.research.digital.-com/SRC/modula-3/html/home.html

thread

s

Feature ArticleImplementing Juno-2: The User Interfaceby Allan Heydon............................................2

How Modula-3 got its spots?Initialization of Object Typesby Greg Nelson .............................................5

Modula-3 in IndustryPhoton: An Environment for Building Distributed Applicationsby Lauren Schmitt.........................................6

Modula-3 in AcademiaUniversity of Klagenfurt, Austriaby Laszlo Boeszoermenyi ...............................7

Advanced Research TopicsThe Whole Program Optimizerby Amer Diwan..............................................8

U N OJ 2

Editors:

Farshad Nayeri, GTE Laboratories

Geoff Wyant, Sun Microsystems Laboratories

Lauren Schmitt, Critical Mass, Inc.

fall 1995 – threads 2

Feature ArticleImplementing Juno-2: The User Interface

Allan Heydon, [email protected] System Research Center

This is the first of a series of articles thatdescribe how Greg Nelson and I used theModula-3 programming language to imple-ment a constraint-based drawing editor calledJuno-2. The articles are meant to show howModula-3 and the rich collection of librariesincluded with src Modula-3 have been usedin a sophisticated application program.

In this article, I’ll describe how we used theFormsvbt, vbtkit, and Trestle libraries toimplement Juno-2’s graphical user interface.

Overview of Juno-2Juno-2 is a constraint-based drawing editorintended for the production of precise techni-cal drawings. The main goal of the project wasto build a usable constraint-based drawingeditor with an extensible constraint definitionlanguage. We hoped to build a system to pro-totype constraint-based interfaces for severaldifferent domains from within the applicationitself.

Constraints allow you to specify locations inyour drawing declaratively, rather than com-puting them imperatively. For example, todraw an equilateral triangle, you first draw anarbitrary triangle and then constrain its sidesto have equal length; Juno-2 will adjust thevertices to make the triangle equilateral.Moreover, the constraints are maintainedwhenever part of the picture is changed, soconstraints make it easier to cope with modifi-cations.

Most drawing editors like MacDraw allow youto align objects in various ways, but thosealignments are only temporary. By contrast,alignments based on Juno-2 constraints arepermanent. This means that alignment ismaintained even if an object is moved. Fur-thermore, constraints can be used to maintainsymmetry.

Juno-2 is a double-view editor: it has a graph-ics view that displays a view of the picture as itwould appear if printed, and a text view that

displays a program in the Juno-2 programminglanguage that corresponds to the picture.Editing either view causes the other view to beupdated. We use software double-buffering tomake dragging in the graphics view appearsmooth. Our implementation of a re-usablesoftware double-buffering object will be thesubject of a future article.

Juno-2 is written entirely in Modula-3. It isabout 26,000 lines of Modula-3 code, plusabout 600 lines of Formsvbt form code todescribe the user interface (see below) and6,000 lines of embedded Juno-2 code. Cur-rently, the system is not publicly available, butwe hope to make the binaries available soonfor various architectures.

Implementing the Juno-2 User Interface The Juno-2 user interface is built on top ofTrestle, Modula-3’s object-oriented windowsystem toolkit. The version of Trestle includedwith src Modula-3 runs on the X window sys-tem; an implementation for Windows/nt andWindows/95 is in progress.

The basic Trestle abstraction is an objectcalled a “virtual bitmap terminal”, or vbt. Eachvbt represents a share of the keyboard, mouse,and displays. vbts are comparable to the win-dows and widgets of other window systems.

A Trestle application’s user interface is struc-tured as a tree of vbts. The vbt at the root cor-responds to the top-level application window,and the vbts at the leaves generally corre-spond to the actual regions on the screenwhere painting occurs. The internal nodes ofthe tree are called split vbts. They divide theirregion of the screen between one or more chil-dren depending on the class of the split.

It is quite possible to build a user interfaceentirely out of Trestle vbts, but then the treeof vbts must be constructed explicitly in Mod-ula-3 code. Since the design of a user inter-face is often an iterative process, recompilingand relinking the application after eachchange to the user interface is tedious.

The FormsVBT library was designed to addressthis problem. The library provides proceduresthat read a declarative user-interface descrip-tion called a form and construct the corre-sponding tree of vbts. Since the form file isinterpreted at run-time, the turnaround time

a b

c d

e f

gh

ij

k

a HOR b ANDa HOR e ANDa HOR f ANDc HOR d ANDj HOR i ANDh HOR g AND(h, a) PARA (b, c) AND(h, a) PARA (b, j) AND(h, a) PARA (b, k) AND(h, a) PARA (b, g) AND(g, f) PARA (e, d) AND(g, f) PARA (e, i) AND(g, f) PARA (e, k) AND(g, f) PARA (e, h) AND(a, b) CONG (c, j) AND(a, h) CONG (g, f) AND(b, c) CONG (j, k)

DiGraph

PS Geometry

Arrow Ellipse

Math

R2

4.0

0.5

Allan Heydon is a Member ofResearch Staff at Digital Sys-tems Research Center. He iscurrently one of two peopleresponsible for the mainte-nance of SRC Modula-3. One of Allan’s areas of researchis in constraint-based drawingwith Juno-2 as explored in thisseries of articles. For moreinformation, see the Juno-2home page on the web:

http://www.research.digital.-com/SRC/juno-2

3 threads – fall 1995

between changes to the user interface is sig-nificantly reduced. Moreover, src Modula-3includes an application called formsedit thatallows users to edit forms and immediately seehow those forms will appear and behave whenincorporated into a Modula-3 application.This separates the task of designing theappearance of the user interface from that ofimplementing its functionality.

The Formsvbt library is built on top of alibrary called VBTkit, which defines many vbt

classes, all with a uniform 3D “look and feel.”These include the standard buttons, menus,file browsers, and text editors of most window-ing toolkits. But vbtkit also includes featureslike buttons and menu items that automati-cally pop-up sub-windows without requiringthe programmer to write any callback proce-dures.

Figure 1 shows the Juno-2 user interface.Across the top is a row of pull-down menus.The left sub-window is divided into an area fortool palettes and the main drawing window.The right sub-window contains two text edi-tors. The “Open Module” pop-up window con-tains a partial list of Juno-2’s predefinedmodules.

A Formsvbt form is a symbolic expression thatdescribes the structure and appearance of aTrestle-based user interface. It is structured asa list of nested components. The first elementof the list is the component type, and theremaining arguments are either properties of

Figure 1The Juno-2 User Interface

the component (name-value pairs) or nestedcomponents for its children. For example,here is a stripped-down version of the top-level Juno-2 form (double semicolons begincomment lines):

(HTile;; left-hand side(VBox

(HBox;; <<left menu-bar description goes here>>Fill)

(Bar 1)(HBox

(Generic %toolbox)(Bar 1)(Generic %drawing)))

;; right-hand side(VBox

(HBox;; <<right menu-bar description goes here>>Fill(Border

(Text %currFile RightAlign "Untitled.juno")))

(Bar 1)(VTile

(TextEdit %currModule)(TextEdit %currCmd))))

Each component may have a name, as speci-fied by the %name syntax. You can use thenames to refer to other components within theform, or to name components from Modula-3code. For example, you attach a callback pro-cedure to a button by giving the button aname and invoking the FormsVBT.AttachProcprocedure to associate the named button witha particular Modula-3 procedure.

In the above form, the symbolic expressionsfor the menus have been omitted. To give youan idea of what they’re like, here’s the sym-bolic expression for the Juno-2 menu on thefar left, which has items named About... andQuit.

(Menu (MenuLabel “Juno-2”) (VBox

(PopMButton (For aboutWindow) (TextL “About...”))

(MButton (Name quit) (TextL “Quit”)) ))

In this form, the component names MenuLabeland TextL are names of user-defined macros.Formsvbt does textual substitution of macrooccurrences by their instantiated definitions.For example, the expression (TextL <text>) gets

fall 1995 – threads 4

replaced by the expression (Text LeftAlign<text>), which causes the text to be left-aligned rather than centered. Macros make iteasy to encapsulate common aspects ofappearance in a central place.

Some Formsvbt components provide func-tionality that eliminates the need to associatecallback procedures with them. For example,the PopMButton component in the previousexample causes the sub-window namedaboutWindow to pop up when that menu item isselected. The form describing the sub-windowhas a special kind of button called a CloseBut-ton that causes the sub-window to disappearwhen the button is pressed. In Juno-2, Close-Buttons are used to cancel dialogues.

vbtkit (and hence, Formsvbt) includes awealth of components, many of which havebeen used in the implementation of Juno-2.For example, when a dialogue box is displayed,the rest of the application becomes passive tomouse clicks and typing. This is easily accom-plished by wrapping the entire Juno-2 form ina Filter component. Since Filter componentshave active and passive states, it is a simplematter to switch the filter between its activeand passive state by making Modula-3 proce-dure calls at the appropriate times.

As another example, we wanted to display theJuno-2 logo and a welcome message when theprogram started up, since there is a short delaywhile the program reads and compiles thebundled in Juno-2 modules. This was also eas-ily accomplished by wrapping the top-levelform in a TSplit component. A TSplit is a splitthat displays exactly one of its children at atime. Here’s an example of the top-level form:

(TSplit %tsplit (Which startupScreen);; Juno-2 logo (Filter %startupScreen Passive

(Cursor “XC_watch”) (VBox

Fill (Pixmap “Juno2Logo.ppm”)(Glue 10) “Welcome to Juno-2! Initializing...” Fill))

;; Main window(Filter %background

;; <<main form from above goes here>> ))

This example illustrates the use of properties.In addition to the use of the Name property, the

Which property has been associated with theTSplit component, and the Passive and Cursorproperties have been associated with the start-up screen Filter component.

The Which property of the TSplit specifieswhich child the TSplit should display initially.When the application has finished its initial-ization work, it calls:

FormsVBT.PutInteger(w, “tsplit”, 1)

to switch the TSplit component in w (the top-level window) to display child 1 (the childrenof a split are numbered starting from 0).

One nice aspect of the Formsvbt design isthat properties are inherited. This makes iteasy to make fairly global changes to theappearance of a user interface. For example,to change the background color of the entireform to a light grey, you could associate theproperty (BgColor “LightGrey”) with the form’stop-level component.

As mentioned before, Formsvbt includes astand-alone application called formsedit forediting and testing forms. Formsedit providesa text editor for editing a form, and a pre-viewer for viewing the instantiation of theform and for testing its behavior. Formsedit’srapid turn-around makes it easy to rapidly pro-totype different user interfaces.

Not every component in your user interfacewill have a corresponding Formsvbt compo-nent. Typically, the “guts” of an applicationhave application-specific vbts. In such cases,you can use a Generic Formsvbt component inyour form, and then replace that componentby the true vbt at run-time. This technique isused to replace the Juno-2 tool palette anddrawing view.

ConclusionsThe Modula-3 distribution includes a windowtoolkit called Trestle, a widget library calledvbtkit, a declarative user interface descriptionsystem called Formsvbt, and a program forinteractively constructing user interfacescalled formsedit. The vbtkit and Formsvbt

libraries, together with the formsedit interfacebuilder, made it easy to prototype and buildthe Juno-2 user interface. vbtkit provided allthe interface components we needed.

DiGraph

PS Geometry

Arrow Ellipse

Math

R2

Constraint solver (2429)Virtual machine (2857)Compiler (9727)User interface (10140)Predefined Juno−2 modules (5778)

0 100 200 300 4000

3

6

9

12

15

Area(K pixels)

Time (ms)

5 threads – fall 1995

Like most modern windowing toolkits, theTrestle and Formsvbt libraries require thatapplications be structured as an initializationroutine and a collection of callback routines.This general approach makes it difficult tobuild modal dialogues, since by default, themain window remains active when a dialoguesub-window appears. With Formsvbt, modaldialogues can be implemented by wrapping aFilter component around the top-level form,as described earlier.

Of course, with all the flexibility that Forms-vbt provides, it’s quite easy to create formswhose corresponding vbt trees contain hun-dreds of nodes. The Juno-2 form contains 559Formsvbt components, which are translatedinto a total of 731 vbts.

Overall, the vbtkit and Formsvbt libraries pro-vide a robust and flexible environment for con-structing graphical user interfaces quickly.The structure and appearance of an interfaceis described in a simple, declarative language,and its functionality is implemented sepa-rately by callback procedures written in Mod-ula-3.

How Modula-3 got its spots?Initialization of Object Types

Greg Nelson, [email protected] Systems Research Center

People often ask why Modula-3 does not dis-tinguish initialization methods. The answer isthat we have found it preferable to deal withthis issue by a convention instead of a lan-guage feature.

The convention is to name one of the methodsof a type init; this method is responsible forinitializing a newly-allocated object of thetype. A further convention is that the initmethod returns the object after initializing it.This is convenient; for example it allows codelike this:

VAR tbl := NEW(HashTable.T).init(size := 50); BEGIN ...

instead of like this:

VAR tbl := NEW(HashTable.T);

BEGIN tbl.init(size := 50); ...

If a default field value is provided when a typeis declared, then that field will be initialized tothat value in each newly allocated object. Thiscan often be used to avoid the need for aexplicit initialization method. For example, ifyou want an object to represent stacks of inte-gers of size at most ten, you could declare

TYPEStack = OBJECT

sp := 0;data: ARRAY [0..9] OF INTEGER;

METHODS ... END;

The .sp field of a newly-allocated Stack will beinitialized to zero automatically. The data fieldwill contain arbitrary values, but these valuesare irrelevant when sp is zero.

Default field values are frequently used toavoid init methods. For example, a newly-allo-cated MUTEX is ready to use: there is no need tocall any init method. Explicit init methods aregenerally needed only for types whose initial-ization depends on parameters supplied by theclient.

It is common for the initialization method of atype to call the initialization method of itssupertype, as in the following example:

TYPEA = OBJECT ... METHODS init(...): A; ... END; ... AB = A OBJECT METHODS init(...): AB := InitAB;... END

PROCEDURE InitAB(a: AB; ...): AB = BEGIN

EVAL NARROW(a, A).init(...); (* initialize extra fields *) RETURN a

END InitAB;

Notice that the AB init method is a newmethod, not an override of the A init method.This is typical: the init method signature for asubtype tends to be specific to that subtype.

Also notice that NARROW(a, A) views a as beingof type A; the result is to call A’s init methodinstead of AB’s. No run-time check is requiredby this NARROW. Finally, notice that EVAL isrequired to discard the result returned by A’sinit method.

Greg Nelson is a Member ofResearch Staff at Digital Sys-tems Research Center.

Aside from his key role as theeditor of Systems Programmingwith Modula-3, he has con-tributed to the development ofvarious Modula-3 libraries,such as Trestle and NetworkObjects.

fall 1995 – threads 6

If the language were changed to distinguishinitialization methods, the compiler might callthem automatically, or it might issue an errorif an object were used without being initial-ized. This might make the language morerobust, and is the main argument for dealingwith initialization in the language definitioninstead of by convention. We rejected theargument for several reasons.

First, it is problematic to have the compilercall the init method automatically. For exam-ple, in the InitAB procedure shown previously,the arguments to the supertype init methodmay be arbitrary expressions. They certainlyneed not be the same as the argument list ofInitAB, or a prefix of the argument list, or any-thing like that. Also, the call to the supertypeinit method is not always first or last withinthe subtype init method: it may occur in anintermediate position.

Second, if one checked (either statically ordynamically) that at least one init method hasbeen called for each allocated object beforethe object is used, the resulting sense of secu-rity would be far from complete. After all,guaranteeing that the init method has beencalled does not guarantee that it has actuallyinitialized every field that will be used.

Third, if careful checking is required for sometype, the implementor of the type can easilyproduce it by defining a boolean field “initial-ized” with a default value of false; setting it totrue in the initialization method, and test it inthe other methods. By hiding the field in theprivate part of the implementation, the imple-mentor can guarantee that no error in a clientprogram can cause the implementation tocompute with an uninitialized object. ✵

Lauren Schmitt is the founderof Critical Mass, Inc. CriticalMass will be the first commer-cial provider of the Modula-3language and accompanyingsupport. For more informationvisit the Critical Mass webpage: http://www.cmass.com/

Modula-3 in IndustryPhoton: An Environment for Building Distributed Applications

Lauren Schmitt, [email protected] Mass, Inc.

Most people who have used Modula-3 agreethat it provides a great deal of support fortoday’s programming tasks. Garbage collec-tion, thread support, exception handling, anda complete set of robust and well-documentedlibraries are among the features that makeModula-3 quite suitable for building large-scale robust distributed applications. Unfortu-nately, most people who may consider usingModula-3 in a commercial setting also agreethat, without a commercial implementationand support for Modula-3, it is difficult if notimpossible to convince management to allowprogrammers to use Modula-3.

We have taken the first step toward solvingthis problem. I am pleased to announce thatwe at Critical Mass, Inc. have been workingon a commercially-supported developmentenvironment, named Photon, based on src

Modula-3. Photon integrates Modula-3 into afamiliar user interface: that of a web browser,allowing the user to readily browse, build, andmanage large projects locally or over a net-work.

We intend to distribute Photon for a low pricewith an open license to make it easily availableto the masses. As part of our efforts, we willalso offer commercial support for Photon. Wehope Photon will be the first in a family ofModula-3 based products distributed by Criti-cal Mass.

A preview release of Photon will be availablebefore end of 1995 leading to an officialrelease in the first quarter of 1996. Our firsttarget platform for Photon is Linux; we intendto support other platforms as the demandrequires. More information regarding Photonwill be posted on Modula-3 newsgroup andwill be available via our home page, http://www.cmass.com. ✵

7 threads – fall 1995

Modula-3 in AcademiaUniversity of Klagenfurt, Austria

Laszlo [email protected]

Carsten [email protected]

University of Klagenfurt, Austria

TeachingWe first experimented with Modula-3 as ateaching tool in 1992. In a course on com-puter networks, students implemented a num-ber of different networking protocols inModula-3. In 1993 a working group wasestablished to discuss a new programming lan-guage to replace Modula-2 as the language forthe first programming course. In making thisdecision, we felt that the most important cri-teria in picking a language were: traditionalstructured programming concepts, support forobject-orientation, and availability of goodcompilers for both the Unix and dos environ-ments.

In the final evaluation phase the followingprogramming languages were considered:Eiffel, C++, Oberon-2, Ada, Modula-3 andTurbo-Pascal 6.0. The winner was Modula-3.Consequently, in 1993 we introduced Mod-ula-3 as the first and second courses program-ming language. Our first experiences havebeen very promising.

To support the curriculum, we have written anintroductory text for programming that usesModula-3 for its examples. It’s called Program-ming with Modula-3: An Introduction to Pro-gramming with Style which has appeared inGerman by Springer-Verlag and is in the pro-cess of being translated to English. The mainconcern of the book is to give a clean andcomprehensive introduction to programmingfor beginners of a computer science study. Westart with more traditional programming con-cepts and move toward advanced topics suchas object-oriented programming, parallel &concurrent programming, exception handling,and persistent data techniques. The book alsopresents a large number of complete exampleswritten in Modula-3.

Laszlo Boeszoermenyi andCarsten Weich teach at Uni-versity of Klagenfurt, Austria.

Their book, “Programmingwith Modula-3: An Introduc-tion to Programming withStyle,” ISBN 3-540-57911-7has been published in Ger-man. An English translationwill soon follow by Springer-Verlag.

For more information on theDOS port, see:

http://www.research.digital.-com/SRC/modula-3/html/m3pc.html

.

DOS PortAt the end of 1992 we made available the firstDOS port of Modula-3. The port was made byKlaus Preschern, as a member of the researchgroup of Professor Boeszoermenyi. This sys-tem is steadily used by our students, and isavailable freely for others via the Modula-3home page.

ResearchThe research group of Professor. L. Boeszoer-menyi (Karl-Heinz Eder, Andreas Stopper,Carsten Weich) in cooperation with Professor.J. Eder and M. Dobrovnik, are working on thea variety of research projects related to Mod-ula-3.

PPOSTppost (parallel persistent object store) is anobject store implemented in Modula-3 thatkeeps all data all the time in main memory ofa distributed set of computer nodes. ppost

uses two kinds of parallelism: horizontal andvertical.

In horizontal parallelism, objects are kept insets (called classes), which can be distributed“horizontally” among a number of workernodes. With the help of horizontal parallelism,we can store large amounts of data in mainmemory (several gigabytes and conceivablyseveral terabytes). Data is accessed with thespeed of internal memory.

Vertical parallelism provides persistence(write to disk) in parallel to normal transactionprocessing taking place on ppost. All modifi-cations of data are stored in a log file by thelog processor. With the help of the log informa-tion and the backup image of the database, anew actual database image on the disk can beproduced by a backup node. As such, diskmanagement is actually parallel to normaltransaction processing and does not slowdown data processing.

Parallel and Persistent SetsGeneral purpose programming languages stillconsider persistence and parallelism as fea-tures of secondary importance. Such featuresare usually added later with the help of somelibrary modules. This has the disadvantage ofthe loss of type safety and optimizations ofsome operations. Typically, programming lan-

fall 1995 – threads 8

guages supporting highly parallel architecturesare based on the array model (e.g. Vienna For-tran, Modula-2*, Modula-3*) as the arraymodel is quite adequate for scientific comput-ing. It is, however, inadequate for the manipu-lation of a large amount of data required formany information systems.

As an alternative, the set model is appropriateto manipulate a large amount of data. It alsosupports parallelism well; sets are by defini-tion an unordered collection of data, thereforeno assumption about the order of processingof the elements needs to be made. We lift therestrictions on sets in Modula-3 and extendthe language to introduce typed, polymorphicsets that may contain compatible types. Thisallows us to handle a large amount of data thatmaybe physically distributed over a number ofprocessors in a convenient way. Only a fewsyntactic additions are necessary to allowaccess to a powerful new feature. The imple-mentation does not have to be heavy-weighteither; we provide several alternative imple-mentations of a set for various uses.

Parallel OO Simulations

Simulation has always been a main researchdirection of object-orientation. Most work onparallel simulation concentrates on discreteevent simulations, which has the disadvantagethat it cannot take advantage of parallelisminherently available in the problem easily.With the help of Modula-3 Network Objectswe try to utilize this inherent parallelism andprovide models which preserve this parallel-ism as much as possible. Such a model can bemore easily mapped to a true parallel architec-ture. ✵

Advanced Research TopicsThe Whole Program Optimizer

Amer Diwan, [email protected] of Massachusetts at Amherst

As part of our efforts to improve the perfor-mance of object-oriented programs, in partic-ular, Modula-3 programs, we have developedthe Whole Program Optimizer (wpo). Thewpo optimizes multiple modules at once andthus has more information available to it thantraditional optimizers that optimize one mod-ule at a time. The wpo contains a number ofanalyses and optimizations that take advan-tage of the increased information. In theremainder of this article we give examples ofthe optimizations performed by the wpo, anddescribes the structure of the wpo. The fol-lowing example illustrates the kinds of optimi-zations targeted by the wpo:

INTERFACE TU;TYPE

Public = OBJECT METHODS f (); END;T <: Public;U <: T;

PROCEDURE foo (t: T); END TU;

MODULE TU;REVEAL T = Public BRANDED OBJECT

OVERRIDES f := Tf;

END;REVEAL U = U BRANDED OBJECT

OVERRIDESf := Uf;

END;PROCEDURE foo (t: T) =

BEGINt.f ();

END; BEGIN END TU;

MODULE C;IMPORT TU;BEGIN

TU.foo (NEW (TU.U));END C;

In procedure foo, the method invocation couldinvoke either procedure Tf or Uf. However, ifthe wpo has access to all the clients of TU (forexample, in module C) it can determine thatthe concrete type of formal t can only be U andtherefore the method invocation can bereplaced with a direct call to Uf.

Amer Diwan is a graduate stu-dent and a member of ObjectSystems Laboratory at thecomputer science departmentof the University of Massachu-setts at Amherst. Amer’s cur-rent research interests are incompiler optimizations andlanguage run-time systems.

For more information on hisproject, see:

http://osl-www.cs.mass.edu/˜oos

.

9 threads – fall 1995

Replacing a method invocation by a direct callspeeds up the program by removing methodlookup overhead and also by enabling otheroptimizations such as inlining. In this example,this optimization required knowledge of mod-ules other than the one being optimized.

Currently, the wpo is about 5000 lines ofModula- 3 code. Figure 1 illustrates how thewpo fits into a compilation framework.

The inputs to the wpo are a collection of codefiles and an optional profile file. Each code filecontains code for a Modula-3 module or inter-face; the code is represented as an annotatedabstract syntax tree (ast). The ast is annotatedwith full type and source level information,including source line numbers. All propertiesof the source modules that may be useful foroptimizations and source-level debugging aremaintained. The Modula-3 pickle facility isused to read and write the ast files readily. Wehave modified the src Modula-3 front end towrite the typed ast to pickle files. Each nodein the ast has a gen method which generatesthe stack intermediate representation (byinvoking the M3CG.T methods) which is theinput to the back end.

We have implemented a collection of analysesand optimizations in the wpo. Currently, thewpo removes the overhead of opaque types,and performs cloning, “if” conversion (similarto transformations in the Self compiler), typeanalysis for heap allocated data, and interpro-cedural concrete type inference to remove theoverhead of critical method invocations. Inaddition, the wpo performs some traditionalcompiler optimizations such as procedureinlining.

An important component of the wpo is thedata-flow engine which is implemented as ageneric module and solves forward-flow dataflow problems for any domain. We use thedata-flow engine to implement use-def analy-

front end adapter

Saved IR generated object code

Modula-3 source code

Whole Program Optimizer

profile

SRC Modula-3 front end

SRC Modula-3 back end

Figure 1Compilation Framework

sis and type inference.

While the wpo is most effective when theentire program is available to it, it can alsobe used on subsets of the program. In partic-ular, most of the time we don’t optimize thestandard libraries. To reduce the memoryrequirements, the wpo can be run in a modewhere it keeps only the modules it needs atany given time in memory rather than theentire program.

We found Modula-3 to be well-suited forthe implementation of the wpo. The objectmodel, opaque types, generic modules, anexcellent collection of standard libraries,and most importantly garbage collectionhave all contributed to an implementationthat is easy to understand and extend.

We also found Modula-3 programs to bewell-suited to optimizations. The small sizeof the language definition simplifies thedesign and implementation of optimizers.Also, the isolation of unsafe features allowsthe optimizer to be more aggressive on safemodules since it can make stronger assump-tions about concrete types of variables. Inunsafe languages, features such as arbitrarytype casts can violate these assumptions andthus cannot be made by the optimizer.

We have recently started experimenting withthe wpo. Preliminary results are promising.The analysis alone in wpo are able to con-vert up to 50% of method invocations todirect calls in our benchmark programs. ✵

fall 1995 – threads 10

check birds of

a feather (BOF)

listings

when&

where

You are cordially invited to

a meeting of the

Modula-3 User Group

at OOPSLA'95, in Austin, Texas

This meeting is open to all, especially current users

and others interested in learning more about Modula-3!

Our meeting will include presentations on what people are doing

with Modula-3 in various organizations. Craig Chambers &

Jeff Dean of University of Washington will describe their work on

applying advanced optimizations to Modula-3 as part of the Vortex project.

Allan Heydon of

DEC Systems

Research Center

will present

Juno-2, an

extensible constraint-based

drawing package

written in

Modula-3. Blair MacIntyre of

Columbia University

will present

his prototype

augmented reality system written using Modula-3 Network Objects. Lauren Schmitt of

Critical Mass Inc will unveil Photon, a programming environment written for Modula-3.

We also hope to cover a variety of topics about Modula-3 such as: ports to PC OSs (Win/NT, Win'95,

OS/2, Linux),

evangelizing, commercial

use, academic

and research

use, and

building distributed

applications with Modula-3.

Modula-3 is a simple and modular programming language, providing facilities for exception handling, concurrency,

object-oriented programming, automatic garbage collection, and systems programming without involving the

complexities forced by other

languages of its class. Modula-3 is both a practical

implementation language

for large software projects and an excellent teaching

language. An

implementation of Modula-3 is available

free of charge

from

Digital

Systems

Research

Center.

Please join us!

Organizers:

Farshad Nayeri &

Geoff Wyant

MASS

Introducing

a distributed program-ming environment for Modula-3.

You've just written your last destructor!

network

objects

threads

distributed

garbage

collection

partial

revelation

exception

handling

generics

coming soon from

http://www.cmass.com/