Skip to content

Instantly share code, notes, and snippets.

@tjarratt
Created June 21, 2019 12:11
Show Gist options
  • Save tjarratt/60bd3b6c22825e9a1017f46fec5bb74b to your computer and use it in GitHub Desktop.
Save tjarratt/60bd3b6c22825e9a1017f46fec5bb74b to your computer and use it in GitHub Desktop.
Extract from "Introduction to Program Optimizers"
Scalar Replacement of Aggregates
================================
Scalar replacement of aggregates makes other optimizations applicable to components of aggregates, such as C structures and Pascal records. It is a simple and effective optimization. It checks which components of the aggregate are simple scalars, and if they are not aliased (neither the components nor the whole aggregate), they are assigned to temporaries of the appropriate type. These temporaries become available to many optimizations.
The following example demonstrates how scalar replacement of Aggregates help other optimizations:
typedef enum { APPLE, BANANA, ORANGE } VARIETY;
typedef enum { LONG, ROUND } SHAPE;
typedef struct fruit {
VARIETY variety;
SHAPE shape; } FRUIT;
char* Red = "red" ;
char* Yellow = "yellow";
char* Orange = "orange";
char* color (CurrentFruit)
FRUIT *CurrentFruit;
{ switch (CurrentFruit->variety) {
case APPLE: return Red;
break;
case BANANA: return Yellow;
break;
case ORANGE: return Orange;
break;
}
}
main()
{ Fruit snack;
snack.variety = APPLE;
snack.shape = ROUND;
printf(“%s\n”,color(&snack));
}
Main procedure resulting from procedure integration and scalar replacement of aggregates (applied for the components of structure snack):
char* Red = "red" ;
char* Yellow = "yellow";
char* Orange = "orange";
main()
{ FRUIT snack
VARIETY t1;
SHAPE t2;
COLOR t3;
t1=APPLE;
t2=ROUND;
switch (t1) {
case APPLE: t3= Red;
break;
case BANANA: t3= Yellow;
break;
case ORANGE: t3= Orange;
break;
}
printf(“%s\n”,t3);
}
And after constant propagation and dead-code elimination:
main()
{ printf(“%s\n” ,”red”);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment