The accelerometer gives you the roll and pitch angles (rotations around X and Y axes) because it can see the gravity vector. Note that this can be done in stationary condition when no additional linear acceleration is present). See design tip DT0058 for more details on the formulas to be utilized.
The magnetometer gives you the yaw angle (rotation around Z axis) because it can see the earth magnetic field. Note that the magnetic north is not the same as the geographic north. One has to add the 'magnetic declination' angle to go from the yaw (angle with respect to magnetic north) to heading (angle with respect to geographic north). Also note that magnetometers can only be utilized after calibrating out the spurious offset, also known as hard-iron effect (see DT0059 and MotionMC in X-Cube-MEMS for more information on this). Finally, you need to compensate for the roll and pitch of the magnetometer to be able to compute the yaw. Again, see DT0058 for more details.
MotionEC in X-Cube-MEMS performs the acc+mag fusion to give you roll, pitch, and yaw angles (it is more sophisticated than what is shown in DT0058).
The gyroscope gives you the angular rotation, therefore if you already have an estimate for the orientation (roll, pitch, yaw) you can update the estimate and compute the new orientation. See DT0060 for more details. Note that you need to calibrate out the spurious offset, also known as gyro bias.The gyroscope is the only sensor in the system that is always available irrespective of external interferences, while the accelerometer is unavailable when there is highly dynamic motion, and the magnetometer is unavailable when there are magnetic interferences.
MotionFX in X-Cube-MEMS performs acc+gyro or acc+gyro+mag fusion to give you roll, pitch, and yaw angles. The yaw is absolute when mag is present, and relative when there is no mag.