]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/doc/gcc/extensions-to-the-c++-language/function-multiversioning.rst
2524ff5353cbfce5f2cbe0a5f522d80ea2bd9742
[thirdparty/gcc.git] / gcc / doc / gcc / extensions-to-the-c++-language / function-multiversioning.rst
1 ..
2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
5
6 .. index:: function versions
7
8 .. _function-multiversioning:
9
10 Function Multiversioning
11 ************************
12
13 With the GNU C++ front end, for x86 targets, you may specify multiple
14 versions of a function, where each function is specialized for a
15 specific target feature. At runtime, the appropriate version of the
16 function is automatically executed depending on the characteristics of
17 the execution platform. Here is an example.
18
19 .. code-block:: c++
20
21 __attribute__ ((target ("default")))
22 int foo ()
23 {
24 // The default version of foo.
25 return 0;
26 }
27
28 __attribute__ ((target ("sse4.2")))
29 int foo ()
30 {
31 // foo version for SSE4.2
32 return 1;
33 }
34
35 __attribute__ ((target ("arch=atom")))
36 int foo ()
37 {
38 // foo version for the Intel ATOM processor
39 return 2;
40 }
41
42 __attribute__ ((target ("arch=amdfam10")))
43 int foo ()
44 {
45 // foo version for the AMD Family 0x10 processors.
46 return 3;
47 }
48
49 int main ()
50 {
51 int (*p)() = &foo;
52 assert ((*p) () == foo ());
53 return 0;
54 }
55
56 In the above example, four versions of function foo are created. The
57 first version of foo with the target attribute "default" is the default
58 version. This version gets executed when no other target specific
59 version qualifies for execution on a particular platform. A new version
60 of foo is created by using the same function signature but with a
61 different target string. Function foo is called or a pointer to it is
62 taken just like a regular function. GCC takes care of doing the
63 dispatching to call the right version at runtime. Refer to the
64 `GCC wiki on
65 Function Multiversioning <https://gcc.gnu.org/wiki/FunctionMultiVersioning>`_ for more details.