Vector addition with RISC-V RVV

Writing a small vector addition program for RISC-V RVV in C.

RISC-V RVV extensions allow you to manipulate vectors in various ways. In this C program we set up three arrays: a, b and c. a and b contain the vectors we wish to add and c will receive the result.

We set the vector size we want to work with, then load the vectors a and b from memory in to the RISC-V vector registers. We then perform the addition and write the result bac to vector c and then print this answer to the terminal.


#include <stdio.h>
#include <riscv_vector.h>

int main() {
    // Initialize two small vectors and a result vector
    int16_t a[] = {1, 2, 3, 4};
    int16_t b[] = {5, 6, 7, 8};
    int16_t c[4]; // Result vector

    // Set the vector length to the maximum supported
    // for 16-bit elements in m1 mode
    size_t vl = vsetvlmax_e16m1();

    // Load vectors from memory
    vint16m1_t va = vle16_v_i16m1(a, vl);
    vint16m1_t vb = vle16_v_i16m1(b, vl);

    // Perform vector addition
    vint16m1_t vc = vadd_vv_i16m1(va, vb, vl);

    // Store the result back to the C array
    vse16_v_i16m1(c, vc, vl);

    // Print the results
    for(int i = 0; i < 4; i++) {
        printf("%d ", c[i]);

    return 0;

Compile and Run

me@pioneer:gcc -o vecadd vecadd.c
6 8 10 12

Mission Accomplished

And there we have it, you have managed to do a vector addition of two 4 element arrays.