Optimize Performance of Memory Access by Using Data Alignment - MATLAB & Simulink (original) (raw)

This example shows how to specify the data alignment requirements for data objects such asSimulink.Parameter, Simulink.Signal, andSimulink.Bus objects. To instruct the compiler to align data objects on specific boundaries in memory, configure your data for data alignment. Data alignment can improve the performance of memory access for some target processors and is sometimes required for the code to execute.

For information about specifying data alignment for a code replacement entry, see Data Alignment for Code Replacement.

For information about specifying data alignment for MATLAB® code, see coder.dataAlignment.

Specify Data Alignment Requirements for Data Objects

To specify the alignment boundary of a data object, set the Alignment property by using one of these methods:

Data objects that support data alignment specification include:

Once you specify the data alignment boundaries for your data objects, provide the data alignment specification for the compiler by using a code replacement library. You do not need to specify code replacements in the library.

Provide Data Alignment Specification for Compilers

To support data alignment in generated code, describe the data alignment capabilities and syntax for your compilers in the code replacement library registration. Provide one or more alignment specifications for each compiler in a library registry entry.

as.AlignmentSyntaxTemplate = 'attribute((aligned(%n)))';
as.AlignmentPosition = 'DATA_ALIGNMENT_PREDIRECTIVE';
as.SupportedLanguages = {'c', 'c++'};
da.addAlignmentSpecification(as);
tc = RTW.TargetCharacteristics;
tc.DataAlignment = da;
The RTW.DataAlignment object also has the propertyDefaultMallocAlignment, which specifies the default alignment boundary, in bytes, that the compiler uses for dynamically allocated memory. If the code generator uses dynamic memory allocation for a data object involved in a code replacement, this value determines if the memory satisfies the alignment requirement of the replacement. If not, the code generator does not use the replacement. The default value forDefaultMallocAlignment is-1, indicating that the default alignment boundary used for dynamically allocated memory is unknown. In this case, the code generator uses the natural alignment of the data type to determine whether to allow a replacement.
Additionally, you can specify the alignment boundary for complex types by using the addComplexTypeAlignment function.

For each data alignment specification, provide this information.

AlignmentSpecification Property Dialog Box Parameter Description
AlignmentType Alignment type Cell array of predefined enumerated strings specifying the types of alignment this specification supports.DATA_ALIGNMENT_LOCAL_VAR — Local variablesDATA_ALIGNMENT_GLOBAL_VAR — Global variablesDATA_ALIGNMENT_STRUCT_FIELD — Individual structure fieldsDATA_ALIGNMENT_WHOLE_STRUCT — Whole structure, with padding (individual structure field alignment, if specified, is favored by the code generator and takes precedence over whole structure alignment)Each alignment specification must specify at leastDATA_ALIGNMENT_GLOBAL_VAR andDATA_ALIGNMENT_STRUCT_FIELD.
AlignmentPosition Alignment position Predefined enumerated string specifying the position in which you must place the compiler alignment directive for the alignment typeDATA_ALIGNMENT_WHOLE_STRUCT:DATA_ALIGNMENT_PREDIRECTIVE — The alignment directive is emitted beforestruct st_tag{…} as part of the type definition statement (for example, MSVC).DATA_ALIGNMENT_POSTDIRECTIVE — The alignment directive is emitted afterstruct st_tag{…} as part of the type definition statement (for example, gcc).DATA_ALIGNMENT_PRECEDING_STATEMENT — The alignment directive is emitted as a standalone statement immediately preceding the definition of the structure type. A semicolon (;) terminates the registered alignment syntax.DATA_ALIGNMENT_FOLLOWING_STATEMENT — The alignment directive is emitted as a standalone statement immediately following the definition of the structure type. A semicolon (;) terminates the registered alignment syntax.For alignment types other thanDATA_ALIGNMENT_WHOLE_STRUCT, code generation uses the alignment positionDATA_ALIGNMENT_PREDIRECTIVE.
AlignmentSyntaxTemplate Alignment syntax Specify the alignment directive string that the compiler supports. The string is registered as a syntax template that has placeholders in it. These placeholders are supported:%n — Replaced by the alignment boundary for the replacement function argument.%s — Replaced by the aligned symbol, usually the identifier of a variable.For example, for the gcc compiler, you can specify__attribute__((aligned(%n))), or for the MSVC compiler,__declspec(align(%n)).
SupportedLanguages Supported languages Cell array specifying the languages to which this alignment specification applies, among c andc++. Sometimes, alignment syntax and position differ between languages for a compiler.

Align Data for a Data Object Programmatically

This example shows how to specify the data alignment for twoSimulink.Bus objects.

  1. Open the example model PreserveBusDims. This model uses twoSimulink.Bus objects stored in the base workspace.
    openExample("PreserveBusDims")
    The model contains two bus ports, which resolve to Simulink.Bus objects in the base workspace.
  2. Set the data alignment for the data objects. For this example, set the alignment for the bus objects ImperialSpecs and MetricSpecs to 64.
    ImperialSpecs.Alignment = 64;
    MetricSpecs.Alignment = 64;
  3. Create and save the following code replacement table definition file,crl_table_align.m. You use this table because data alignment compiler specification requires that you register a code replacement library. The table does not contain code replacement entries, it only specifies the compiler information needed for data alignment.
    function hLib = crl_table_align
    hLib = RTW.TflTable;
  4. Create and save the following registration file, rtwTargetInfo.m. If you want to compile the code generated in this example, first modify theAlignmentSyntaxTemplate property for the compiler that you use. For example, for the MSVC compiler, replace the gcc template specification__attribute__((aligned(%n))) with__declspec(align(%n)).
    function rtwTargetInfo(cm)
    % rtwTargetInfo function to register a code replacement library (CRL)
    % for use with code generation
    % Register the CRL defined in local function locCrlRegFcn
    cm.registerTargetInfo(@locCrlRegFcn);
    end % End of RTWTARGETINFO
    % Local function to define a CRL containing crl_table_align
    function thisCrl = locCrlRegFcn
    % Create an alignment specification object, assume gcc
    as = RTW.AlignmentSpecification;
    as.AlignmentType = {'DATA_ALIGNMENT_LOCAL_VAR', ...
    'DATA_ALIGNMENT_GLOBAL_VAR', ...
    'DATA_ALIGNMENT_STRUCT_FIELD'};

as.AlignmentSyntaxTemplate = 'attribute((aligned(%n)))';
as.SupportedLanguages={'c', 'c++'};
% Add the alignment specification object
da = RTW.DataAlignment;
da.addAlignmentSpecification(as);
% Add the data alignment object to target characteristics
tc = RTW.TargetCharacteristics;
tc.DataAlignment = da;
% Instantiate a CRL registry entry
thisCrl = RTW.TflRegistry;
% Define the CRL properties
thisCrl.Name = 'Data Alignment Example';
thisCrl.Description = 'Example of replacement with data alignment';
thisCrl.TableList = {'crl_table_align'};
thisCrl.TargetCharacteristics = tc;
end % End of LOCCRLREGFCN 5. To register your library with the code generator, enter this command.
RTW.TargetRegistry.getInstance('reset'); 6. Configure the model to use your code replacement library.
set_param("PreserveBusDims","CodeReplacementLibrary","Data Alignment Example"); 7. Generate code for the model.
slbuild("PreserveBusDims"); 8. Check that the generated code aligns the data by using the alignment syntax that you specified. For this example, PreserveBusDims.h contains this code.

#ifndef DEFINED_TYPEDEF_FOR_MetricSpecs_  
#define DEFINED_TYPEDEF_FOR_MetricSpecs_  
typedef struct {  
  __attribute__((aligned(64))) real_T DimensionsInCms[30];  
  __attribute__((aligned(64))) real_T WeightInKilograms[10];  
} MetricSpecs;  
#endif  
#ifndef DEFINED_TYPEDEF_FOR_ImperialSpecs_  
#define DEFINED_TYPEDEF_FOR_ImperialSpecs_  
typedef struct {  
  __attribute__((aligned(64))) real_T DimensionsInInches[30];  
  __attribute__((aligned(64))) real_T WeightInPounds[10];  
} ImperialSpecs;  
#endif  

Align Data for a Data Object Alignment by Using the Editor

Configure Alignment Values for Data Objects

Set the Alignment property of a data object by using the Type Editor.

  1. Open the Type Editor. On the Modeling tab, from theDesign gallery, click Type Editor.
  2. In the Type Editor, set the View toAll.
  3. For the data object that you want to align, set the value in theAlignment column.
    Type Editor for the PreserveBusDims model. The row for the object ImperialSpecs is highlighted. The Alignment column for that row shows a value of 64.
  4. Use the Type Editor to specify the alignment for other data objects that you want to align.

Provide Alignment Specifications in a Code Replacement Library Registration

Describe the data alignment capabilities and syntax for your compilers in the code replacement library registration. You can provide one or more alignment specifications for each compiler in a library registry entry.

  1. Create and save the following code replacement table definition file,data_alignment.m. You use this table because data alignment compiler specification requires that you register a code replacement library. The table does not contain code replacement entries, you use it only to specify the compiler information needed for data alignment.
    function hLib = data_alignment
    hLib = RTW.TflTable;
  2. Open the Code Replacement Tool from the command line with this command:
  3. Register the code replacement library and specify the alignment syntax in the registration. Click Generate Registration File. In the Generate registration file dialog box, specify these parameter settings:
    • Registry nameCRL for Data Alignment
    • Table listdata_alignment
    • Base CRLNone
    • Target HW device*
    • DescriptionExample code replacement library
    • Generate data alignment specification — on
      In the Alignment Specification 1 section, add this alignment information:
    • Alignment type — selectDATA_ALIGNMENT_LOCAL_VAR,DATA_ALIGNMENT_STRUCT_FIELD, andDATA_ALIGNMENT_GLOBAL_VAR.
    • Alignment positionDATA_ALIGNMENT_PREDIRECTIVE
    • Alignment syntax__attribute__((aligned(%n)))
    • Supported languagesc, c++
      Generate registration dialog box showing filled in fields.
      You can optionally add more alignment specifications by clicking the add button. Click OK and save the registration file.

Apply Alignment Specifications to the Model

  1. Register the code replacement library with the code generator by entering this command:
    RTW.TargetRegistry.getInstance('reset');
  2. Configure the model to use the empty code replacement library that you registered. On the Modeling tab, click Settings. Set the model configuration parameter Code replacement libraries toCRL for Data Alignment and click OK. Then close the dialog box.
  3. Generate code for the model. The generated header file contains the alignment directives for the data.

Data Alignment Limitations

When you try to perform data alignment in a case that is not supported:

Data alignment is not supported for:

If the following conditions exist, the code generator includes data alignment directives for root-level I/O variables in the ert_main.c orert_main.cpp file it produces. In this case, if you discard the generated example main program, align used root-level I/O variables correctly. If you choose not to generate an example main program in this case, data alignment is not supported.

If a replacement imposes alignment requirements on the shared utility interface arguments, the code generator does not honor data alignment. Under these conditions, replacement does not occur. Replacement is allowed if the registered data alignment type specification supports alignment of local variables, and the replacement involves only local variables.

For Simulink.Bus objects:

When you specify alignment for functions that occur in a model reference hierarchy, and multiple models in the hierarchy operate on the same function data, the bottommost model dictates alignment for the rest of the hierarchy. If the alignment requirement for a function in a model higher in the hierarchy cannot be honored due to the alignment set by a model lower in the hierarchy, data alignment is not supported. To work around this issue, if the shared data is represented by a bus or signal object, manually set the alignment property on the shared data by setting the alignment property of theSimulink.Bus or Simulink.Signal object.

Storage Class Limitations

Data that is associated with storage classes supports alignment only under certain conditions. This table shows the built-in storage classes that support data alignment and the required conditions.

Storage Class Conditions
Default None
ExportedGlobal None
ImportedExtern Specify the data alignment by using a data object. Specification by using a code replacement entry is not supported.
ImportedExternPointer Specify the data alignment by using a data object. Specification by using a code replacement entry is not supported.
Volatile None
Const None
ConstVolatile None
ExportToFile None
ImportedFromFile Specify the data alignment by using a data object. Specification by using a code replacement entry is not supported.
Localizable Not supported for root input ports
GetSet Not supported
MultiInstance None
FileScope Not supported when used from an Embedded Coder Dictionary
Struct None
Reusable None
Bitfield Not supported
Define Not supported
ImportedDefine Specify the data alignment by using a data object. Specification by using a code replacement entry is not supported.
CompilerFlag Specify the data alignment by using a data object. Specification by using a code replacement entry is not supported.

For storage classes that you create by using the Embedded Coder Dictionary or the Custom Storage Class Designer, data alignment is not supported if the storage class has:

See Also

Topics