MATLAB: Does the generated code incorporate inefficient bit shifting operations in Real-Time Workshop Embedded Coder 5.0.1 (R2007b+)

bitshiftbitshiftingEmbedded Coderleftoptimizationoptimizeright

I noticed that when multiplying a signal by a power of 2 (via a Gain block), the generated code shows:
(val << 14) >> 12
instead of:
val << 2
To reproduce the issue, generate code for model, mux_to_array.mdl, found in the attachments. The generated code has the following line:
mux_to_array_Y.Out1 = (int16_T)((((mux_to_array_U.In1 << 2U) << 14) >> 13) * 3);

Best Answer

The generated code is not incorrect. Notice the following comments in the generated code:
96 /* Outport: '<Root>/Out 1' incorporates:
97 * Gain: '<Root>/Gain 1'
98 * Gain: '<Root>/Gain 2'
99 * Gain: '<Root>/Gain 5'
100 * Gain: '<Root>/Gain 6'
101 * Inport: '<Root>/In 1'
102 * SignalConversion: '<Root>/TmpHiddenBufferAtGain 1Inport1'
103 */
104 mux_to_array_Y.Out1 = (int16_T)((((mux_to_array_U.In1 << 2U) << 14) >> 13) *
105 3);
Each gain is an operation y = fn(u). These functions are being folded to make one line of code equivalent to
y = f1(f2(f3(f4(u))))
Hence the reason for the behavior observed. Most likely, the shift operations will be optimized in the C compiler anyway.
This expression folding of gains has, however, been enhanced in R2008a. So in R2008a and later releases, the generated code appears as follows:
mux_to_array_Y.Out1 = (int16_T)((mux_to_array_U.In1 << 3U) * 3);