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 # hack: this list is not exhaustive
175 if outputname.endswith(('.exe', '.dll')):
176 return ['/Fe' + outputname]
177 return ['/Fo' + outputname]
178
179 def get_debug_args(self, is_debug: bool) -> T.List[str]:
180 if is_debug:
181 return ['/Z7']
182 else:
183 return []
184
185 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
186 args = msvc_optimization_args[optimization_level]
187 if mesonlib.version_compare(self.version, '<18.0'):
188 args = [arg for arg in args if arg != '/Gw']
189 return args
190
191 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
192 return ['/link'] + [arg for arg in args if arg != '/link']
193
194 def get_pic_args(self) -> T.List[str]:
195 return [] # PIC is handled by the loader on Windows
196
197 def gen_pch_args(self, header: str, source: str, pchname: str) -> T.Tuple[str, T.List[str]]:
198 objname = os.path.splitext(source)[0] + '.obj'
199 return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]
200
201 def openmp_flags(self) -> T.List[str]:
202 return ['/openmp']
203
204 def openmp_link_flags(self) -> T.List[str]:
205 return []
206
207 # FIXME, no idea what these should be.
208 def thread_flags(self) -> T.List[str]:
209 return []
210
211 @classmethod
212 def include_arg_to_native(cls, opt: str, path: str) -> str:
213 # msvc does not have a concept of system header dirs.
214 return f'/I{path}'
215
216 @classmethod
217 def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
218 result: T.List[str] = []
219 prev = None
220 for i in args:
221 if prev:
222 i = cls.include_arg_to_native(prev, i)
223 prev = None
224 # -mms-bitfields is specific to MinGW-GCC
225 # -pthread is only valid for GCC
226 elif i in {'-mms-bitfields', '-pthread'}:
227 continue
228 elif i.startswith('-LIBPATH:'):
229 i = '/LIBPATH:' + i[9:]
230 elif i.startswith('-L'):
231 i = '/LIBPATH:' + i[2:]
232 # Translate GNU-style -lfoo library name to the import library
233 elif i.startswith('-l'):
234 name = i[2:]
235 if name in cls.ignore_libs:
236 # With MSVC, these are provided by the C runtime which is
237 # linked in by default
238 continue
239 else:
240 i = name + '.lib'
241 elif i.startswith(('-iquote=', '-isystem=', '-idirafter=')):
242 opt, i = i.split('=', 1)
243 i = cls.include_arg_to_native(opt, i)
244 elif i in {'-iquote', '-isystem', '-idirafter'}:
245 prev = i
246 continue
247 elif i.startswith('-iquote'):
248 i = cls.include_arg_to_native('-iquote', i[7:])
249 elif i.startswith('-isystem'):
250 i = cls.include_arg_to_native('-isystem', i[8:])
251 elif i.startswith('-idirafter'):
252 i = cls.include_arg_to_native('-idirafter', i[10:])
253 # cl.exe does not allow specifying both, so remove /utf-8 that we
254 # added automatically in the case the user overrides it manually.
255 elif (i.startswith('/source-charset:')
256 or i.startswith('/execution-charset:')
257 or i == '/validate-charset-'):
258 try:
259 result.remove('/utf-8')
260 except ValueError:
261 pass
262 result.append(i)
263 return result
264
265 @classmethod
266 def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
267 result: T.List[str] = []
268 for arg in args:
269 if arg.startswith(('/LIBPATH:', '-LIBPATH:')):
270 result.append('-L' + arg[9:])
271 elif arg.endswith(('.a', '.lib')) and not mesonlib.path_has_root(arg):
272 result.append('-l' + arg)
273 else:
274 result.append(arg)
275 return result
276
277 def get_werror_args(self) -> T.List[str]:
278 return ['/WX']
279
280 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
281 if path == '':
282 path = '.'
283 if is_system:
284 # fixed up by unix_args_to_native() for Microsoft cl.exe
285 return ['-isystem', path]
286 return ['-I' + path]
287
288 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:
289 for idx, i in enumerate(parameter_list):
290 if i[:2] == '-I' or i[:2] == '/I':
291 parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))
292 elif i[:9] == '/LIBPATH:':
293 parameter_list[idx] = i[:9] + os.path.normpath(os.path.join(build_dir, i[9:]))
294
295 return parameter_list
296
297 # Visual Studio is special. It ignores some arguments it does not
298 # understand and you can't tell it to error out on those.
299 # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t
300 def has_arguments(self, args: T.List[str], code: str, mode: CompileCheckMode) -> T.Tuple[bool, bool]:
301 warning_text = '4044' if mode == CompileCheckMode.LINK else '9002'
302 with self._build_wrapper(code, extra_args=args, mode=mode) as p:
303 if p.returncode != 0:
304 return False, p.cached
305 return not (warning_text in p.stderr or warning_text in p.stdout), p.cached
306
307 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
308 pdbarr = rel_obj.split('.')[:-1]
309 pdbarr += ['pdb']
310 args = ['/Fd' + '.'.join(pdbarr)]
311 return args
312
313 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
314 if self.is_64:
315 return vs64_instruction_set_args.get(instruction_set, None)
316 return vs32_instruction_set_args.get(instruction_set, None)
317
318 def get_default_include_dirs(self) -> T.List[str]:
319 if 'INCLUDE' not in os.environ:
320 return []
321 return os.environ['INCLUDE'].split(os.pathsep)
322
323 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
324 crt_val = self.get_crt_val(crt_val)
325 return self.crt_args[crt_val]
326
327 def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]:
328 # MSVC doesn't have __attribute__ like Clang and GCC do, so just return
329 # false without compiling anything
330 return name in {'dllimport', 'dllexport'}, False
331
332 @staticmethod
333 def get_argument_syntax() -> str:
334 return 'msvc'
335
336 def symbols_have_underscore_prefix(self) -> bool:
337 '''
338 Check if the compiler prefixes an underscore to global C symbols.
339
340 This overrides the Clike method, as for MSVC checking the
341 underscore prefix based on the compiler define never works,
342 so do not even try.
343 '''
344 # Try to consult a hardcoded list of cases we know
345 # absolutely have an underscore prefix
346 result = self._symbols_have_underscore_prefix_list()
347 if result is not None:
348 return result
349
350 # As a last resort, try search in a compiled binary
351 return self._symbols_have_underscore_prefix_searchbin()
352
353 def get_pie_args(self) -> T.List[str]:
354 return []
355
356 def get_show_dep_args(self) -> T.List[str]:
357 # /showIncludes is needed for build dependency tracking in Ninja
358 # See: https://ninja-build.org/manual.html#_deps
359 return ['/showIncludes']
360
361 class MSVCCompiler(VisualStudioLikeCompiler):
362
363 """Specific to the Microsoft Compilers."""
364
365 id = 'msvc'
366
367 def __init__(self, target: str):
368 super().__init__(target)
369
370 self.base_options.update({OptionKey('b_lto'), OptionKey('b_lto_mode'), OptionKey('b_pgo')})
371
372 # Visual Studio 2013 and earlier don't support the /utf-8 argument.
373 # We want to remove it. We also want to make an explicit copy so we
374 # don't mutate class constant state
375 if mesonlib.version_compare(self.version, '<19.00') and '/utf-8' in self.always_args:
376 self.always_args = [r for r in self.always_args if r != '/utf-8']
377
378 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
379 args = super().get_compile_debugfile_args(rel_obj, pch)
380 # When generating a PDB file with PCH, all compile commands write
381 # to the same PDB file. Hence, we need to serialize the PDB
382 # writes using /FS since we do parallel builds. This slows down the
383 # build obviously, which is why we only do this when PCH is on.
384 # This was added in Visual Studio 2013 (MSVC 18.0). Before that it was
385 # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspx
386 if pch and mesonlib.version_compare(self.version, '>=18.0'):
387 args = ['/FS'] + args
388 return args
389
390 # Override CCompiler.get_always_args
391 # We want to drop '/utf-8' for Visual Studio 2013 and earlier
392 def get_always_args(self) -> T.List[str]:
393 return self.always_args
394
395 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
396 if self.version.split('.')[0] == '16' and instruction_set == 'avx':
397 # VS documentation says that this exists and should work, but
398 # it does not. The headers do not contain AVX intrinsics
399 # and they cannot be called.
400 return None
401 return super().get_instruction_set_args(instruction_set)
402
403 def get_pch_base_name(self, header: str) -> str:
404 return os.path.basename(header)
405
406 # MSVC requires linking to the generated object file when linking a build target
407 # that uses a precompiled header
408 def should_link_pch_object(self) -> bool:
409 return True
410
411 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
412 mode: str = 'default') -> T.List[str]:
413 args: T.List[str] = ['/GL']
414 if mode == 'thin':
415 args.append('/Gy')
416 return args
417
418 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
419 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
420 args: T.List[str] = []
421 # LTO data generated by MSVC is only usable by link
422 if not isinstance(self.linker, MSVCDynamicLinker):
423 raise mesonlib.MesonException(f"MSVC's LTCG only works with link, not {self.linker.id}")
424 if mode == 'default':
425 args.append('/LTCG')
426 elif mode == 'thin':
427 args.append('/LTCG:INCREMENTAL')
428 return args
429
430 def get_profile_generate_args(self) -> T.List[str]:
431 if not isinstance(self.linker, MSVCDynamicLinker):
432 raise mesonlib.MesonException(f"MSVC's PGO only works with link, not {self.linker.id}")
433 return self.linker_to_compiler_args(['/GENPROFILE'])
434
435 def get_profile_use_args(self) -> T.List[str]:
436 if not isinstance(self.linker, MSVCDynamicLinker):
437 raise mesonlib.MesonException(f"MSVC's PGO only works with link, not {self.linker.id}")
438 return self.linker_to_compiler_args(['/USEPROFILE'])
439
440 class ClangClCompiler(VisualStudioLikeCompiler):
441
442 """Specific to Clang-CL."""
443
444 id = 'clang-cl'
445
446 @classmethod
447 def include_arg_to_native(cls, opt: str, path: str) -> str:
448 # clang-cl does not seem to like a syntax like -iquote=...
449 # but unix_args_to_native() canonicalizes opt to not have
450 # a trailing equals sign
451 return f'/clang:{opt}{path}'
452
453 def __init__(self, target: str):
454 super().__init__(target)
455
456 self.base_options.update(
457 {OptionKey('b_lto_threads'), OptionKey('b_lto'), OptionKey('b_lto_mode'), OptionKey('b_thinlto_cache'),
458 OptionKey('b_thinlto_cache_dir')})
459
460 # Assembly
461 self.can_compile_suffixes.add('s')
462 self.can_compile_suffixes.add('sx')
463
464 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
465 if not value:
466 return value
467 args = ['/clang:-fsanitize=' + ','.join(value)]
468 if 'address' in value:
469 args.append('/clang:-fno-omit-frame-pointer')
470 return args
471
472 def has_arguments(self, args: T.List[str], code: str, mode: CompileCheckMode) -> T.Tuple[bool, bool]:
473 if mode != CompileCheckMode.LINK:
474 args = args + [
475 '-Werror=unknown-argument',
476 '-Werror=unknown-warning-option',
477 '-Werror=unused-command-line-argument',
478 ]
479 return super().has_arguments(args, code, mode)
480
481 def get_pch_base_name(self, header: str) -> str:
482 return header
483
484 @classmethod
485 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
486 # Clang additionally can use a linker specified as a path, unlike MSVC.
487 if linker == 'lld-link':
488 return ['-fuse-ld=lld-link']
489 return super().use_linker_args(linker, version)
490
491 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
492 # clang-cl forwards arguments span-wise with the /LINK flag
493 # therefore -Wl will be received by lld-link or LINK and rejected
494 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])
495
496 def openmp_link_flags(self) -> T.List[str]:
497 # see https://github.com/mesonbuild/meson/issues/5298
498 libs = self.find_library('libomp', [])
499 if libs is None:
500 raise mesonlib.MesonBugException('Could not find libomp')
501 return super().openmp_link_flags() + libs
502
503 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
504 mode: str = 'default') -> T.List[str]:
505 args: T.List[str] = []
506 if mode == 'thin':
507 # LTO data generated by clang-cl is only usable by lld-link
508 if not isinstance(self.linker, ClangClDynamicLinker):
509 raise mesonlib.MesonException(f"LLVM's ThinLTO only works with lld-link, not {self.linker.id}")
510 args.append(f'-flto={mode}')
511 else:
512 assert mode == 'default', 'someone forgot to wire something up'
513 args.extend(super().get_lto_compile_args(target=target, threads=threads))
514 return args
515
516 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
517 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
518 args = []
519 if mode == 'thin' and thinlto_cache_dir is not None:
520 args.extend(self.linker.get_thinlto_cache_args(thinlto_cache_dir))
521 # lld-link /threads:N has the same behaviour as -flto-jobs=N in lld
522 if threads > 0:
523 # clang-cl was released after clang already had LTO support, so it
524 # is safe to assume that all versions of clang-cl support LTO
525 args.append(f'/threads:{threads}')
526 return args