]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/doc/gcc/extensions-to-the-c++-language/function-multiversioning.rst
sphinx: add missing trailing newline
[thirdparty/gcc.git] / gcc / doc / gcc / extensions-to-the-c++-language / function-multiversioning.rst
CommitLineData
c63539ff
ML
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
10Function Multiversioning
11************************
12
13With the GNU C++ front end, for x86 targets, you may specify multiple
14versions of a function, where each function is specialized for a
15specific target feature. At runtime, the appropriate version of the
16function is automatically executed depending on the characteristics of
17the 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
56In the above example, four versions of function foo are created. The
57first version of foo with the target attribute "default" is the default
58version. This version gets executed when no other target specific
59version qualifies for execution on a particular platform. A new version
60of foo is created by using the same function signature but with a
61different target string. Function foo is called or a pointer to it is
62taken just like a regular function. GCC takes care of doing the
63dispatching to call the right version at runtime. Refer to the
64`GCC wiki on
3ed1b4ce 65Function Multiversioning <https://gcc.gnu.org/wiki/FunctionMultiVersioning>`_ for more details.