]> git.lizzy.rs Git - plan9front.git/blob - sys/doc/compiler.ms
qer(8): correct man page example (thanks, kenji)
[plan9front.git] / sys / doc / compiler.ms
1 .HTML "Plan 9 C Compilers
2 .TL
3 Plan 9 C Compilers
4 .AU
5 Ken Thompson
6 ken@plan9.bell-labs.com
7 .AB
8 .FS
9 Originally appeared, in a different form, in
10 .I
11 Proceedings of the Summer 1990 UKUUG Conference,
12 .R
13 pp. 41-51,
14 London, 1990.
15 .FE
16 This paper describes the overall structure and function of the Plan 9 C compilers.
17 A more detailed implementation document
18 for any one of the compilers
19 is yet to be written.
20 .AE
21 .NH
22 Introduction
23 .LP
24 There are many compilers in the series.
25 Six of the compilers (MIPS 3000, SPARC, Intel 386, Power PC, DEC Alpha, and Motorola 68020)
26 are considered active and are used to compile
27 current versions of Plan 9.
28 Several others (Motorola 68000, Intel 960, ARM 7500, AMD 29000) have had only limited use, such as
29 to program peripherals or experimental devices.
30 .NH
31 Structure
32 .LP
33 The compiler is a single program that produces an
34 object file.
35 Combined in the compiler are the traditional
36 roles of preprocessor, lexical analyzer, parser, code generator,
37 local optimizer,
38 and first half of the assembler.
39 The object files are binary forms of assembly
40 language,
41 similar to what might be passed between
42 the first and second passes of an assembler.
43 .LP
44 Object files and libraries
45 are combined by a loader
46 program to produce the executable binary.
47 The loader combines the roles of second half
48 of the assembler, global optimizer, and loader.
49 The names of the compliers, loaders, and assemblers
50 are as follows:
51 .DS
52 .ta 1.5i
53 .de Ta
54 \\$1    \f(CW\\$2\fP  \f(CW\\$3\fP  \f(CW\\$4\fP
55 ..
56 .Ta SPARC kc kl ka
57 .Ta Power\ PC qc ql qa
58 .Ta MIPS vc vl va
59 .Ta Motorola\ 68000 1c 1l 1a
60 .Ta Motorola\ 68020 2c 2l 2a
61 .Ta ARM\ 7500 5c 5l 5a
62 .Ta Intel\ 960 6c 6l 6a
63 .Ta DEC\ Alpha 7c 7l 7a
64 .Ta Intel\ 386 8c 8l 8a
65 .Ta AMD\ 29000 9c 9l 9a
66 .DE
67 There is a further breakdown
68 in the source of the compilers into
69 object-independent and
70 object-dependent
71 parts.
72 All of the object-independent parts
73 are combined into source files in the
74 directory
75 .CW /sys/src/cmd/cc .
76 The object-dependent parts are collected
77 in a separate directory for each compiler,
78 for example
79 .CW /sys/src/cmd/vc .
80 All of the code,
81 both object-independent and
82 object-dependent,
83 is machine-independent
84 and may be cross-compiled and executed on any
85 of the architectures.
86 .NH
87 The Language
88 .LP
89 The compiler implements ANSI C with some
90 restrictions and extensions
91 [ANSI90].
92 Most of the restrictions are due to
93 personal preference, while
94 most of the extensions were to help in
95 the implementation of Plan 9.
96 There are other departures from the standard,
97 particularly in the libraries,
98 that are beyond the scope of this
99 paper.
100 .NH 2
101 Register, volatile, const
102 .LP
103 The keyword
104 .CW register
105 is recognized syntactically
106 but is semantically ignored.
107 Thus taking the address of a
108 .CW register
109 variable is not diagnosed.
110 The keyword
111 .CW volatile
112 disables all optimizations, in particular registerization, of the corresponding variable.
113 The keyword
114 .CW const
115 generates warnings (if warnings are enabled by the compiler's
116 .CW -w
117 option) of non-constant use of the variable,
118 but does not affect the generated code.
119 .NH 2
120 The preprocessor
121 .LP
122 The C preprocessor is probably the
123 biggest departure from the ANSI standard.
124 .LP
125 The preprocessor built into the Plan 9 compilers does not support
126 .CW #if ,
127 although it does handle
128 .CW #ifdef
129 and
130 .CW #include .
131 If it is necessary to be more standard,
132 the source text can first be run through the separate ANSI C
133 preprocessor,
134 .CW cpp .
135 .NH 2
136 Unnamed substructures
137 .LP
138 The most important and most heavily used of the
139 extensions is the declaration of an
140 unnamed substructure or subunion.
141 For example:
142 .DS
143 .CW
144 .ta .1i .6i 1.1i 1.6i
145         typedef
146         struct  lock
147         {
148                 int    locked;
149         } Lock;
150
151         typedef
152         struct  node
153         {
154                 int     type;
155                 union
156                 {
157                         double dval;
158                         float  fval;
159                         long   lval;
160                 };
161                 Lock;
162         } Node;
163
164         Lock*   lock;
165         Node*   node;
166 .DE
167 The declaration of
168 .CW Node
169 has an unnamed substructure of type
170 .CW Lock
171 and an unnamed subunion.
172 One use of this feature allows references to elements of the
173 subunit to be accessed as if they were in
174 the outer structure.
175 Thus
176 .CW node->dval
177 and
178 .CW node->locked
179 are legitimate references.
180 .LP
181 When an outer structure is used
182 in a context that is only legal for
183 an unnamed substructure,
184 the compiler promotes the reference to the
185 unnamed substructure.
186 This is true for references to structures and
187 to references to pointers to structures.
188 This happens in assignment statements and
189 in argument passing where prototypes have been
190 declared.
191 Thus, continuing with the example,
192 .DS
193 .CW
194 .ta .1i .6i 1.1i 1.6i
195         lock = node;
196 .DE
197 would assign a pointer to the unnamed
198 .CW Lock
199 in
200 the
201 .CW Node
202 to the variable
203 .CW lock .
204 Another example,
205 .DS
206 .CW
207 .ta .1i .6i 1.1i 1.6i
208         extern void lock(Lock*);
209         func(...)
210         {
211                 ...
212                 lock(node);
213                 ...
214         }
215 .DE
216 will pass a pointer to the
217 .CW Lock
218 substructure.
219 .LP
220 Finally, in places where context is insufficient to identify the unnamed structure,
221 the type name (it must be a
222 .CW typedef )
223 of the unnamed structure can be used as an identifier.
224 In our example,
225 .CW &node->Lock
226 gives the address of the anonymous
227 .CW Lock
228 structure.
229 .NH 2
230 Structure displays
231 .LP
232 A structure cast followed by a list of expressions in braces is
233 an expression with the type of the structure and elements assigned from
234 the corresponding list.
235 Structures are now almost first-class citizens of the language.
236 It is common to see code like this:
237 .DS
238 .CW
239 .ta .1i
240         r = (Rectangle){point1, (Point){x,y+2}};
241 .DE
242 .NH 2
243 Initialization indexes
244 .LP
245 In initializers of arrays,
246 one may place a constant expression
247 in square brackets before an initializer.
248 This causes the next initializer to assign
249 the indicated element.
250 For example:
251 .DS
252 .CW
253 .ta .1i .6i 1.6i
254         enum    errors
255         {
256                 Etoobig,
257                 Ealarm,
258                 Egreg
259         };
260         char* errstrings[] =
261         {
262                 [Ealarm]        "Alarm call",
263                 [Egreg] "Panic: out of mbufs",
264                 [Etoobig]       "Arg list too long",
265         };
266 .DE
267 In the same way,
268 individual structures members may
269 be initialized in any order by preceding the initialization with
270 .CW .tagname .
271 Both forms allow an optional
272 .CW = ,
273 to be compatible with a proposed
274 extension to ANSI C.
275 .NH 2
276 External register
277 .LP
278 The declaration
279 .CW extern
280 .CW register
281 will dedicate a register to
282 a variable on a global basis.
283 It can be used only under special circumstances.
284 External register variables must be identically
285 declared in all modules and
286 libraries.
287 The feature is not intended for efficiency,
288 although it can produce efficient code;
289 rather it represents a unique storage class that
290 would be hard to get any other way.
291 On a shared-memory multi-processor,
292 an external register is
293 one-per-processor and neither one-per-procedure (automatic)
294 or one-per-system (external).
295 It is used for two variables in the Plan 9 kernel,
296 .CW u
297 and
298 .CW m .
299 .CW U
300 is a pointer to the structure representing the currently running process
301 and
302 .CW m
303 is a pointer to the per-machine data structure.
304 .NH 2
305 Long long
306 .LP
307 The compilers accept
308 .CW long
309 .CW long
310 as a basic type meaning 64-bit integer.
311 On all of the machines
312 this type is synthesized from 32-bit instructions.
313 .NH 2
314 Pragma
315 .LP
316 The compilers accept
317 .CW #pragma
318 .CW lib
319 .I libname
320 and pass the
321 library name string uninterpreted
322 to the loader.
323 The loader uses the library name to
324 find libraries to load.
325 If the name contains
326 .CW %O ,
327 it is replaced with
328 the single character object type of the compiler
329 (e.g.,
330 .CW v
331 for the MIPS).
332 If the name contains
333 .CW %M ,
334 it is replaced with
335 the architecture type for the compiler
336 (e.g.,
337 .CW mips
338 for the MIPS).
339 If the name starts with
340 .CW /
341 it is an absolute pathname;
342 if it starts with
343 .CW .
344 then it is searched for in the loader's current directory.
345 Otherwise, the name is searched from
346 .CW /%M/lib .
347 Such
348 .CW #pragma
349 statements in header files guarantee that the correct
350 libraries are always linked with a program without the
351 need to specify them explicitly at link time.
352 .LP
353 They also accept
354 .CW #pragma
355 .CW hjdicks
356 .CW on
357 (or
358 .CW yes
359 or
360 .CW 1 )
361 to cause subsequently declared data, until
362 .CW #pragma
363 .CW hjdicks
364 .CW off
365 (or
366 .CW no
367 or
368 .CW 0 ),
369 to be laid out in memory tightly packed in successive bytes, disregarding
370 the usual alignment rules.
371 Accessing such data can cause faults.
372 .LP
373 Similarly, 
374 .CW #pragma
375 .CW profile
376 .CW off
377 (or
378 .CW no
379 or
380 .CW 0 )
381 causes subsequently declared functions, until
382 .CW #pragma
383 .CW profile
384 .CW on
385 (or
386 .CW yes
387 or
388 .CW 1 ),
389 to be marked as unprofiled.
390 Such functions will not be profiled when 
391 profiling is enabled for the rest of the program.
392 .LP
393 Two
394 .CW #pragma
395 statements allow type-checking of
396 .CW print -like
397 functions.
398 The first, of the form
399 .P1
400 #pragma varargck argpos error 2
401 .P2
402 tells the compiler that the second argument to
403 .CW error
404 is a
405 .CW print
406 format string (see the manual page
407 .I print (2))
408 that specifies how to format
409 .CW error 's
410 subsequent arguments.
411 The second, of the form
412 .P1
413 #pragma varargck type "s" char*
414 .P2
415 says that the
416 .CW print
417 format verb
418 .CW s
419 processes an argument of
420 type
421 .CW char* .
422 If the compiler's
423 .CW -F
424 option is enabled, the compiler will use this information
425 to report type violations in the arguments to
426 .CW print ,
427 .CW error ,
428 and similar routines.
429 .NH
430 Object module conventions
431 .LP
432 The overall conventions of the runtime environment
433 are important
434 to runtime efficiency.
435 In this section,
436 several of these conventions are discussed.
437 .NH 2
438 Register saving
439 .LP
440 In the Plan 9 compilers,
441 the caller of a procedure saves the registers.
442 With caller-saves,
443 the leaf procedures can use all the
444 registers and never save them.
445 If you spend a lot of time at the leaves,
446 this seems preferable.
447 With callee-saves,
448 the saving of the registers is done
449 in the single point of entry and return.
450 If you are interested in space,
451 this seems preferable.
452 In both,
453 there is a degree of uncertainty
454 about what registers need to be saved.
455 Callee-saved registers make it difficult to
456 find variables in registers in debuggers.
457 Callee-saved registers also complicate
458 the implementation of
459 .CW longjmp .
460 The convincing argument is
461 that with caller-saves,
462 the decision to registerize a variable
463 can include the cost of saving the register
464 across calls.
465 For a further discussion of caller- vs. callee-saves,
466 see the paper by Davidson and Whalley [Dav91].
467 .LP
468 In the Plan 9 operating system,
469 calls to the kernel look like normal procedure
470 calls, which means
471 the caller
472 has saved the registers and the system
473 entry does not have to.
474 This makes system calls considerably faster.
475 Since this is a potential security hole,
476 and can lead to non-determinism,
477 the system may eventually save the registers
478 on entry,
479 or more likely clear the registers on return.
480 .NH 2
481 Calling convention
482 .LP
483 Older C compilers maintain a frame pointer, which is at a known constant
484 offset from the stack pointer within each function.
485 For machines where the stack grows towards zero,
486 the argument pointer is at a known constant offset
487 from the frame pointer.
488 Since the stack grows down in Plan 9,
489 the Plan 9 compilers
490 keep neither an
491 explicit frame pointer nor
492 an explicit argument pointer;
493 instead they generate addresses relative to the stack pointer.
494 .LP
495 On some architectures, the first argument to a subroutine is passed in a register.
496 .NH 2
497 Functions returning structures
498 .LP
499 Structures longer than one word are awkward to implement
500 since they do not fit in registers and must
501 be passed around in memory.
502 Functions that return structures
503 are particularly clumsy.
504 The Plan 9 compilers pass the return address of
505 a structure as the first argument of a
506 function that has a structure return value.
507 Thus
508 .DS
509 .CW
510 .ta .1i .6i 1.1i 1.6i
511         x = f(...)
512 .DE
513 is rewritten as
514 .DS
515 .CW
516 .ta .1i .6i 1.1i 1.6i
517         f(&x, ...)\f1.
518 .DE
519 This saves a copy and makes the compilation
520 much less clumsy.
521 A disadvantage is that if you call this
522 function without an assignment,
523 a dummy location must be invented.
524 .LP
525 There is also a danger of calling a function
526 that returns a structure without declaring
527 it as such.
528 With ANSI C function prototypes,
529 this error need never occur.
530 .NH
531 Implementation
532 .LP
533 The compiler is divided internally into
534 four machine-independent passes,
535 four machine-dependent passes,
536 and an output pass.
537 The next nine sections describe each pass in order.
538 .NH 2
539 Parsing
540 .LP
541 The first pass is a YACC-based parser
542 [Joh79].
543 Declarations are interpreted immediately,
544 building a block structured symbol table.
545 Executable statements are put into a parse tree
546 and collected,
547 without interpretation.
548 At the end of each procedure,
549 the parse tree for the function is
550 examined by the other passes of the compiler.
551 .LP
552 The input stream of the parser is
553 a pushdown list of input activations.
554 The preprocessor
555 expansions of
556 macros
557 and
558 .CW #include
559 are implemented as pushdowns.
560 Thus there is no separate
561 pass for preprocessing.
562 .NH 2
563 Typing
564 .LP
565 The next pass distributes typing information
566 to every node of the tree.
567 Implicit operations on the tree are added,
568 such as type promotions and taking the
569 address of arrays and functions.
570 .NH 2
571 Machine-independent optimization
572 .LP
573 The next pass performs optimizations
574 and transformations of the tree, such as converting
575 .CW &*x
576 and
577 .CW *&x
578 into
579 .CW x .
580 Constant expressions are converted to constants in this pass.
581 .NH 2
582 Arithmetic rewrites
583 .LP
584 This is another machine-independent optimization.
585 Subtrees of add, subtract, and multiply of integers are
586 rewritten for easier compilation.
587 The major transformation is factoring:
588 .CW 4+8*a+16*b+5
589 is transformed into
590 .CW 9+8*(a+2*b) .
591 Such expressions arise from address
592 manipulation and array indexing.
593 .NH 2
594 Addressability
595 .LP
596 This is the first of the machine-dependent passes.
597 The addressability of a processor is defined as the set of
598 expressions that is legal in the address field
599 of a machine language instruction.
600 The addressability of different processors varies widely.
601 At one end of the spectrum are the 68020 and VAX,
602 which allow a complex mix of incrementing,
603 decrementing,
604 indexing, and relative addressing.
605 At the other end is the MIPS,
606 which allows only registers and constant offsets from the
607 contents of a register.
608 The addressability can be different for different instructions
609 within the same processor.
610 .LP
611 It is important to the code generator to know when a
612 subtree represents an address of a particular type.
613 This is done with a bottom-up walk of the tree.
614 In this pass, the leaves are labeled with small integers.
615 When an internal node is encountered,
616 it is labeled by consulting a table indexed by the
617 labels on the left and right subtrees.
618 For example,
619 on the 68020 processor,
620 it is possible to address an
621 offset from a named location.
622 In C, this is represented by the expression
623 .CW *(&name+constant) .
624 This is marked addressable by the following table.
625 In the table,
626 a node represented by the left column is marked
627 with a small integer from the right column.
628 Marks of the form
629 .CW A\s-2\di\u\s0
630 are addressable while
631 marks of the form
632 .CW N\s-2\di\u\s0
633 are not addressable.
634 .DS
635 .B
636 .ta .1i 1.1i
637         Node    Marked
638 .CW
639         name    A\s-2\d1\u\s0
640         const   A\s-2\d2\u\s0
641         &A\s-2\d1\u\s0  A\s-2\d3\u\s0
642         A\s-2\d3\u\s0+A\s-2\d1\u\s0     N\s-2\d1\u\s0 \fR(note that this is not addressable)\fP
643         *N\s-2\d1\u\s0  A\s-2\d4\u\s0
644 .DE
645 Here there is a distinction between
646 a node marked
647 .CW A\s-2\d1\u\s0
648 and a node marked
649 .CW A\s-2\d4\u\s0
650 because the address operator of an
651 .CW A\s-2\d4\u\s0
652 node is not addressable.
653 So to extend the table:
654 .DS
655 .B
656 .ta .1i 1.1i
657         Node    Marked
658 .CW
659         &A\s-2\d4\u\s0  N\s-2\d2\u\s0
660         N\s-2\d2\u\s0+N\s-2\d1\u\s0     N\s-2\d1\u\s0
661 .DE
662 The full addressability of the 68020 is expressed
663 in 18 rules like this,
664 while the addressability of the MIPS is expressed
665 in 11 rules.
666 When one ports the compiler,
667 this table is usually initialized
668 so that leaves are labeled as addressable and nothing else.
669 The code produced is poor,
670 but porting is easy.
671 The table can be extended later.
672 .LP
673 This pass also rewrites some complex operators
674 into procedure calls.
675 Examples include 64-bit multiply and divide.
676 .LP
677 In the same bottom-up pass of the tree,
678 the nodes are labeled with a Sethi-Ullman complexity
679 [Set70].
680 This number is roughly the number of registers required
681 to compile the tree on an ideal machine.
682 An addressable node is marked 0.
683 A function call is marked infinite.
684 A unary operator is marked as the
685 maximum of 1 and the mark of its subtree.
686 A binary operator with equal marks on its subtrees is
687 marked with a subtree mark plus 1.
688 A binary operator with unequal marks on its subtrees is
689 marked with the maximum mark of its subtrees.
690 The actual values of the marks are not too important,
691 but the relative values are.
692 The goal is to compile the harder
693 (larger mark)
694 subtree first.
695 .NH 2
696 Code generation
697 .LP
698 Code is generated by recursive
699 descent.
700 The Sethi-Ullman complexity completely guides the
701 order.
702 The addressability defines the leaves.
703 The only difficult part is compiling a tree
704 that has two infinite (function call)
705 subtrees.
706 In this case,
707 one subtree is compiled into the return register
708 (usually the most convenient place for a function call)
709 and then stored on the stack.
710 The other subtree is compiled into the return register
711 and then the operation is compiled with
712 operands from the stack and the return register.
713 .LP
714 There is a separate boolean code generator that compiles
715 conditional expressions.
716 This is fundamentally different from compiling an arithmetic expression.
717 The result of the boolean code generator is the
718 position of the program counter and not an expression.
719 The boolean code generator makes extensive use of De Morgan's rule.
720 The boolean code generator is an expanded version of that described
721 in chapter 8 of Aho, Sethi, and Ullman
722 [Aho87].
723 .LP
724 There is a considerable amount of talk in the literature
725 about automating this part of a compiler with a machine
726 description.
727 Since this code generator is so small
728 (less than 500 lines of C)
729 and easy,
730 it hardly seems worth the effort.
731 .NH 2
732 Registerization
733 .LP
734 Up to now,
735 the compiler has operated on syntax trees
736 that are roughly equivalent to the original source language.
737 The previous pass has produced machine language in an internal
738 format.
739 The next two passes operate on the internal machine language
740 structures.
741 The purpose of the next pass is to reintroduce
742 registers for heavily used variables.
743 .LP
744 All of the variables that can be
745 potentially registerized within a procedure are
746 placed in a table.
747 (Suitable variables are any automatic or external
748 scalars that do not have their addresses extracted.
749 Some constants that are hard to reference are also
750 considered for registerization.)
751 Four separate data flow equations are evaluated
752 over the procedure on all of these variables.
753 Two of the equations are the normal set-behind
754 and used-ahead
755 bits that define the life of a variable.
756 The two new bits tell if a variable life
757 crosses a function call ahead or behind.
758 By examining a variable over its lifetime,
759 it is possible to get a cost
760 for registerizing.
761 Loops are detected and the costs are multiplied
762 by three for every level of loop nesting.
763 Costs are sorted and the variables
764 are replaced by available registers on a greedy basis.
765 .LP
766 The 68020 has two different
767 types of registers.
768 For the 68020,
769 two different costs are calculated for
770 each variable life and the register type that
771 affords the better cost is used.
772 Ties are broken by counting the number of available
773 registers of each type.
774 .LP
775 Note that externals are registerized together with automatics.
776 This is done by evaluating the semantics of a ``call'' instruction
777 differently for externals and automatics.
778 Since a call goes outside the local procedure,
779 it is assumed that a call references all externals.
780 Similarly,
781 externals are assumed to be set before an ``entry'' instruction
782 and assumed to be referenced after a ``return'' instruction.
783 This makes sure that externals are in memory across calls.
784 .LP
785 The overall results are satisfactory.
786 It would be nice to be able to do this processing in
787 a machine-independent way,
788 but it is impossible to get all of the costs and
789 side effects of different choices by examining the parse tree.
790 .LP
791 Most of the code in the registerization pass is machine-independent.
792 The major machine-dependency is in
793 examining a machine instruction to ask if it sets or references
794 a variable.
795 .NH 2
796 Machine code optimization
797 .LP
798 The next pass walks the machine code
799 for opportunistic optimizations.
800 For the most part,
801 this is highly specific to a particular
802 processor.
803 One optimization that is performed
804 on all of the processors is the
805 removal of unnecessary ``move''
806 instructions.
807 Ironically,
808 most of these instructions were inserted by
809 the previous pass.
810 There are two patterns that are repetitively
811 matched and replaced until no more matches are
812 found.
813 The first tries to remove ``move'' instructions
814 by relabeling variables.
815 .LP
816 When a ``move'' instruction is encountered,
817 if the destination variable is set before the
818 source variable is referenced,
819 then all of the references to the destination
820 variable can be renamed to the source and the ``move''
821 can be deleted.
822 This transformation uses the reverse data flow
823 set up in the previous pass.
824 .LP
825 An example of this pattern is depicted in the following
826 table.
827 The pattern is in the left column and the
828 replacement action is in the right column.
829 .DS
830 .CW
831 .ta .1i .6i 1.6i 2.1i 2.6i
832         MOVE    a->b            \fR(remove)\fP
833 .R
834         (sequence with no mention of \f(CWa\fP)
835 .CW
836         USE     b               USE     a
837 .R
838         (sequence with no mention of \f(CWa\fP)
839 .CW
840         SET     b               SET     b
841 .DE
842 .LP
843 Experiments have shown that it is marginally
844 worthwhile to rename uses of the destination variable
845 with uses of the source variable up to
846 the first use of the source variable.
847 .LP
848 The second transform will do relabeling
849 without deleting instructions.
850 When a ``move'' instruction is encountered,
851 if the source variable has been set prior
852 to the use of the destination variable
853 then all of the references to the source
854 variable are replaced by the destination and
855 the ``move'' is inverted.
856 Typically,
857 this transformation will alter two ``move''
858 instructions and allow the first transformation
859 another chance to remove code.
860 This transformation uses the forward data flow
861 set up in the previous pass.
862 .LP
863 Again,
864 the following is a depiction of the transformation where
865 the pattern is in the left column and the
866 rewrite is in the right column.
867 .DS
868 .CW
869 .ta .1i .6i 1.6i 2.1i 2.6i
870         SET     a               SET     b
871 .R
872         (sequence with no use of \f(CWb\fP)
873 .CW
874         USE     a               USE     b
875 .R
876         (sequence with no use of \f(CWb\fP)
877 .CW
878         MOVE    a->b            MOVE    b->a
879 .DE
880 Iterating these transformations
881 will usually get rid of all redundant ``move'' instructions.
882 .LP
883 A problem with this organization is that the costs
884 of registerization calculated in the previous pass
885 must depend on how well this pass can detect and remove
886 redundant instructions.
887 Often,
888 a fine candidate for registerization is rejected
889 because of the cost of instructions that are later
890 removed.
891 .NH 2
892 Writing the object file
893 .LP
894 The last pass walks the internal assembly language
895 and writes the object file.
896 The object file is reduced in size by about a factor
897 of three with simple compression
898 techniques.
899 The most important aspect of the object file
900 format is that it is independent of the compiling machine.
901 All integer and floating numbers in the object
902 code are converted to known formats and byte
903 orders.
904 .NH
905 The loader
906 .LP
907 The loader is a multiple pass program that
908 reads object files and libraries and produces
909 an executable binary.
910 The loader also does some minimal
911 optimizations and code rewriting.
912 Many of the operations performed by the
913 loader are machine-dependent.
914 .LP
915 The first pass of the loader reads the
916 object modules into an internal data
917 structure that looks like binary assembly language.
918 As the instructions are read,
919 code is reordered to remove
920 unconditional branch instructions.
921 Conditional branch instructions are inverted
922 to prevent the insertion of unconditional branches.
923 The loader will also make a copy of a few instructions
924 to remove an unconditional branch.
925 .LP
926 The next pass allocates addresses for
927 all external data.
928 Typical of processors is the MIPS,
929 which can reference ±32K bytes from a
930 register.
931 The loader allocates the register
932 .CW R30
933 as the static pointer.
934 The value placed in
935 .CW R30
936 is the base of the data segment plus 32K.
937 It is then cheap to reference all data in the
938 first 64K of the data segment.
939 External variables are allocated to
940 the data segment
941 with the smallest variables allocated first.
942 If all of the data cannot fit into the first
943 64K of the data segment,
944 then usually only a few large arrays
945 need more expensive addressing modes.
946 .LP
947 For the MIPS processor,
948 the loader makes a pass over the internal
949 structures,
950 exchanging instructions to try
951 to fill ``delay slots'' with useful work.
952 If a useful instruction cannot be found
953 to fill a delay slot,
954 the loader will insert
955 ``noop''
956 instructions.
957 This pass is very expensive and does not
958 do a good job.
959 About 40% of all instructions are in
960 delay slots.
961 About 65% of these are useful instructions and
962 35% are ``noops.''
963 The vendor-supplied assembler does this job
964 more effectively,
965 filling about 80%
966 of the delay slots with useful instructions.
967 .LP
968 On the 68020 processor,
969 branch instructions come in a variety of
970 sizes depending on the relative distance
971 of the branch.
972 Thus the size of branch instructions
973 can be mutually dependent.
974 The loader uses a multiple pass algorithm
975 to resolve the branch lengths
976 [Szy78].
977 Initially, all branches are assumed minimal length.
978 On each subsequent pass,
979 the branches are reassessed
980 and expanded if necessary.
981 When no more expansions occur,
982 the locations of the instructions in
983 the text segment are known.
984 .LP
985 On the MIPS processor,
986 all instructions are one size.
987 A single pass over the instructions will
988 determine the locations of all addresses
989 in the text segment.
990 .LP
991 The last pass of the loader produces the
992 executable binary.
993 A symbol table and other tables are
994 produced to help the debugger to
995 interpret the binary symbolically.
996 .LP
997 The loader places absolute source line numbers in the symbol table.
998 The name and absolute line number of all
999 .CW #include
1000 files is also placed in the
1001 symbol table so that the debuggers can
1002 associate object code to source files.
1003 .NH
1004 Performance
1005 .LP
1006 The following is a table of the source size of the MIPS
1007 compiler.
1008 .DS
1009 .ta .1i .6i
1010         lines   module
1011         \0509   machine-independent headers
1012         1070    machine-independent YACC source
1013         6090    machine-independent C source
1014
1015         \0545   machine-dependent headers
1016         6532    machine-dependent C source
1017
1018         \0298   loader headers
1019         5215    loader C source
1020 .DE
1021 .LP
1022 The following table shows timing
1023 of a test program
1024 that plays checkers, running on a MIPS R4000.
1025 The test program is 26 files totaling 12600 lines of C.
1026 The execution time does not significantly
1027 depend on library implementation.
1028 Since no other compiler runs on Plan 9,
1029 the Plan 9 tests were done with the Plan 9 operating system;
1030 the other tests were done on the vendor's operating system.
1031 The hardware was identical in both cases.
1032 The optimizer in the vendor's compiler
1033 is reputed to be extremely good.
1034 .DS
1035 .ta .1i .9i
1036         \0\04.49s       Plan 9 \f(CWvc\fP \f(CW-N\fP compile time (opposite of \f(CW-O\fP)
1037         \0\01.72s       Plan 9 \f(CWvc\fP \f(CW-N\fP load time
1038         148.69s Plan 9 \f(CWvc\fP \f(CW-N\fP run time
1039
1040         \015.07s        Plan 9 \f(CWvc\fP compile time (\f(CW-O\fP implicit)
1041         \0\01.66s       Plan 9 \f(CWvc\fP load time
1042         \089.96s        Plan 9 \f(CWvc\fP run time
1043
1044         \014.83s        vendor \f(CWcc\fP compile time
1045         \0\00.38s       vendor \f(CWcc\fP load time
1046         104.75s vendor \f(CWcc\fP run time
1047
1048         \043.59s        vendor \f(CWcc\fP \f(CW-O\fP compile time
1049         \0\00.38s       vendor \f(CWcc\fP \f(CW-O\fP load time
1050         \076.19s        vendor \f(CWcc\fP \f(CW-O\fP run time
1051
1052         \0\08.19s       vendor \f(CWcc\fP \f(CW-O3\fP compile time
1053         \035.97s        vendor \f(CWcc\fP \f(CW-O3\fP load time
1054         \071.16s        vendor \f(CWcc\fP \f(CW-O3\fP run time
1055 .DE
1056 .LP
1057 To compare the Intel compiler,
1058 a program that is about 40% bit manipulation and
1059 about 60% single precision floating point was
1060 run on the same 33 MHz 486, once under Windows
1061 compiled with the Watcom compiler, version 10.0,
1062 in 16-bit mode and once under
1063 Plan 9 in 32-bit mode.
1064 The Plan 9 execution time was 27 sec while the Windows
1065 execution time was 31 sec.
1066 .NH
1067 Conclusions
1068 .LP
1069 The new compilers compile
1070 quickly,
1071 load slowly,
1072 and produce
1073 medium quality
1074 object code.
1075 The compilers are relatively
1076 portable,
1077 requiring but a couple of weeks' work to
1078 produce a compiler for a different computer.
1079 For Plan 9,
1080 where we needed several compilers
1081 with specialized features and
1082 our own object formats,
1083 this project was indispensable.
1084 It is also necessary for us to
1085 be able to freely distribute our compilers
1086 with the Plan 9 distribution.
1087 .LP
1088 Two problems have come up in retrospect.
1089 The first has to do with the
1090 division of labor between compiler and loader.
1091 Plan 9 runs on multi-processors and as such
1092 compilations are often done in parallel.
1093 Unfortunately,
1094 all compilations must be complete before loading
1095 can begin.
1096 The load is then single-threaded.
1097 With this model,
1098 any shift of work from compile to load
1099 results in a significant increase in real time.
1100 The same is true of libraries that are compiled
1101 infrequently and loaded often.
1102 In the future,
1103 we may try to put some of the loader work
1104 back into the compiler.
1105 .LP
1106 The second problem comes from
1107 the various optimizations performed over several
1108 passes.
1109 Often optimizations in different passes depend
1110 on each other.
1111 Iterating the passes could compromise efficiency,
1112 or even loop.
1113 We see no real solution to this problem.
1114 .NH
1115 References
1116 .LP
1117 [Aho87] A. V. Aho, R. Sethi, and J. D. Ullman,
1118 .I
1119 Compilers \- Principles, Techniques, and Tools,
1120 .R
1121 Addison Wesley,
1122 Reading, MA,
1123 1987.
1124 .LP
1125 [ANSI90] \f2American National Standard for Information Systems \-
1126 Programming Language C\f1, American National Standards Institute, Inc.,
1127 New York, 1990.
1128 .LP
1129 [Dav91] J. W. Davidson and D. B. Whalley,
1130 ``Methods for Saving and Restoring Register Values across Function Calls'',
1131 .I
1132 Software\-Practice and Experience,
1133 .R
1134 Vol 21(2), pp. 149-165, February 1991.
1135 .LP
1136 [Joh79] S. C. Johnson,
1137 ``YACC \- Yet Another Compiler Compiler'',
1138 .I
1139 UNIX Programmer's Manual, Seventh Ed., Vol. 2A,
1140 .R
1141 AT&T Bell Laboratories,
1142 Murray Hill, NJ,
1143 1979.
1144 .LP
1145 [Set70] R. Sethi and J. D. Ullman,
1146 ``The Generation of Optimal Code for Arithmetic Expressions'',
1147 .I
1148 Journal of the ACM,
1149 .R
1150 Vol 17(4), pp. 715-728, 1970.
1151 .LP
1152 [Szy78] T. G. Szymanski,
1153 ``Assembling Code for Machines with Span-dependent Instructions'',
1154 .I
1155 Communications of the ACM,
1156 .R
1157 Vol 21(4), pp. 300-308, 1978.