Debian Codegraph @

mesonbuild/compilers/mixins/visualstudio.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019 The meson development team
3 # Copyright © 2023 Intel Corporation
4
5 from __future__ import annotations
6
7 """Abstractions to simplify compilers that implement an MSVC compatible
8 interface.
9 """
10
11 import os
12 import typing as T
13
14 from ... import arglist
15 from ... import mesonlib
16 from mesonbuild.compilers.compilers import CompileCheckMode
17 from ...options import OptionKey
18 from mesonbuild.linkers.linkers import ClangClDynamicLinker, MSVCDynamicLinker
19
20 if T.TYPE_CHECKING:
21 from ...build import BuildTarget
22 from .clike import CLikeCompiler as Compiler
23 else:
24 # This is a bit clever, for mypy we pretend that these mixins descend from
25 # Compiler, so we get all of the methods and attributes defined for us, but
26 # for runtime we make them descend from object (which all classes normally
27 # do). This gives up DRYer type checking, with no runtime impact
28 Compiler = object
29
30 vs32_instruction_set_args: T.Dict[str, T.Optional[T.List[str]]] = {
31 'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMX
32 'sse': ['/arch:SSE'],
33 'sse2': ['/arch:SSE2'],
34 'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.
35 'sse41': ['/arch:AVX'],
36 'sse42': ['/arch:AVX'],
37 'avx': ['/arch:AVX'],
38 'avx2': ['/arch:AVX2'],
39 'neon': None,
40 }
41
42 # The 64 bit compiler defaults to /arch:avx.
43 vs64_instruction_set_args: T.Dict[str, T.Optional[T.List[str]]] = {
44 'mmx': ['/arch:AVX'],
45 'sse': ['/arch:AVX'],
46 'sse2': ['/arch:AVX'],
47 'sse3': ['/arch:AVX'],
48 'ssse3': ['/arch:AVX'],
49 'sse41': ['/arch:AVX'],
50 'sse42': ['/arch:AVX'],
51 'avx': ['/arch:AVX'],
52 'avx2': ['/arch:AVX2'],
53 'neon': None,
54 }
55
56 msvc_optimization_args: T.Dict[str, T.List[str]] = {
57 'plain': [],
58 '0': ['/Od'],
59 'g': [], # No specific flag to optimize debugging, /Zi or /ZI will create debug information
60 '1': ['/O1'],
61 '2': ['/O2'],
62 '3': ['/O2', '/Gw'],
63 's': ['/O1', '/Gw'],
64 }
65
66
67 class VisualStudioLikeCompiler(Compiler, metaclass=mesonlib.SimpleABC):
68
69 """A common interface for all compilers implementing an MSVC-style
70 interface.
71
72 A number of compilers attempt to mimic MSVC, with varying levels of
73 success, such as Clang-CL and ICL (the Intel C/C++ Compiler for Windows).
74 This class implements as much common logic as possible.
75 """
76
77 std_warn_args = ['/W3']
78 std_opt_args = ['/O2']
79 ignore_libs = arglist.UNIXY_COMPILER_INTERNAL_LIBS + ['execinfo']
80 internal_libs: T.List[str] = []
81
82 crt_args: T.Dict[str, T.List[str]] = {
83 'none': [],
84 'md': ['/MD'],
85 'mdd': ['/MDd'],
86 'mt': ['/MT'],
87 'mtd': ['/MTd'],
88 }
89
90 # Assume UTF-8 sources by default, but self.unix_args_to_native() removes it
91 # if `/source-charset` is set too.
92 # It is also dropped if Visual Studio 2013 or earlier is used, since it would
93 # not be supported in that case.
94 always_args = ['/nologo', '/utf-8']
95 warn_args: T.Dict[str, T.List[str]] = {
96 '0': [],
97 '1': ['/W2'],
98 '2': ['/W3'],
99 '3': ['/W4'],
100 'everything': ['/Wall'],
101 }
102
103 USED_FOR_SEPARATE_LINKING_STEP = False
104
105 def __init__(self, target: str):
106 self.base_options = {OptionKey(o) for o in ['b_pch', 'b_ndebug', 'b_vscrt']} # FIXME add lto, pgo and the like
107 self.target = target
108 self.is_64 = ('x64' in target) or ('x86_64' in target)
109 # do some canonicalization of target machine
110 if 'x86_64' in target:
111 self.machine = 'x64'
112 elif '86' in target:
113 self.machine = 'x86'
114 elif 'aarch64' in target:
115 self.machine = 'arm64'
116 elif 'arm' in target:
117 self.machine = 'arm'
118 else:
119 self.machine = target
120 if mesonlib.version_compare(self.version, '>=19.28.29910'): # VS 16.9.0 includes cl 19.28.29910
121 self.base_options.add(OptionKey('b_sanitize'))
122 assert self.linker is not None
123 self.linker.machine = self.machine
124
125 # Override CCompiler.get_always_args
126 def get_always_args(self) -> T.List[str]:
127 # TODO: use ImmutableListProtocol[str] here instead
128 return self.always_args.copy()
129
130 def get_no_stdinc_args(self) -> T.List[str]:
131 return ['/X']
132
133 def get_no_stdlib_link_args(self) -> T.List[str]:
134 return ['/NODEFAULTLIB']
135
136 def get_pch_suffix(self) -> str:
137 return 'pch'
138
139 def get_pch_name(self, name: str) -> str:
140 chopped = os.path.basename(name).split('.')[:-1]
141 chopped.append(self.get_pch_suffix())
142 pchname = '.'.join(chopped)
143 return pchname
144
145 def get_pch_base_name(self, header: str) -> str:
146 # This needs to be implemented by inheriting classes
147 raise NotImplementedError
148
149 def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
150 base = self.get_pch_base_name(header)
151 pchname = self.get_pch_name(header)
152 return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]
153
154 def get_preprocess_only_args(self) -> T.List[str]:
155 return ['/EP']
156
157 def get_preprocess_to_file_args(self) -> T.List[str]:
158 return ['/EP', '/P']
159
160 def get_compile_only_args(self) -> T.List[str]:
161 return ['/c']
162
163 def get_no_optimization_args(self) -> T.List[str]:
164 return ['/Od', '/Oi-']
165
166 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
167 if not value:
168 return value
169 return [f'/fsanitize={",".join(value)}']
170
171 def get_output_args(self, outputname: str) -> T.List[str]:
172 if self.mode == 'PREPROCESSOR':
173 return ['/Fi' + outputname]
174 if outputname.endswith('.exe'):
175 return ['/Fe' + outputname]
176 return ['/Fo' + outputname]
177
178 def get_debug_args(self, is_debug: bool) -> T.List[str]:
179 if is_debug:
180 return ['/Z7']
181 else:
182 return []
183
184 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
185 args = msvc_optimization_args[optimization_level]
186 if mesonlib.version_compare(self.version, '<18.0'):
187 args = [arg for arg in args if arg != '/Gw']
188 return args
189
190 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
191 return ['/link'] + [arg for arg in args if arg != '/link']
192
193 def get_pic_args(self) -> T.List[str]:
194 return [] # PIC is handled by the loader on Windows
195
196 def gen_pch_args(self, header: str, source: str, pchname: str) -> T.Tuple[str, T.List[str]]:
197 objname = os.path.splitext(source)[0] + '.obj'
198 return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]
199
200 def openmp_flags(self) -> T.List[str]:
201 return ['/openmp']
202
203 def openmp_link_flags(self) -> T.List[str]:
204 return []
205
206 # FIXME, no idea what these should be.
207 def thread_flags(self) -> T.List[str]:
208 return []
209
210 @classmethod
211 def include_arg_to_native(cls, opt: str, path: str) -> str:
212 # msvc does not have a concept of system header dirs.
213 return f'/I{path}'
214
215 @classmethod
216 def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
217 result: T.List[str] = []
218 prev = None
219 for i in args:
220 if prev:
221 i = cls.include_arg_to_native(prev, i)
222 prev = None
223 # -mms-bitfields is specific to MinGW-GCC
224 # -pthread is only valid for GCC
225 elif i in {'-mms-bitfields', '-pthread'}:
226 continue
227 elif i.startswith('-LIBPATH:'):
228 i = '/LIBPATH:' + i[9:]
229 elif i.startswith('-L'):
230 i = '/LIBPATH:' + i[2:]
231 # Translate GNU-style -lfoo library name to the import library
232 elif i.startswith('-l'):
233 name = i[2:]
234 if name in cls.ignore_libs:
235 # With MSVC, these are provided by the C runtime which is
236 # linked in by default
237 continue
238 else:
239 i = name + '.lib'
240 elif i.startswith(('-iquote=', '-isystem=', '-idirafter=')):
241 opt, i = i.split('=', 1)
242 i = cls.include_arg_to_native(opt, i)
243 elif i in {'-iquote', '-isystem', '-idirafter'}:
244 prev = i
245 continue
246 elif i.startswith('-iquote'):
247 i = cls.include_arg_to_native('-iquote', i[7:])
248 elif i.startswith('-isystem'):
249 i = cls.include_arg_to_native('-isystem', i[8:])
250 elif i.startswith('-idirafter'):
251 i = cls.include_arg_to_native('-idirafter', i[10:])
252 # cl.exe does not allow specifying both, so remove /utf-8 that we
253 # added automatically in the case the user overrides it manually.
254 elif (i.startswith('/source-charset:')
255 or i.startswith('/execution-charset:')
256 or i == '/validate-charset-'):
257 try:
258 result.remove('/utf-8')
259 except ValueError:
260 pass
261 result.append(i)
262 return result
263
264 @classmethod
265 def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
266 result: T.List[str] = []
267 for arg in args:
268 if arg.startswith(('/LIBPATH:', '-LIBPATH:')):
269 result.append('-L' + arg[9:])
270 elif arg.endswith(('.a', '.lib')) and not mesonlib.path_has_root(arg):
271 result.append('-l' + arg)
272 else:
273 result.append(arg)
274 return result
275
276 def get_werror_args(self) -> T.List[str]:
277 return ['/WX']
278
279 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
280 if path == '':
281 path = '.'
282 if is_system:
283 # fixed up by unix_args_to_native() for Microsoft cl.exe
284 return ['-isystem', path]
285 return ['-I' + path]
286
287 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
288 for idx, i in enumerate(parameter_list):
289 if i[:2] == '-I' or i[:2] == '/I':
290 parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
291 elif i[:9] == '/LIBPATH:':
292 parameter_list[idx] = i[:9] + os.path.normpath(os.path.join(build_dir, i[9:]))
293
294 return parameter_list
295
296 # Visual Studio is special. It ignores some arguments it does not
297 # understand and you can't tell it to error out on those.
298 # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t
299 def has_arguments(self, args: T.List[str], code: str, mode: CompileCheckMode) -> T.Tuple[bool, bool]:
300 warning_text = '4044' if mode == CompileCheckMode.LINK else '9002'
301 with self._build_wrapper(code, extra_args=args, mode=mode) as p:
302 if p.returncode != 0:
303 return False, p.cached
304 return not (warning_text in p.stderr or warning_text in p.stdout), p.cached
305
306 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
307 pdbarr = rel_obj.split('.')[:-1]
308 pdbarr += ['pdb']
309 args = ['/Fd' + '.'.join(pdbarr)]
310 return args
311
312 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
313 if self.is_64:
314 return vs64_instruction_set_args.get(instruction_set, None)
315 return vs32_instruction_set_args.get(instruction_set, None)
316
317 def get_default_include_dirs(self) -> T.List[str]:
318 if 'INCLUDE' not in os.environ:
319 return []
320 return os.environ['INCLUDE'].split(os.pathsep)
321
322 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
323 crt_val = self.get_crt_val(crt_val)
324 return self.crt_args[crt_val]
325
326 def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]:
327 # MSVC doesn't have __attribute__ like Clang and GCC do, so just return
328 # false without compiling anything
329 return name in {'dllimport', 'dllexport'}, False
330
331 @staticmethod
332 def get_argument_syntax() -> str:
333 return 'msvc'
334
335 def symbols_have_underscore_prefix(self) -> bool:
336 '''
337 Check if the compiler prefixes an underscore to global C symbols.
338
339 This overrides the Clike method, as for MSVC checking the
340 underscore prefix based on the compiler define never works,
341 so do not even try.
342 '''
343 # Try to consult a hardcoded list of cases we know
344 # absolutely have an underscore prefix
345 result = self._symbols_have_underscore_prefix_list()
346 if result is not None:
347 return result
348
349 # As a last resort, try search in a compiled binary
350 return self._symbols_have_underscore_prefix_searchbin()
351
352 def get_pie_args(self) -> T.List[str]:
353 return []
354
355 def get_show_dep_args(self) -> T.List[str]:
356 # /showIncludes is needed for build dependency tracking in Ninja
357 # See: https://ninja-build.org/manual.html#_deps
358 return ['/showIncludes']
359
360 class MSVCCompiler(VisualStudioLikeCompiler):
361
362 """Specific to the Microsoft Compilers."""
363
364 id = 'msvc'
365
366 def __init__(self, target: str):
367 super().__init__(target)
368
369 self.base_options.update({OptionKey('b_lto'), OptionKey('b_lto_mode'), OptionKey('b_pgo')})
370
371 # Visual Studio 2013 and earlier don't support the /utf-8 argument.
372 # We want to remove it. We also want to make an explicit copy so we
373 # don't mutate class constant state
374 if mesonlib.version_compare(self.version, '<19.00') and '/utf-8' in self.always_args:
375 self.always_args = [r for r in self.always_args if r != '/utf-8']
376
377 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
378 args = super().get_compile_debugfile_args(rel_obj, pch)
379 # When generating a PDB file with PCH, all compile commands write
380 # to the same PDB file. Hence, we need to serialize the PDB
381 # writes using /FS since we do parallel builds. This slows down the
382 # build obviously, which is why we only do this when PCH is on.
383 # This was added in Visual Studio 2013 (MSVC 18.0). Before that it was
384 # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspx
385 if pch and mesonlib.version_compare(self.version, '>=18.0'):
386 args = ['/FS'] + args
387 return args
388
389 # Override CCompiler.get_always_args
390 # We want to drop '/utf-8' for Visual Studio 2013 and earlier
391 def get_always_args(self) -> T.List[str]:
392 return self.always_args
393
394 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
395 if self.version.split('.')[0] == '16' and instruction_set == 'avx':
396 # VS documentation says that this exists and should work, but
397 # it does not. The headers do not contain AVX intrinsics
398 # and they cannot be called.
399 return None
400 return super().get_instruction_set_args(instruction_set)
401
402 def get_pch_base_name(self, header: str) -> str:
403 return os.path.basename(header)
404
405 # MSVC requires linking to the generated object file when linking a build target
406 # that uses a precompiled header
407 def should_link_pch_object(self) -> bool:
408 return True
409
410 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
411 mode: str = 'default') -> T.List[str]:
412 args: T.List[str] = ['/GL']
413 if mode == 'thin':
414 args.append('/Gy')
415 return args
416
417 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
418 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
419 args: T.List[str] = []
420 # LTO data generated by MSVC is only usable by link
421 if not isinstance(self.linker, MSVCDynamicLinker):
422 raise mesonlib.MesonException(f"MSVC's LTCG only works with link, not {self.linker.id}")
423 if mode == 'default':
424 args.append('/LTCG')
425 elif mode == 'thin':
426 args.append('/LTCG:INCREMENTAL')
427 return args
428
429 def get_profile_generate_args(self) -> T.List[str]:
430 if not isinstance(self.linker, MSVCDynamicLinker):
431 raise mesonlib.MesonException(f"MSVC's PGO only works with link, not {self.linker.id}")
432 return self.linker_to_compiler_args(['/GENPROFILE'])
433
434 def get_profile_use_args(self) -> T.List[str]:
435 if not isinstance(self.linker, MSVCDynamicLinker):
436 raise mesonlib.MesonException(f"MSVC's PGO only works with link, not {self.linker.id}")
437 return self.linker_to_compiler_args(['/USEPROFILE'])
438
439 class ClangClCompiler(VisualStudioLikeCompiler):
440
441 """Specific to Clang-CL."""
442
443 id = 'clang-cl'
444
445 @classmethod
446 def include_arg_to_native(cls, opt: str, path: str) -> str:
447 # clang-cl does not seem to like a syntax like -iquote=...
448 # but unix_args_to_native() canonicalizes opt to not have
449 # a trailing equals sign
450 return f'/clang:{opt}{path}'
451
452 def __init__(self, target: str):
453 super().__init__(target)
454
455 self.base_options.update(
456 {OptionKey('b_lto_threads'), OptionKey('b_lto'), OptionKey('b_lto_mode'), OptionKey('b_thinlto_cache'),
457 OptionKey('b_thinlto_cache_dir')})
458
459 # Assembly
460 self.can_compile_suffixes.add('s')
461 self.can_compile_suffixes.add('sx')
462
463 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
464 if not value:
465 return value
466 args = ['/clang:-fsanitize=' + ','.join(value)]
467 if 'address' in value:
468 args.append('/clang:-fno-omit-frame-pointer')
469 return args
470
471 def has_arguments(self, args: T.List[str], code: str, mode: CompileCheckMode) -> T.Tuple[bool, bool]:
472 if mode != CompileCheckMode.LINK:
473 args = args + [
474 '-Werror=unknown-argument',
475 '-Werror=unknown-warning-option',
476 '-Werror=unused-command-line-argument',
477 ]
478 return super().has_arguments(args, code, mode)
479
480 def get_pch_base_name(self, header: str) -> str:
481 return header
482
483 @classmethod
484 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
485 # Clang additionally can use a linker specified as a path, unlike MSVC.
486 if linker == 'lld-link':
487 return ['-fuse-ld=lld-link']
488 return super().use_linker_args(linker, version)
489
490 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
491 # clang-cl forwards arguments span-wise with the /LINK flag
492 # therefore -Wl will be received by lld-link or LINK and rejected
493 return super().use_linker_args(self.linker.id, '') + super().linker_to_compiler_args([flag[4:] if flag.startswith('-Wl,') else flag for flag in args])
494
495 def openmp_link_flags(self) -> T.List[str]:
496 # see https://github.com/mesonbuild/meson/issues/5298
497 libs = self.find_library('libomp', [])
498 if libs is None:
499 raise mesonlib.MesonBugException('Could not find libomp')
500 return super().openmp_link_flags() + libs
501
502 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
503 mode: str = 'default') -> T.List[str]:
504 args: T.List[str] = []
505 if mode == 'thin':
506 # LTO data generated by clang-cl is only usable by lld-link
507 if not isinstance(self.linker, ClangClDynamicLinker):
508 raise mesonlib.MesonException(f"LLVM's ThinLTO only works with lld-link, not {self.linker.id}")
509 args.append(f'-flto={mode}')
510 else:
511 assert mode == 'default', 'someone forgot to wire something up'
512 args.extend(super().get_lto_compile_args(target=target, threads=threads))
513 return args
514
515 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
516 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
517 args = []
518 if mode == 'thin' and thinlto_cache_dir is not None:
519 args.extend(self.linker.get_thinlto_cache_args(thinlto_cache_dir))
520 # lld-link /threads:N has the same behaviour as -flto-jobs=N in lld
521 if threads > 0:
522 # clang-cl was released after clang already had LTO support, so it
523 # is safe to assume that all versions of clang-cl support LTO
524 args.append(f'/threads:{threads}')
525 return args