# REP84: Value Manipulation Analysis (VMA)
###### tags: `vma` `dla` `type-recovery` `analysis` `model`
**Status**: `🟡 NEEDSREVIEW`
## What is this?
This REP describes a *dataflow model type provider* (see [REP89](https://pad.rev.ng/BvdRKjecS5igRP1ZE8WLHw)) for *type recovery* (see [REP71](https://pad.rev.ng/yDe5Yeb3TqGhxVAMKnjZ5A)), called Value Manipulation Analysis (VMA).
VMA is a *dataflow type provider*
[REP90](https://pad.rev.ng/jEDFbwz_RNi2K8sTWxChbw) also describes how such *dataflow type providers* can be integrated into the current DLA codebase without implementing the full REP71.
## Why is it important?
Today, for a function whose body is a single `sdiv`, `revng` emits something like the following C code, which is full of ugly unnecessary casts.
```c
generic64_t f(generic64_t a, generic64_t b) {
return (generic64_t)((int64_t) a / (int64_t) b);
}
```
VMA is what turns that into `int64_t f(int64_t, int64_t)`.
## Design
### VMA in the pipeline
VMA is implemented as a *dataflow model type provider* as described by [REP89](https://pad.rev.ng/BvdRKjecS5igRP1ZE8WLHw).
### Interprocedural propagation
Intuitively, it is beneficial to enable VMA to propagate information across many functions.
In the long term, we should evaluate implementing this as proper interprocedural, bidirectional propagation, with the mechanism described in [REP88](https://pad.rev.ng/vIsgFC6WTUip0DcXkoTX8g), which would also enable us to handle recursion properly.
However, in practice, at the moment we will restrict this propagation to happen only from the callees to the callers, never in the opposite direction.
This is the result of practical concerns: keeping interprocedural propagation simple enables to make it one-sweep, without the need of a full-blown monotone framework, and without coupling this REP with REP88, while at the same time bringing home important results.
Given that we want to propagate only from callees to callers, we can use a post-order visit on the call graph to drive the interprocedural logic.
Informally, it works like this.
For each function $F$ in post order on the call graph:
* Analyze $F$ to see if we can provide better argument types and/or return types.
* Update the model of the function prototype accordingly.
### Intraprocedural propagation
This analysis is implemented as a monotone framework over a type-flow graph defined in this REP, using the set of scalar `model::Type`s as lattice.
This will be implemented using the `mfp` classes coming with `revng`.
In order to do this we need to specify the following things.
* The *lattice*, with its comparison operator and combine/join operator.
* The *type-flow graph* (also called TFG in this document), and how to build it from LLVM IR.
* The *transfer functions*.
* How to initialize the initial lattice element for each node of the TFG.
### The lattice of scalars
VMA needs to map each `llvm::Value` in all the input `llvm::Module`s to a scalar `model::Type` if possible.
To this end, we can define the lattice of all scalar `model::Type`s.
This lattice goes from less decided, less refined scalars to more defined, more refined scalars.
The lattice is represented in the following graph.
Remember that VMA does not reason about sizes, so the ordering can only be defined among scalars of the same size.
From now on we will use shorthands like `generic*_t` or simply `generic` to express the scalars abstracting away the size. In the rest of the REP the size can be considered fixed.
It is has some similarity to the lattice used by *type refinement* in [REP70](https://pad.rev.ng/MOk3Vm5xT0aOPK_7KczSdw?view#Partial-order-of-types-kinds), with a few important differences:
* it is upside down
* it has a weak and a strong version of each non-typedefed primitive and pointer scalar type
* it is restricted to scalar types, since non-scalar types are not responsibility of VMA.
* it has pointers
* it has floats, that were not supported at the time of REP70 design
```graphviz
digraph {
rankdir = BT
node [margin="0.4,0.1",shape=box]
generic[label="generic\n(TOP)"]
tdgeneric1[label="typedef\ngeneric_1"]
tdgeneric2[label="typedef\ngeneric_2"]
wgeneric[label="weak\ngeneric"]
wgeneric->tdgeneric1->generic
wgeneric->tdgeneric2->generic
{
rank=same
float[label="float"]
pon[label="pointer_or_number"]
}
{
rank=same
wfloat[label="weak\nfloat"]
wpon[label="weak\npointer_or_number"]
}
{
rank=same
tdfloat1[label="typedef\nfloat_1"]
tdfloat2[label="typedef\nfloat_2"]
}
float->wgeneric
wfloat->tdfloat1->float
wfloat->tdfloat2->float
{
rank=same
tdpon1[label="typedef\npointer_or_number_1"]
tdpon2[label="typedef\npointer_or_number_2"]
}
pon->wgeneric
wpon->tdpon1->pon
wpon->tdpon2->pon
{
rank=same
p[label="void*"]
n[label="number"]
}
{
rank=same
wp[label="weak\nvoid *"]
wn[label="weak\nnumber"]
}
p->wpon
{
rank=same
p1[label="T1*"]
p2[label="T2*"]
}
{
rank=same
wp1[label="weak\nT1*"]
wp2[label="weak\nT2*"]
}
{
rank=same
tdp1[label="typedef\nvoid* 1"]
tdp2[label="typedef\nvoid* 2"]
td1p1[label="typedef\nT1*"]
td2p2[label="typedef\nT2*"]
}
wp->tdp1->p
wp->tdp2->p
wp->wp1->td1p1->p1->p
wp->wp2->td2p2->p2->p
{
rank=same
tdn1[label="typedef\nnumber_1"]
tdn2[label="typedef\nnumber_2"]
}
n->wpon
wn->tdn1->n
wn->tdn2->n
{
rank=same
u[label="unsigned"]
s[label="signed"]
}
{
rank=same
wu[label="weak\nunsigned"]
ws[label="weak\nsigned"]
}
tdu1[label="typedef\nunsigned 1"]
tdu2[label="typedef\nunsigned 2"]
u->wn
wu->tdu1->u
wu->tdu2->u
tds1[label="typedef\nsigned 1"]
tds2[label="typedef\nsigned 2"]
s->wn
ws->tds1->s
ws->tds2->s
{ rank=same tdu1 tdu2 tds2 tds1 }
{
rank=same
uenum1[label="unsigned\nenum 1"]
senum1[label="signed\nenum 1"]
}
{
rank=same
wuenum1[label="weak\nunsigned\nenum 1"]
wsenum1[label="weak\nsigned\nenum 1"]
}
uenum1->u
wu->wuenum1->tduenum1->uenum1
senum1->s
ws->wsenum1->tdsenum1->senum1
{
rank=same
tduenum1[label="typedef\nunsigned\nenum 1"]
tdsenum1[label="typedef\nsigned\nenum 1"]
tds1 tds2
tdu1 tdu2
}
bottom[label="BOTTOM\nmodel::Type::empty()"]
bottom->ws
bottom->wu
bottom->wfloat
bottom->wp
}
```
The picture represents the lattice, with the ordering, and implies the combine: combining X and Y means finding the lowest element on the lattice above that is comparable with both and higher than both.
The picture shows only diamond shaped regions with one layer of typedefs, between weak and strong version of the same type, but this structure must be intended as recursive, as in the following example with a where `td1` is `typedef generic td1`.
```graphviz
digraph {
node [margin="0.4,0.1",shape=box]
rankdir = BT
generic[label="generic (TOP)"]
td1[label="strong td1"]
tdtd1[label="typedef td1 tdtd1"]
tdtd2[label="typedef td1 tdtd2"]
wtd1[label="weak td1"]
wgeneric[label="weak generic"]
td1->generic
tdtd1->td1
tdtd2->td1
wtd1->tdtd1
wtd1->tdtd2
wgeneric->wtd1
}
```
### The type-flow graph (TFG)
At the level of an individual function we need some form of type-flow graph.
This kind of graph represents how type information flows from/to values and operand uses.
#### Nodes - type operations
Nodes in the TFG represent *operations on types not on values*.
In practice each type operation represents a set of constraints on types, induced by some data operations.
As a simple intuition: a `load` induces a the following set of constraints on the type of the pointer operand and of the result: 1) the type of the operand must be capable of representing a pointer; 2) the type of the operand must have exactly one level of pointerness more than the type of the result; 3) the type of the result must have exactly one level of pointerness less then the operand type.
Constraints 2 and 3 encode the same information, and in principle they could be represented on the graph as different kind of edges, but that would require per-edge dedicated transfer functions that we want to avoid.
The different kinds of type constraints that we want to represent are the following.
Each has some additional property that it requires on its neighbors that should be checked with a dedicated `verify` for consistency.
1. *produce*
Can only have outgoing edges.
Constrains the types of the neighbors, requiring them to be capable of representing a fixed type.
2. *take address*
Can only have a single incoming edge and a single outgoing edge.
Constrains the type coming from the incoming edge to be capable of representing a pointer, and the types of the outgoing edges to being capable of representing what can be obtained by dereferencing that pointer.
3. *dereference*
The opposite of *take address*.
Can only have a single incoming edge and a single outgoing edge.
Constrains the type on the outgoing edges to be capable of representing a pointer, and the types of incoming edge to being capable of representing what can be obtained by dereferencing that pointer.
4. *extend*
Can only have a single incoming edge and a single outgoing edge.
Constrains the type on the outgoing edges to being capable of representing a type that can be obtained by the incoming edge by widening its size to a fixed size.
5. *truncate*
The opposite of *extend*
Can only have a single incoming edge and a single outgoing edge.
Constrains the type coming on the outgoing edges to being capable of representing a type that can be obtained by the incoming edge by truncating its size to a fixed size.
6. *propagate*
Can have any number of incoming and outgoing edges, but each node connected to it via an incoming must also be connected via outgoing.
Represents that constraint that all the neighbors must have the same type, without imposing any restriction on what that type should be.
7. *require*
Can have any number of incoming and outgoing edges, but each node connected to it via an incoming must also be connected via outgoing.
Represents that constraint that all the neighbors must have the same type, without but imposing the restriction that they should be capable of representing a given type.
So a node can be represented as follows.
```cpp
class TypeOperation {
// The kind of node this represents.
enum {
Produce,
TakeAddress,
Dereference,
Extend,
Truncate,
Propagate,
Require,
} Kind;
// Some node kinds are parametric.
// The following fields are parameters.
// Type parameter. Can be empty.
// Represents the required type for `Produce` and `Require`.
// Must be emtpy for `TakeAddress` and `Dereference`, since they
// never carry strong information on the pointee.
// Must be empty for `Propagate`, `Truncate` since they don't carry
// strong information.
// Must be empty for `Extend`, because the signedness of the
// extension is carried elsewhere (see below on `sext`/`zext`).
model::Type Type = model::Type::empty();
// Size parameter. 0 means unused
// It's only meaningful for `Extend` and `Truncate`, for which it
// represents the extended/truncated size in bytes respectively.
//
// TODO: could also be meaningful for `TakeAddress` `Dereference` to
// encode the pointer size???
uint64_t Size = 0;
// Optional backreferences to LLVM IR.
// They are the Value and (optionally) operands associated with this node.
// Used to refer back to LLVM IR after the analysis and for debug prints.
// Must **never** be used for the analysis.
llvm::Value *Value;
llvm::SmallVector<llvm::Use *, 2> Operands;
};
```
#### Edges
On a TFG, nodes determine how type information flows, while edges determine *where* if flows.
Given that nodes are type operations that already determine how the type information flows, there is no need to have many different kind of edges.
In practice, this means that in a TFG built starting from LLVM IR there will be edges that, informally, go *in the same direction* as data (from operands to users), but also *in the opposite direction* (from users to operands), and even in directions and ways that can't be represented on a dataflow-graph, such as *from an operand to another*.
This is not explictly visible on the TFG though, because all type-flow edges are equal. It's just an informal description to ease the reader's intuition.
In the remainder of this document, whenever we show small snippets of the TFG to describe how the nodes and the edges are setup, we will informally refer to these kind of edges as
* *use edges* when they go from the node associated to a `Value`, to a node associated to a `Use` of that value.
* *operand edges* when they go from the node associated to a `User` to a node associated with the used `Value`.
All of this is just for the sake of exposition, and is not represented in the TFG edges explicitly.
There are also edges that are neither *operand edges* nor *use edges* so we don't tag them in any specific way.
### Graph initialization
To initialize the graph we look at each instruction in the function.
For each instruction, we generate one or many `TypeOperation` nodes.
One of such `TypeOperation` nodes can be associated with the instruction's `Value` and/or with one or more of the the instruction's operand `Use`s.
The initialization phase must hold a map from `Value` to the `TypeOperation` associated with the instruction's `Value` and a map from `Use` to the `TypeOperation` associated with that use.
When a `TypeOperation` is associated with a `Value`, its `Value` field should be initialized accordingly for consistency. The same should happen if it's associated with an `Use`.
The map is temporary, only used to bring up the graph. The `Value` field is what matters at the end of the analysis to write back the results.
In the remainder of this document we refer to a *value node* to mean the `TypeOperation` node in the graph associated to an `llvm::Value`; we refer to a *operand node* to mean the `TypeOperation` node in the graph associated to an `llvm::Use`.
Most instructions and all their operands generate simple a single *propagate* node, associated both with the instruction value and all it's operands' uses, propagating type information without any change among all of them.
They are connected both via *operand edges* and via *use edges* with the nodes associated to their operands' `Value`s.
The [per-opcode specification](#Per-opcode-specification) lists exhaustively the exceptions, and how operands that are not instructions are handled.
It includes a description of the edges that connect the generated nodes with other nodes.
### Transfer functions
Consider a `TypeOperation` node `T`.
The transfer function $f_{\texttt{T}}$ is a monotonic function from the lattice of `model::Type` to itself.
Given `S` an input lattice element we define $f_{\texttt{T}}(\texttt{S})$ as follows.
* *produce*
The type parameter `T.Type` represents the fixed type that is produced by this operation.
$f_{\texttt{T}}$ is the constant function equal to `T.Type`.
This is monotonic by construction, because it's constant.
* *take address*
$f_{\texttt{T}}$ adds a pointer to `S`.
This is monotonic by construction because adding a pointer is monotonic.
* *dereference*
* If `S` is less than `void *`, it's well defined what removing a pointer from `S` means. $f_{\texttt{T}}$ removes a pointer from `S`.
In both cases, if the result is not a scalar type, $f_{\texttt{T}}$ returns `generic`.
* Otherwise $f_{\texttt{T}}$ is constant returing `generic`.
This is monotonic by construction because removing a pointer is monotonic. Constant `generic` is also monotonic.
The only other case is when we have `x` $\sqsubseteq$ `y` and `x` $\sqsubseteq$ `void *` but `y` $\not\sqsubseteq$ `void *`. In that case $f_{\texttt{T}}(\texttt{y})$ is `generic` which is $\top$, so it's always true that $f_{\texttt{T}}(\texttt{x})$ $\sqsubseteq$ `generic` and monotonicity is proven.
* *extend*
It acts as *require* with `T.Type` set to `pointer_or_number`.
It then extends the result to `T.Size`.
* *truncate*
It acts as *require* with `T.Type` set to `pointer_or_number`.
It then shrinks the result to `T.Size`.
* *propagate*
* identity function
* *require*
given the type parameter `T.Type`
* if `T.Type` is comparable with `S`, $f_{\texttt{T}}$ is the identity function
* otherwise it returns `T.Type` joined with `S`
this is monotonic by construction.
### Per-opcode specification
This section describes, for each opcode family the following information, which nodes are created for the instruction and its operands.
The list is exhaustive: anything that is not listed here is handled as described in [all other instructions](#All-other-instructions), at the end of the section.
Each opcode family comes with a small graph, showing the nodes created for an example instruction:
* the nodes inside the dashed box are the ones created for the instruction, and the first line of each of them reports its kind name and its kind;
* the small dashed nodes outside the box are the nodes of other values, created elsewhere. For simplicity, they are assumed to be *propagate* nodes, so that all the edges that could be created (see [Edges](#Graph-initialization)) are shown.
---
#### `llvm::Argument`
For each `llvm::Argument` of the function we're analyzing, we create a *require* node with `Type` parameter equal to the `model::Type` of the associated argument of the `model::Function`.
```graphviz
digraph {
label="llvm::Argument: %arg"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_arg {
label=""; style="rounded,dashed"
arg [label="{Kind: Require|Type: argument's model type|Size: \{\}|Value: %arg|Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
argusers [label="users of %arg"]
arg -> argusers [label=" use "]
argusers -> arg [label=" operand"]
}
```
---
#### `llvm::GlobalVariable`
For each instruction operand that is a `llvm::GlobalVariable`, we create a *produce* node with `Type` parameter set to a pointer to the type of the associated `model::Segment`.
```graphviz
digraph {
label="llvm::GlobalVariable: @g"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_arg {
label=""; style="rounded,dashed"
arg [label="{Kind: Produce|Type: pointer to the segment's model type|Size: \{\}|Value: @g|Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
argusers [label="users of @g in this function"]
arg -> argusers [label=" use "]
}
```
---
#### `llvm::Function`
For each instruction operand that is a `llvm::Function`, we create a *produce* node with `Type` parameter set to a pointer to the type of the associated `model::Function` or `model::DynamicFunction`.
```graphviz
digraph {
label="llvm::Function: @f"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_arg {
label=""; style="rounded,dashed"
arg [label="{Kind: Produce|Type: pointer to the functions's model type|Size: \{\}|Value: @f|Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
argusers [label="users of @f in this function"]
arg -> argusers [label=" use "]
}
```
---
#### Other non-instruction operands
There is no need to create nodes for `llvm::Constant`s nor for block addresses, nor for any other non-instruction operand.
---
#### `add`/`sub`/`mul`/`and`/`or`/`xor`/`udiv`/`urem`/`sdiv`/`srem`
Each of these instruction generate a single *require* node, together with all of its operands.
The `Type` parameter changes depends on the opcode:
* `add`/`sub`/`mul`: weak `number`
* `and`/`or`/`xor`: weak `number`
* `udiv`/`urem`: weak `unsigned`
* `sdiv`/`srem`: weak `signed`
The picture shows an example for `add`
```graphviz
digraph {
label="%x = add i64 %y, %z"; labelloc=t
edge [fontsize=10]
node [shape=record]
subgraph cluster_i {
label=""; style="rounded,dashed"
x [label="{Kind: Require|Type: number|Size: \{\}|Value: %x|Operands: \{%y (op 0), %z (op 1)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; y [label="%y"]; z [label="%z"] }
users [label="users of %x"]
y -> x [label=" use"]
z -> x [label=" use"]
x -> y [label=" operand"]
x -> z [label=" operand"]
x -> users [label=" use"]
users -> x [label=" operand"]
}
```
---
#### `shl`/`lshr`/`ashr`
The second operand, i.e. the shift amount generates a *produce node*, with `Type` parameter set to `unsigned`.
The `Value` for the shift and the first operand, together, generate a *require node*, `Type` parameter set to:
* weak `number` for `shl`
* weak `unsigned` for `lshr`
* weak `signed` for `ashr`
```graphviz
digraph {
label="%x = lshr i64 %y, %n"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
x [label="{Kind: Require|Type: unsigned|Size: \{\}|Value: %x|Operands: \{%y (op 0)\}}"]
amount [label="{Kind: Produce|Type: unsigned|Size: \{\}|Value: nullptr|Operands: \{%y (op 1)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; y [label="%y"]; n [label="%n"] }
users [label="users of %x"]
y -> x [label=" use"]
x -> y [label=" operand"]
x -> users [label=" use"]
users -> x [label=" operand"]
amount -> n [label=" operand"]
}
```
---
#### `sext`/`zext`
The `Value` of each of these instructions generates a single *require* node, with `Type` parameter set to weak `signed`/`unsigned`, respectively.
The operand generates two different nodes:
* an *extend* node, with `Type` parameter set to empty, and `Size` parameter set to the extended size.
This connects the node generated by the operand's value, with the node of the `sext`/`zext` value.
* a *truncate* node, with `Type` parameter set to empty, and `Size` parameter set to the truncated size.
This connects the node associated with the `sext`/`zext` value with the ode generated by the operand's value.
```graphviz
digraph {
label="%x = sext i32 %y to i64"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
trunc [label="{Kind: Truncate|Type: empty|Size: 32|Value: null|Operands \{\}}"]
extend [label="{Kind: Extend|Type: empty|Size: 64|Value: null|Operands \{\}}"]
x [label="{Kind: Require|Type: signed|Size: \{\}|Value: %x|Operands \{\}}"]
{ rank=same; trunc, extend}
}
node [shape=box, style="rounded,dashed"]
{ rank=source; y [label="%y"] }
{ rank=sink; users [label="%y"] }
users [label="users of %x"]
y -> extend
extend -> x
x -> trunc
trunc -> y
x -> users [label=" use"]
}
```
---
#### `trunc`
The `Value` generates a single *require* node, with `Type` parameter set to weak `pointer_or_number`.
The operand generates two different nodes:
* a *extend* node, with `Type` parameter set to empty, and `Size` parameter set to the extended size.
This connects the node associated with the `sext`/`zext` value with the ode generated by the operand's value.
* a *truncate* node, with `Type` parameter set to empty, and `Size` parameter set to the truncated size.
This connects the node generated by the operand's value, with the node of the `sext`/`zext` value.
```graphviz
digraph {
label="%x = trunc i64 %y to i32"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
trunc [label="{Kind: Truncate|Type: empty|Size: 32|Value: null|Operands \{\}}"]
extend [label="{Kind: Extend|Type: empty|Size: 64|Value: null|Operands \{\}}"]
x [label="{Kind: Propagate|Type: empty|Size: \{\}|Value: %x|Operands \{\}}"]
{ rank=same; trunc, extend}
}
node [shape=box, style="rounded,dashed"]
{ rank=source; y [label="%y"] }
{ rank=sink; users [label="%y"] }
users [label="users of %x"]
x -> extend
extend -> y
y -> trunc
trunc -> x
x -> users [label=" use"]
}
```
---
#### `icmp`
The result of the `icmp` always generates a *produce* node on its own, with `Type` parameter set to weak `signed`.
The operands of the comparison, generate one individual node together.
* `eq`/`ne`: generate a *propagate* node.
* all the others: generate a *require* node.
Its `Type` parameter depends on the opcode of the comparison.
* `sgt`/`slt`/`sge`/`sle`: weak `signed`
* `ugt`/`ult`/`uge`/`ule`: weak `unsigned`
```graphviz
digraph {
label="%c = icmp slt i64 %a, %b"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
c [label="{Kind: Produce|Type: signed|Size: \{\}|Value: %c|Operands: \{\}}"]
operands [label="{Kind: Require|Type: signed|Size: \{\}|Value: nullptr|Operands: \{%a (op 0), %b (op 1)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; a [label="%a"]; b [label="%b"] }
users [label="users of %c"]
a -> operands [label=" use"]
b -> operands [label=" use"]
operands -> a [label=" operand"]
operands -> b [label=" operand"]
c -> users [label=" use"]
}
```
---
#### `select`
Operand 0, i.e. the controlling condition, generates a *produce node*, with `Type` parameter set to weak `uint8_t`.
It is treated like the condition operand of `br`/`brcond` later.
:::danger
* [name=fez] TODO: we should write a remark somewhere that all the `i1` get `uint8_t`.
* [name=fez] TODO: should this be *require* `uint8_t` instead?
:::
The `Value` for the `select` and the other two operands generate, together, a single *propagate* node.
```graphviz
digraph {
label="%x = select i1 %c, i64 %y, i64 %z"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
condition [label="{Kind: Produce|Type: uint8_t|Size: \{\}|Value: null|Operands: \{%c (op 0)\}}"]
x [label="{Kind: Propagate|Type: empty|Size: \{\}|Value: %x|Operands: \{%y (op 1), %z (op 2)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; c [label="%c"]; y [label="%y"]; z [label="%z"] }
users [label="users of %x"]
condition -> c [style=dashed, label=" operand"]
y -> x [label=" use"]
z -> x [label=" use"]
x -> y [label=" operand"]
x -> z [label=" operand"]
x -> users [label=" use"]
users -> x [label=" operand"]
}
```
---
#### `br`/`brcond`
Only the condition operand matters.
It generates a *produce node*, with `Type` parameter set to weak `uint8_t`.
:::danger
* [name=fez] TODO: we should write a remark somewhere that all the `i1` get `uint8_t`.
* [name=fez] TODO: should this be *require* `uint8_t` instead?
:::
```graphviz
digraph {
label="br i1 %c, label %t, label %f"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
condition [label="{Kind: Produce|Type: uint8_t|Size: \{\}|Value: null|Operands: \{%c (op 0)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; c [label="%c"] }
condition -> c [label=" operand"]
}
```
---
#### `switch`
Only the condition operand matters.
It generates a *produce node*, with `Type` parameter set to weak `pointer_or_number` if the condition size is larger or equal to a pointer size in the model, `number` otherwise.
:::danger
* [name=fez] TODO: should this be a *require* node instead?
:::
```graphviz
digraph {
label="switch i64 %v, label %default [ ... ]"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
condition [label="{Kind: Produce|Type: pointer_or_number64_t|Size: \{\}|Value: null|Operands: \{%v (op 0)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; v [label="%v"] }
condition -> v [label=" operand"]
}
```
---
#### `alloca`
Can be treated like [global variables](#llvmGlobalVariable).
They generate a *produce* node, with `Type` parameter set to a pointer.
The pointee varies:
* for `alloca`s representing the stack frame, the pointee is the `model::Type` of the stack frame of the current function
* for other `alloca`s the pointee it `void`
```graphviz
digraph {
label="%p = alloca i64"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
p [label="{Kind: Produce|Type: void *|Size: \{\}|Value: %p | Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
users [label="users of %p"]
p -> users [label=" use"]
}
```
---
#### `load`
The `Value` of the `load` generates a single *propagate* node.
The pointer operand generates two different nodes:
* a *dereference* node, with `Type` parameter set to empty
This connects the node associated with the pointer operand's value, with the node generated by the `load` `Value`
* a *take address* node, with `Type` parameter set to empty
This connects the node generated by the `load` `Value`, with the node associated with the pointer operand's value
```graphviz
digraph {
label="%x = load i64, ptr %p"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
address [label="{Kind: TakeAddress|Type: empty|Size: \{\}|Value: null|Operands \{(%p, 0)\}}"]
dereference [label="{Kind: Dereference|Type: empty|Size: \{\}|Value: null|Operands \{(%p, 0)\}}"]
x [label="{Kind: Propagate|Type: empty|Size: \{\}|Value: %x|Operands \{\}}"]
{ rank=same; address, dereference}
}
node [shape=box, style="rounded,dashed"]
{ rank=source; p [label="%p"] }
{ rank=sink; users [label="%p"] }
users [label="users of %x"]
p -> dereference
dereference -> x
x -> address
address -> p
x -> users [label=" use"]
}
```
---
#### `store`
The pointer operand generates two different nodes:
* a *dereference* node, with `Type` parameter set to empty
This connects the node associated with the pointer operand's `Value`, with the node generated by the value operand's `Value`.
* a *take address* node, with `Type` parameter set to empty
This connects the node associated with the value operand's `Value`, with the node generated by the pointer operand's `Value`.
```graphviz
digraph {
label="store i64 %x, ptr %p"; labelloc=t
edge [fontsize=10]
node [shape=box, style="rounded,dashed"]
{ rank=source; p, x}
p [label="%p"]
x [label="%x"]
node [shape=record,style=solid]
subgraph cluster_i {
label=""; style="rounded,dashed"
address [label="{Kind: TakeAddress|Type: empty|Size: \{\}|Value: null|Operands \{(%p, 0)\}}"]
dereference [label="{Kind: Dereference|Type: empty|Size: \{\}|Value: null|Operands \{(%p, 0)\}}"]
{ rank=same; address, dereference}
}
p -> dereference
dereference -> x
x -> address
address -> p
}
```
---
#### `inttoptr`/`ptrtoint`
Each of `inttoptr` and `ptrtoint` generates a single *require* node, together with their operand, with `Type` parameter set to weak `void *`.
```graphviz
digraph {
label="%p = inttoptr i64 %x to ptr"; labelloc=t
edge [fontsize=10]
node [shape=record,style=solid]
subgraph cluster_i {
label=""; style="rounded,dashed"
p [label="{Kind: Require|Type: void*|Size: \{\}|Value: %p|Operands \{(%x, 0)\}}"]
}
node [shape=box, style="rounded,dashed"]
x[label="%x"]
users[label="users of %p"]
{ rank=source; x}
{ rank=sink; users}
x -> p [label=" use"]
p -> x [label=" operand"]
p -> users [label=" use"]
users -> p [label=" operand"]
}
```
---
#### `getelementptr`
There should be none.
---
#### `call`
The `Value` of the call generates a *produce* node, with `Type` equal to the model return type of the call site prototype.
The callee operand, if it's not an `llvm::Function` (already handled above), generates a *produce* node with `Type` set to a pointer type, whose pointee is the call site prototype of the callee.
Each argument operand generates a *produce* node with `Type` set to the associated argument type on the model.
The only exceptions are calls that call
* calls to `OpaqueExtractValue` that should be handled as `extractvalue` (see below).
* calls to `struct_initializer` that should be handled separately (see below).
Notice that all the nodes produced here are *produce* nodes, because when analyzing a function, the types of the callees are not part of what is being analyzed, and are considered fixed and given.
```graphviz
digraph {
label="%r = call i64 %callee(i64 %a)"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
calleeop [label="{Kind: Produce|Type: pointer to model callee type|Size: \{\}|Value: null| Operands: \{(%callee, 0)\}}"]
aop [label="{Kind: Produce|Type: argument type on the model|Size: \{\}|Value: null| Operands: \{(%a, 0)\}}"]
r [label="{Kind: Produce|Type: return type on the model|Size: \{\}|Value: %r| Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; callee [label="%callee"]; a [label="%a"] }
users [label="users of %r"]
calleeop -> callee [label=" operand"]
aop -> a [label=" operand"]
r -> users [label=" use"]
}
```
---
#### `extractvalue`/call to `OpaqueExtractValue`
This should only ever happen when the value we extract from is a call whose callee prototype is raw, and returns a register set.
Assert that this is the case.
The `Value` of the call just generates a *produce* node, with `Type` parameter set to the model type of the register associated with extracted value.
```graphviz
digraph {
label="%x = extractvalue %RegisterSet %r, 1"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
x [label="{Kind: Produce|Type: model return type for register 1 in RegisterSet|Size: \{\}|Value: %x| Operands: \{\}}"]
}
node [shape=box, style="rounded,dashed"]
users [label="users of %x"]
x -> users [label=" use"]
}
```
---
#### `call` to `struct_initializer`
This only ever happens inside raw functions returning register set. Assert this.
Each argument operand should be treated as the operand of a `ret` (see below), i.e. it generates a *require* on its own, with `Type` set to the model type of the associated return register.
```graphviz
digraph {
label="%s = call %RegisterSet @struct_initializer(i64 %a, i64 %b)"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
arg0 [label="{Kind: Require|Type: type of a's return register|Size: \{\}|Value: null| Operands \{(%a, 0)\}}"]
arg1 [label="{Kind: Require|Type: type of b's return register|Size: \{\}|Value: null| Operands \{(%b, 0)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; a [label="%a"]; b [label="%b"] }
arg0 -> a [label=" operand"]
arg1 -> b [label=" operand"]
}
```
---
#### `ret`
The returned operand generates a *require* on its own, with `Type` set to the model type of the associated return register.
```graphviz
digraph {
label="ret i64 %v"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
returned [label="{Kind: Require|Type: type of the return register|Size: \{\}|Value: null| Operands \{(%v, 0)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; v [label="%v"] }
returned -> v [style=dashed, label=" operand"]
}
```
---
#### `insertvalue`
This should never happen. Assert that it doesn't.
---
#### All other instructions
All the instructions that are not listed above (e.g., `phi`) generate a single *propagate* node, associated to the instruction itself and all its operands that are not block addresses.
```graphviz
digraph {
label="%x = phi i64 [ %y, %bb1 ], [ %z, %bb2 ]"; labelloc=t
node [shape=record]
edge [fontsize=10]
subgraph cluster_i {
label=""; style="rounded,dashed"
x [label="{Kind: Propagate|Type: empty|Size: \{\}|Value: %x| Operands \{(%y, 0), (%z, 1)\}}"]
}
node [shape=box, style="rounded,dashed"]
{ rank=source; y [label="%y"]; z [label="%z"] }
users [label="users of %x"]
y -> x [label=" use"]
z -> x [label=" use"]
x -> y [style=dashed, label=" operand"]
x -> z [style=dashed, label=" operand"]
x -> users [label=" use"]
users -> x [style=dashed, label=" operand"]
}
```
## Tests
* Unit test the lattice
* Test how the analysis works on an individual function, with lit and FileCheck
* Test how the analysis works interprocedurally in a simple tree-like call graph
* Test how the analysis works interprocedurally in a DAG-like call graph
* Test how the analysis works interprocedurally in a call graph with recursion
For all these cases, explicitly remember to also test pure forwarding across both arguments and return types.
## Discarded designs
* Using the use-def or a dataflow graph instead of the type-flow graph
* The use-def graph requires edge-wise transfer functions.
* The dataflow graph can't represent flow of types from an operand to another.
* Using a full blown graph with a node for each use and a node for each user
* This grows the size of the graph unnecessarily, given that in most cases operand uses can be collapsed with the user.
* The current design is the compact representation of this full blown graph.
## Non Goals
* **Referring to the old VMA**
The old VMA we used to have in revng is not a design we should inspire this work. It was a different analysis.
Everything in this REP is derived from REP72's framing and from the code as it stands.
* **Reasoning about pointees**
VMA should never try to reason about pointee types of pointers, or across memory accesses. That will be possible in the final design as explained in REP73, but only thanks to the fact that we run it at fixed point with MAA.
* **Reasoning about sizes**
VMA should never try to reason about or to change the size of scalars. That's the role of URSA (Used Register Size Analysis), which is expected to run right before VMA.
* **Running VMA and DLA at fixed point**
* **Soft-float helpers.**
* **Cast minimization**
Cast minimization is a job for *type refinement* in Clift.
Here we can't really reason about minimizing casts.
The goal of VMA is just to provide better looking refined types to DLA and let it propagate them.
* **Booleans**
`i1` can be entirely ignored by VMA, since there isn't much it can say about them except they're boolean
* **Non scalar types**
## Roadmap
* [ ] 1. Bring up the intra-procedural dataflow graph with `GenericGraph`
* [ ] 2. Implement the transfer functions and MFP
* [ ] 3. Implement the interprocedural propagation via post-order visit on the call graph. This computes a final `std::map<llvm::Value *, model::Type>`.
* [ ] 4. Implement a standalone `pypeline` analysis, that reads LLMV IR, the model, materializes the graph, runs MFP, modifies the model. This is an analysis separate from DLA, used for unit testing. The computed map is still unused.
* [ ] 5. Run the standalone analysis as initial step of DLA, without. This reduces invalidation. Full DLA integration using the computed map (as explained in [REP90](https://pad.rev.ng/jEDFbwz_RNi2K8sTWxChbw)) is **out of scope**.
* [ ] 6. Integrate with URPA ([REP83](https://pad.rev.ng/3mdtFDxlTGuneX3V75fjwA))
* [ ] 7. Integrate with DLA ([REP90](https://pad.rev.ng/jEDFbwz_RNi2K8sTWxChbw))
* [ ] 8. Adopt full fledged interprocedural propagation via [REP88](https://pad.rev.ng/vIsgFC6WTUip0DcXkoTX8g)