1# Copyright 2012-2019 The Meson development team
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6
7#     http://www.apache.org/licenses/LICENSE-2.0
8
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Representations specific to the arm family of compilers."""
16
17import os
18import re
19import typing as T
20
21from ... import mesonlib
22from ..compilers import clike_debug_args
23from .clang import clang_color_args
24
25if T.TYPE_CHECKING:
26    from ...environment import Environment
27
28arm_buildtype_args = {
29    'plain': [],
30    'debug': [],
31    'debugoptimized': [],
32    'release': [],
33    'minsize': [],
34    'custom': [],
35}  # type: T.Dict[str, T.List[str]]
36
37arm_optimization_args = {
38    '0': ['-O0'],
39    'g': ['-g'],
40    '1': ['-O1'],
41    '2': [], # Compiler defaults to -O2
42    '3': ['-O3', '-Otime'],
43    's': ['-O3'], # Compiler defaults to -Ospace
44}  # type: T.Dict[str, T.List[str]]
45
46armclang_buildtype_args = {
47    'plain': [],
48    'debug': [],
49    'debugoptimized': [],
50    'release': [],
51    'minsize': [],
52    'custom': [],
53}  # type: T.Dict[str, T.List[str]]
54
55armclang_optimization_args = {
56    '0': [], # Compiler defaults to -O0
57    'g': ['-g'],
58    '1': ['-O1'],
59    '2': ['-O2'],
60    '3': ['-O3'],
61    's': ['-Oz']
62}  # type: T.Dict[str, T.List[str]]
63
64
65class ArmCompiler:
66    # Functionality that is common to all ARM family compilers.
67    def __init__(self):
68        if not self.is_cross:
69            raise mesonlib.EnvironmentException('armcc supports only cross-compilation.')
70        self.id = 'arm'
71        default_warn_args = []  # type: T.List[str]
72        self.warn_args = {'0': [],
73                          '1': default_warn_args,
74                          '2': default_warn_args + [],
75                          '3': default_warn_args + []}
76        # Assembly
77        self.can_compile_suffixes.add('s')
78
79    def get_pic_args(self) -> T.List[str]:
80        # FIXME: Add /ropi, /rwpi, /fpic etc. qualifiers to --apcs
81        return []
82
83    def get_buildtype_args(self, buildtype: str) -> T.List[str]:
84        return arm_buildtype_args[buildtype]
85
86    # Override CCompiler.get_always_args
87    def get_always_args(self) -> T.List[str]:
88        return []
89
90    # Override CCompiler.get_dependency_gen_args
91    def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
92        return ['--depend_target', outtarget, '--depend', outfile, '--depend_single_line']
93
94    def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
95        # FIXME: Add required arguments
96        # NOTE from armcc user guide:
97        # "Support for Precompiled Header (PCH) files is deprecated from ARM Compiler 5.05
98        # onwards on all platforms. Note that ARM Compiler on Windows 8 never supported
99        # PCH files."
100        return []
101
102    def get_pch_suffix(self) -> str:
103        # NOTE from armcc user guide:
104        # "Support for Precompiled Header (PCH) files is deprecated from ARM Compiler 5.05
105        # onwards on all platforms. Note that ARM Compiler on Windows 8 never supported
106        # PCH files."
107        return 'pch'
108
109    def thread_flags(self, env: 'Environment') -> T.List[str]:
110        return []
111
112    def get_coverage_args(self) -> T.List[str]:
113        return []
114
115    def get_optimization_args(self, optimization_level: str) -> T.List[str]:
116        return arm_optimization_args[optimization_level]
117
118    def get_debug_args(self, is_debug: bool) -> T.List[str]:
119        return clike_debug_args[is_debug]
120
121    def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
122        for idx, i in enumerate(parameter_list):
123            if i[:2] == '-I' or i[:2] == '-L':
124                parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
125
126        return parameter_list
127
128
129class ArmclangCompiler:
130    def __init__(self):
131        if not self.is_cross:
132            raise mesonlib.EnvironmentException('armclang supports only cross-compilation.')
133        # Check whether 'armlink' is available in path
134        self.linker_exe = 'armlink'
135        args = '--vsn'
136        try:
137            p, stdo, stderr = mesonlib.Popen_safe(self.linker_exe, args)
138        except OSError as e:
139            err_msg = 'Unknown linker\nRunning "{0}" gave \n"{1}"'.format(' '.join([self.linker_exe] + [args]), e)
140            raise mesonlib.EnvironmentException(err_msg)
141        # Verify the armlink version
142        ver_str = re.search('.*Component.*', stdo)
143        if ver_str:
144            ver_str = ver_str.group(0)
145        else:
146            raise mesonlib.EnvironmentException('armlink version string not found')
147        assert ver_str  # makes mypy happy
148        # Using the regular expression from environment.search_version,
149        # which is used for searching compiler version
150        version_regex = r'(?<!(\d|\.))(\d{1,2}(\.\d+)+(-[a-zA-Z0-9]+)?)'
151        linker_ver = re.search(version_regex, ver_str)
152        if linker_ver:
153            linker_ver = linker_ver.group(0)
154        if not mesonlib.version_compare(self.version, '==' + linker_ver):
155            raise mesonlib.EnvironmentException('armlink version does not match with compiler version')
156        self.id = 'armclang'
157        self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
158                             'b_ndebug', 'b_staticpic', 'b_colorout']
159        # Assembly
160        self.can_compile_suffixes.add('s')
161
162    def get_pic_args(self) -> T.List[str]:
163        # PIC support is not enabled by default for ARM,
164        # if users want to use it, they need to add the required arguments explicitly
165        return []
166
167    def get_colorout_args(self, colortype: str) -> T.List[str]:
168        return clang_color_args[colortype][:]
169
170    def get_buildtype_args(self, buildtype: str) -> T.List[str]:
171        return armclang_buildtype_args[buildtype]
172
173    def get_pch_suffix(self) -> str:
174        return 'gch'
175
176    def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
177        # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
178        # This flag is internal to Clang (or at least not documented on the man page)
179        # so it might change semantics at any time.
180        return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
181
182    # Override CCompiler.get_dependency_gen_args
183    def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
184        return ['-MD', '-MT', outtarget, '-MF', outfile]
185
186    def get_optimization_args(self, optimization_level: str) -> T.List[str]:
187        return armclang_optimization_args[optimization_level]
188
189    def get_debug_args(self, is_debug: bool) -> T.List[str]:
190        return clike_debug_args[is_debug]
191
192    def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
193        for idx, i in enumerate(parameter_list):
194            if i[:2] == '-I' or i[:2] == '-L':
195                parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
196
197        return parameter_list
198