Main Content

Data Alignment for Code Replacement

Code replacement libraries can align data objects passed into a replacement function to a specified boundary.

Code Replacement Data Alignment

You can take advantage of function implementations that require aligned data to optimize application performance. To configure data alignment for a function implementation:

  1. 指定数据对齐需求在一个代码replacement entry. Specify alignment separately for each implementation function argument or collectively for all function arguments. SeeSpecify Data Alignment Requirements for Function Arguments.

  2. Specify the data alignment capabilities and syntax for one or more compilers. Include the alignment specifications in a library registration entry in thertwTargetInfo.mfile. SeeProvide Data Alignment Specifications for Compilers.

  3. Register the library containing the table entry and alignment specification object.

  4. Configure the code generator to use the code replacement library and generate code. Observe the results.

For examples, seeBasic Example of Code Replacement Data Alignmentand the “Data Alignment for Function Implementations” section of theOptimize Generated Code by Developing and Using Code Replacement Libraries - Simulinkexample page.

Specify Data Alignment Requirements for Function Arguments

To specify the data alignment requirement for an argument in a code replacement entry:

  • If you are defining a replacement function in a code replacement table registration file, create an argument descriptor object (RTW.ArgumentDescriptor). Use itsAlignmentBoundaryproperty to specify the required alignment boundary and assign the object to the argumentDescriptorproperty.

  • If you are defining a replacement function using theCode Replacement Tool, on theMapping Informationtab, in theArgument propertiessection for the replacement function, enter a value for theAlignment valueparameter.

TheAlignmentBoundaryproperty (orAlignment valueparameter) specifies the alignment boundary for data passed to a function argument, in number of bytes. TheAlignmentBoundaryproperty is valid only for addressable objects, including matrix and pointer arguments. It is not applicable for value arguments. Valid values are:

  • -1(default) — If the data is aSimulink.Bus,Simulink.Signal, orSimulink.Parameterobject, specifies that the code generator determines an optimal alignment based on usage. Otherwise, specifies that there is not an alignment requirement for this argument.

  • Positive integer that is a power of 2, not exceeding 128 — Specifies number of bytes in the boundary. The starting memory address for the data allocated for the function argument is a multiple of the specified value. If you specify an alignment boundary that is less than the natural alignment of the argument data type, the alignment directive is emitted in the generated code. However, the target compiler ignores the directive.

The following code specifies theAlignmentBoundaryfor an argument as 16 bytes.

hLib = RTW.TflTable; entry = RTW.TflCOperationEntry; arg = getTflArgFromString(hLib,'u1','single*'); desc = RTW.ArgumentDescriptor; desc.AlignmentBoundary = 16; arg.Descriptor = desc; entry.Implementation.addArgument(arg);

The equivalent alignment boundary specification in the Code Replacement Tool dialog box is in this figure.

Note

If your model importsSimulink.Bus,Simulink.Parameter, orSimulink.Signalobjects, specify an alignment boundary in the object properties, using theAlignmentproperty. For more information, seeSimulink.Bus,Simulink.Parameter, andSimulink.Signal.

Provide Data Alignment Specifications 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.

To describe the data alignment capabilities and syntax for a compiler:

  • If you are defining a code replacement library registration entry in artwTargetInfo.mcustomization file, add one or moreAlignmentSpecificationobjects to anRTW.DataAlignmentobject. Attach theRTW.DataAlignmentobject to theTargetCharacteristicsobject of the registry entry.

    TheRTW.DataAlignmentobject 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 forDefaultMallocAlignmentis-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 theaddComplexTypeAlignmentfunction.

  • If you are generating a customization file function using the Code Replacement Tool, fill out the following fields for each compiler.

    Click the plus (+) symbol to add additional compiler specifications.

For each data alignment specification, provide the following information.

AlignmentSpecificationProperty

Dialog Box Parameter

Description

AlignmentType

Alignment type

Cell array of predefined enumerated strings, specifying which types of alignment this specification supports.

  • DATA_ALIGNMENT_LOCAL_VAR— Local variables.

  • DATA_ALIGNMENT_GLOBAL_VAR— Global variables.

  • DATA_ALIGNMENT_STRUCT_FIELD— Individual structure fields.

  • DATA_ALIGNMENT_WHOLE_STRUCT— Whole structure, with padding (individual structure field alignment, if specified, is favored and takes precedence over whole structure alignment).

Each alignment specification must specify at leastDATA_ALIGNMENT_GLOBAL_VARandDATA_ALIGNMENT_STRUCT_FIELD.

AlignmentPosition

Alignment position

Predefined enumerated string specifying the position in which you must place the compiler alignment directive for 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——对齐standalo指令发射ne statement immediately preceding the definition of the structure type. A semicolon (;) must terminate the registered alignment syntax.

  • DATA_ALIGNMENT_FOLLOWING_STATEMENT——对齐standalo指令发射ne statement immediately following the definition of the structure type. A semicolon (;) must terminate the registered alignment syntax.

For alignment types other thanDATA_ALIGNMENT_WHOLE_STRUCT, code generation uses alignment positionDATA_ALIGNMENT_PREDIRECTIVE.

AlignmentSyntaxTemplate

Alignment syntax

Specifies 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, amongcandc++. Sometimes alignment syntax and position differ between languages for a compiler.

Here is a data alignment specification for the GCC compiler:

da = RTW.DataAlignment; as = RTW.AlignmentSpecification; as.AlignmentType = {“DATA_ALIGNMENT_LOCAL_VAR',...“DATA_ALIGNMENT_STRUCT_FIELD',...“DATA_ALIGNMENT_GLOBAL_VAR”}; as.AlignmentSyntaxTemplate ='__attribute__((aligned(%n)))'; as.AlignmentPosition =“DATA_ALIGNMENT_PREDIRECTIVE'; as.SupportedLanguages = {'c','c++'}; da.addAlignmentSpecification(as); tc = RTW.TargetCharacteristics; tc.DataAlignment = da;

Here is the corresponding specification in theGenerate customizationdialog box of the Code Replacement Tool.

Basic Example of Code Replacement Data Alignment

A simple example of the complete workflow for data alignment specified for code replacement is:

  1. Create and save the following code replacement table definition file,crl_table_mmul_4x4_single_align.m. This table defines a replacement entry for the * (multiplication) operator, thesingledata type, and input dimensions[4,4]. The entry also specifies a data alignment boundary of 16 bytes for each replacement function argument. The entry expresses the requirement that the starting memory address for the data allocated for the function arguments during code generation is a multiple of 16.

    functionhLib = crl_table_mmul_4x4_single_align%CRL_TABLE_MMUL_4x4_SINGLE_ALIGN - Describe matrix operator entry with data alignmenthLib = RTW.TflTable; entry = RTW.TflCOperationEntry; setTflCOperationEntryParameters(entry,...'Key','RTW_OP_MUL',...'Priority', 90,...'ImplementationName','matrix_mul_4x4_s');% conceptual argumentscreateAndAddConceptualArg(entry,'RTW.TflArgMatrix',...'Name','y1',...'IOType','RTW_IO_OUTPUT',...'BaseType','single',...'DimRange', [4 4]); createAndAddConceptualArg(entry,'RTW.TflArgMatrix',...'Name','u1',...'BaseType','single',...'DimRange', [4 4]); createAndAddConceptualArg(entry,'RTW.TflArgMatrix',...'Name','u2',...'BaseType','single',...'DimRange', [4 4]);% implementation argumentsarg = getTflArgFromString(hLib,'y2','void'); arg.IOType ='RTW_IO_OUTPUT'; entry.Implementation.setReturn(arg); arg = getTflArgFromString(hLib,'y1','single*'); arg.IOType ='RTW_IO_OUTPUT'; desc = RTW.ArgumentDescriptor; desc.AlignmentBoundary = 16; arg.Descriptor = desc; entry.Implementation.addArgument(arg); arg = getTflArgFromString(hLib,'u1','single*'); desc = RTW.ArgumentDescriptor; desc.AlignmentBoundary = 16; arg.Descriptor = desc; entry.Implementation.addArgument(arg); arg = getTflArgFromString(hLib,'u2','single*'); desc = RTW.ArgumentDescriptor; desc.AlignmentBoundary = 16; arg.Descriptor = desc; entry.Implementation.addArgument(arg); hLib.addEntry(entry);
  2. Create and save the following registration file,rtwTargetInfo.m. If you want to compile the code generated in this example, first modify theAlignmentSyntaxTemplateproperty for the compiler that you use. For example, for the MSVC compiler, replace the gcc template specification__attribute__((aligned(%n)))with__declspec(align(%n)).

    functionrtwTargetInfo(cm)% rtwTargetInfo function to register a code replacement library (CRL)% for use with code generation% Register the CRL defined in local function locCrlRegFcncm.registerTargetInfo(@locCrlRegFcn);end% End of RTWTARGETINFO% Local function to define a CRL containing crl_table_mmul_4x4_single_alignfunctionthisCrl = locCrlRegFcn% create an alignment specification object, assume gccas = 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 objectda = RTW.DataAlignment; da.addAlignmentSpecification(as);% add the data alignment object to target characteristicstc = RTW.TargetCharacteristics; tc.DataAlignment = da;% Instantiate a CRL registry entrythisCrl = RTW.TflRegistry;% Define the CRL propertiesthisCrl.Name ='Data Alignment Example'; thisCrl.Description ='Example of replacement with data alignment'; thisCrl.TableList = {'crl_table_mmul_4x4_single_align'}; thisCrl.TargetCharacteristics = tc;end% End of LOCCRLREGFCN
  3. To register your library with code generator without having to restart MATLAB®, enter this command:

    RTW.TargetRegistry.getInstance('reset');
  4. Configure the code generator to use your code replacement library.

  5. Generate code and a code generation report.

  6. Review the code replacements. For example, check whether a multiplication operation is replaced with amatrix_mul_4x4_sfunction call. Inmmalign.h, check whether the gcc alignment directive__attribute__((aligned(16)))is generated to align the function variables.

Related Topics