Debian Codegraph @

third_party/rust/cc/src/flags.rs

raw
1 use crate::target::TargetInfo;
2 use crate::{Build, Error, ErrorKind, Tool, ToolFamily};
3 use std::borrow::Cow;
4 use std::ffi::OsString;
5
6 #[derive(Debug, PartialEq, Default)]
7 pub(crate) struct RustcCodegenFlags<'a> {
8 branch_protection: Option<&'a str>,
9 code_model: Option<&'a str>,
10 no_vectorize_loops: bool,
11 no_vectorize_slp: bool,
12 profile_generate: Option<&'a str>,
13 profile_use: Option<&'a str>,
14 control_flow_guard: Option<&'a str>,
15 lto: Option<&'a str>,
16 relocation_model: Option<&'a str>,
17 embed_bitcode: Option<bool>,
18 force_frame_pointers: Option<bool>,
19 no_redzone: Option<bool>,
20 soft_float: Option<bool>,
21 }
22
23 impl<'this> RustcCodegenFlags<'this> {
24 // Parse flags obtained from CARGO_ENCODED_RUSTFLAGS
25 pub(crate) fn parse(rustflags_env: &'this str) -> Result<Self, Error> {
26 fn is_flag_prefix(flag: &str) -> bool {
27 [
28 "-Z",
29 "-C",
30 "--codegen",
31 "-L",
32 "-l",
33 "-o",
34 "-W",
35 "--warn",
36 "-A",
37 "--allow",
38 "-D",
39 "--deny",
40 "-F",
41 "--forbid",
42 ]
43 .contains(&flag)
44 }
45
46 fn handle_flag_prefix<'a>(prev: &'a str, curr: &'a str) -> (&'a str, &'a str) {
47 match prev {
48 "--codegen" | "-C" => ("-C", curr),
49 // Handle flags passed like --codegen=code-model=small
50 _ if curr.starts_with("--codegen=") => ("-C", &curr[10..]),
51 "-Z" => ("-Z", curr),
52 "-L" | "-l" | "-o" => (prev, curr),
53 // Handle lint flags
54 "-W" | "--warn" => ("-W", curr),
55 "-A" | "--allow" => ("-A", curr),
56 "-D" | "--deny" => ("-D", curr),
57 "-F" | "--forbid" => ("-F", curr),
58 _ => ("", curr),
59 }
60 }
61
62 let mut codegen_flags = Self::default();
63
64 let mut prev_prefix = None;
65 for curr in rustflags_env.split("\u{1f}") {
66 let prev = prev_prefix.take().unwrap_or("");
67 if prev.is_empty() && is_flag_prefix(curr) {
68 prev_prefix = Some(curr);
69 continue;
70 }
71
72 let (prefix, rustc_flag) = handle_flag_prefix(prev, curr);
73 codegen_flags.set_rustc_flag(prefix, rustc_flag)?;
74 }
75
76 Ok(codegen_flags)
77 }
78
79 fn set_rustc_flag(&mut self, prefix: &str, flag: &'this str) -> Result<(), Error> {
80 // Convert a textual representation of a bool-like rustc flag argument into an actual bool
81 fn arg_to_bool(arg: impl AsRef<str>) -> Option<bool> {
82 match arg.as_ref() {
83 "y" | "yes" | "on" | "true" => Some(true),
84 "n" | "no" | "off" | "false" => Some(false),
85 _ => None,
86 }
87 }
88
89 let (flag, value) = if let Some((flag, value)) = flag.split_once('=') {
90 (flag, Some(value))
91 } else {
92 (flag, None)
93 };
94 let flag = if prefix.is_empty() {
95 Cow::Borrowed(flag)
96 } else {
97 Cow::Owned(format!("{prefix}{flag}"))
98 };
99
100 fn flag_ok_or<'flag>(
101 flag: Option<&'flag str>,
102 msg: &'static str,
103 ) -> Result<&'flag str, Error> {
104 flag.ok_or(Error::new(ErrorKind::InvalidFlag, msg))
105 }
106
107 match flag.as_ref() {
108 // https://doc.rust-lang.org/rustc/codegen-options/index.html#code-model
109 "-Ccode-model" => {
110 self.code_model = Some(flag_ok_or(value, "-Ccode-model must have a value")?);
111 }
112 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-loops
113 "-Cno-vectorize-loops" => self.no_vectorize_loops = true,
114 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-slp
115 "-Cno-vectorize-slp" => self.no_vectorize_slp = true,
116 // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-generate
117 "-Cprofile-generate" => {
118 self.profile_generate =
119 Some(flag_ok_or(value, "-Cprofile-generate must have a value")?);
120 }
121 // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-use
122 "-Cprofile-use" => {
123 self.profile_use = Some(flag_ok_or(value, "-Cprofile-use must have a value")?);
124 }
125 // https://doc.rust-lang.org/rustc/codegen-options/index.html#control-flow-guard
126 "-Ccontrol-flow-guard" => self.control_flow_guard = value.or(Some("true")),
127 // https://doc.rust-lang.org/rustc/codegen-options/index.html#lto
128 "-Clto" => self.lto = value.or(Some("true")),
129 // https://doc.rust-lang.org/rustc/codegen-options/index.html#relocation-model
130 "-Crelocation-model" => {
131 self.relocation_model =
132 Some(flag_ok_or(value, "-Crelocation-model must have a value")?);
133 }
134 // https://doc.rust-lang.org/rustc/codegen-options/index.html#embed-bitcode
135 "-Cembed-bitcode" => self.embed_bitcode = value.map_or(Some(true), arg_to_bool),
136 // https://doc.rust-lang.org/rustc/codegen-options/index.html#force-frame-pointers
137 "-Cforce-frame-pointers" => {
138 self.force_frame_pointers = value.map_or(Some(true), arg_to_bool)
139 }
140 // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-redzone
141 "-Cno-redzone" => self.no_redzone = value.map_or(Some(true), arg_to_bool),
142 // https://doc.rust-lang.org/rustc/codegen-options/index.html#soft-float
143 // Note: This flag is now deprecated in rustc.
144 "-Csoft-float" => self.soft_float = value.map_or(Some(true), arg_to_bool),
145 // https://doc.rust-lang.org/beta/unstable-book/compiler-flags/branch-protection.html
146 // FIXME: Drop the -Z variant and update the doc link once the option is stabilised
147 "-Zbranch-protection" | "-Cbranch-protection" => {
148 self.branch_protection =
149 Some(flag_ok_or(value, "-Zbranch-protection must have a value")?);
150 }
151 _ => {}
152 }
153 Ok(())
154 }
155
156 // Rust and clang/cc don't agree on what equivalent flags should look like.
157 pub(crate) fn cc_flags(&self, build: &Build, tool: &mut Tool, target: &TargetInfo<'_>) {
158 let family = tool.family;
159 // Push `flag` to `flags` if it is supported by the currently used CC
160 let mut push_if_supported = |flag: OsString| {
161 if build
162 .is_flag_supported_inner(&flag, tool, target)
163 .unwrap_or(false)
164 {
165 tool.args.push(flag);
166 } else {
167 build.cargo_output.print_warning(&format!(
168 "Inherited flag {:?} is not supported by the currently used CC",
169 flag
170 ));
171 }
172 };
173
174 let clang_or_gnu =
175 matches!(family, ToolFamily::Clang { .. }) || matches!(family, ToolFamily::Gnu { .. });
176
177 // Flags shared between clang and gnu
178 if clang_or_gnu {
179 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mbranch-protection
180 // https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html#index-mbranch-protection (Aarch64)
181 // https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html#index-mbranch-protection-1 (ARM)
182 // https://developer.arm.com/documentation/101754/0619/armclang-Reference/armclang-Command-line-Options/-mbranch-protection
183 if let Some(value) = self.branch_protection {
184 push_if_supported(
185 format!("-mbranch-protection={}", value.replace(",", "+")).into(),
186 );
187 }
188 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mcmodel
189 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-mcmodel=`).
190 // FIXME(madsmtm): Parse the model, to make sure we pass the correct value (depending on arch).
191 if let Some(value) = self.code_model {
192 push_if_supported(format!("-mcmodel={value}").into());
193 }
194 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-vectorize
195 // https://gcc.gnu.org/onlinedocs/gnat_ugn/Vectorization-of-loops.html
196 if self.no_vectorize_loops {
197 push_if_supported("-fno-vectorize".into());
198 }
199 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-slp-vectorize
200 // https://gcc.gnu.org/onlinedocs/gnat_ugn/Vectorization-of-loops.html
201 if self.no_vectorize_slp {
202 push_if_supported("-fno-slp-vectorize".into());
203 }
204 if let Some(value) = self.relocation_model {
205 let cc_flag = match value {
206 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIC
207 // https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fPIC
208 "pic" => Some("-fPIC"),
209 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIE
210 // https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fPIE
211 "pie" => Some("-fPIE"),
212 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mdynamic-no-pic
213 // https://gcc.gnu.org/onlinedocs/gcc/RS_002f6000-and-PowerPC-Options.html#index-mdynamic-no-pic
214 "dynamic-no-pic" => Some("-mdynamic-no-pic"),
215 _ => None,
216 };
217 if let Some(cc_flag) = cc_flag {
218 push_if_supported(cc_flag.into());
219 }
220 }
221 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-omit-frame-pointer
222 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fomit-frame-pointer
223 // https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fomit-frame-pointer
224 if let Some(value) = self.force_frame_pointers {
225 let cc_flag = if value {
226 "-fno-omit-frame-pointer"
227 } else {
228 "-fomit-frame-pointer"
229 };
230 push_if_supported(cc_flag.into());
231 }
232 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mno-red-zone
233 // https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-mno-red-zone
234 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mred-zone
235 // https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-mred-zone
236 if let Some(value) = self.no_redzone {
237 let cc_flag = if value { "-mno-red-zone" } else { "-mred-zone" };
238 push_if_supported(cc_flag.into());
239 }
240 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-msoft-float
241 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mhard-float
242 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-msoft-float`).
243 // https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html (several archs, search for `-mhard-float`).
244 if let Some(value) = self.soft_float {
245 let cc_flag = if value {
246 "-msoft-float"
247 } else {
248 // Do not use -mno-soft-float, that's basically just an alias for -mno-implicit-float.
249 "-mhard-float"
250 };
251 push_if_supported(cc_flag.into());
252 }
253 }
254
255 // Compiler-exclusive flags
256 match family {
257 ToolFamily::Clang { .. } => {
258 // GNU and Clang compilers both support the same PGO flags, but they use different libraries and
259 // different formats for the profile files which are not compatible.
260 // clang and rustc both internally use llvm, so we want to inherit the PGO flags only for clang.
261 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-generate
262 if let Some(value) = self.profile_generate {
263 push_if_supported(format!("-fprofile-generate={value}").into());
264 }
265 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-use
266 if let Some(value) = self.profile_use {
267 push_if_supported(format!("-fprofile-use={value}").into());
268 }
269
270 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fembed-bitcode
271 if let Some(value) = self.embed_bitcode {
272 let cc_val = if value { "all" } else { "off" };
273 push_if_supported(format!("-fembed-bitcode={cc_val}").into());
274 }
275
276 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-flto
277 if let Some(value) = self.lto {
278 let cc_val = match value {
279 "y" | "yes" | "on" | "true" | "fat" => Some("full"),
280 "thin" => Some("thin"),
281 _ => None,
282 };
283 if let Some(cc_val) = cc_val {
284 push_if_supported(format!("-flto={cc_val}").into());
285 }
286 }
287 // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mguard
288 if let Some(value) = self.control_flow_guard {
289 let cc_val = match value {
290 "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
291 "nochecks" => Some("cf-nochecks"),
292 "n" | "no" | "off" | "false" => Some("none"),
293 _ => None,
294 };
295 if let Some(cc_val) = cc_val {
296 push_if_supported(format!("-mguard={cc_val}").into());
297 }
298 }
299 }
300 ToolFamily::Gnu { .. } => {}
301 ToolFamily::Msvc { .. } => {
302 // https://learn.microsoft.com/en-us/cpp/build/reference/guard-enable-control-flow-guard
303 if let Some(value) = self.control_flow_guard {
304 let cc_val = match value {
305 "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
306 "n" | "no" | "off" | "false" => Some("cf-"),
307 _ => None,
308 };
309 if let Some(cc_val) = cc_val {
310 push_if_supported(format!("/guard:{cc_val}").into());
311 }
312 }
313 // https://learn.microsoft.com/en-us/cpp/build/reference/oy-frame-pointer-omission
314 if let Some(value) = self.force_frame_pointers {
315 // Flag is unsupported on 64-bit arches
316 if !target.arch.contains("64") {
317 let cc_flag = if value { "/Oy-" } else { "/Oy" };
318 push_if_supported(cc_flag.into());
319 }
320 }
321 }
322 }
323 }
324 }
325
326 #[cfg(test)]
327 mod tests {
328 use super::*;
329
330 #[track_caller]
331 fn check(env: &str, expected: &RustcCodegenFlags) {
332 let actual = RustcCodegenFlags::parse(env).unwrap();
333 assert_eq!(actual, *expected);
334 }
335
336 #[test]
337 fn codegen_type() {
338 let expected = RustcCodegenFlags {
339 code_model: Some("tiny"),
340 ..RustcCodegenFlags::default()
341 };
342 check("-Ccode-model=tiny", &expected);
343 check("-C\u{1f}code-model=tiny", &expected);
344 check("--codegen\u{1f}code-model=tiny", &expected);
345 check("--codegen=code-model=tiny", &expected);
346 }
347
348 #[test]
349 fn precedence() {
350 check(
351 "-ccode-model=tiny\u{1f}-Ccode-model=small",
352 &RustcCodegenFlags {
353 code_model: Some("small"),
354 ..RustcCodegenFlags::default()
355 },
356 );
357 }
358
359 #[test]
360 fn two_valid_prefixes() {
361 let expected = RustcCodegenFlags::default();
362 check("-L\u{1f}-Clto", &expected);
363 }
364
365 #[test]
366 fn three_valid_prefixes() {
367 let expected = RustcCodegenFlags {
368 lto: Some("true"),
369 ..RustcCodegenFlags::default()
370 };
371 check("-L\u{1f}-L\u{1f}-Clto", &expected);
372 }
373
374 #[test]
375 fn all_rustc_flags() {
376 // Throw all possible flags at the parser to catch false positives
377 let flags = [
378 // Set all the flags we recognise first
379 "-Ccode-model=tiny",
380 "-Ccontrol-flow-guard=yes",
381 "-Cembed-bitcode=no",
382 "-Cforce-frame-pointers=yes",
383 "-Clto=false",
384 "-Clink-dead-code=yes",
385 "-Cno-redzone=yes",
386 "-Cno-vectorize-loops",
387 "-Cno-vectorize-slp",
388 "-Cprofile-generate=fooprofile",
389 "-Cprofile-use=fooprofile",
390 "-Crelocation-model=pic",
391 "-Csoft-float=yes",
392 "-Zbranch-protection=bti,pac-ret,leaf",
393 // Set flags we don't recognise but rustc supports next
394 // rustc flags
395 "--cfg",
396 "a",
397 "--check-cfg 'cfg(verbose)",
398 "-L",
399 "/usr/lib/foo",
400 "-l",
401 "static:+whole-archive=mylib",
402 "--crate-type=dylib",
403 "--crate-name=foo",
404 "--edition=2021",
405 "--emit=asm",
406 "--print=crate-name",
407 "-g",
408 "-O",
409 "-o",
410 "foooutput",
411 "--out-dir",
412 "foooutdir",
413 "--target",
414 "aarch64-unknown-linux-gnu",
415 "-W",
416 "missing-docs",
417 "-D",
418 "unused-variables",
419 "--force-warn",
420 "dead-code",
421 "-A",
422 "unused",
423 "-F",
424 "unused",
425 "--cap-lints",
426 "warn",
427 "--version",
428 "--verbose",
429 "-v",
430 "--extern",
431 "foocrate",
432 "--sysroot",
433 "fooroot",
434 "--error-format",
435 "human",
436 "--color",
437 "auto",
438 "--diagnostic-width",
439 "80",
440 "--remap-path-prefix",
441 "foo=bar",
442 "--json=artifact",
443 // Codegen flags
444 "-Car",
445 "-Ccodegen-units=1",
446 "-Ccollapse-macro-debuginfo=yes",
447 "-Cdebug-assertions=yes",
448 "-Cdebuginfo=1",
449 "-Cdefault-linker-libraries=yes",
450 "-Cdlltool=foo",
451 "-Cextra-filename=foo",
452 "-Cforce-unwind-tables=yes",
453 "-Cincremental=foodir",
454 "-Cinline-threshold=6",
455 "-Cinstrument-coverage",
456 "-Clink-arg=-foo",
457 "-Clink-args=-foo",
458 "-Clink-self-contained=yes",
459 "-Clinker=lld",
460 "-Clinker-flavor=ld.lld",
461 "-Clinker-plugin-lto=yes",
462 "-Cllvm-args=foo",
463 "-Cmetadata=foo",
464 "-Cno-prepopulate-passes",
465 "-Cno-stack-check",
466 "-Copt-level=3",
467 "-Coverflow-checks=yes",
468 "-Cpanic=abort",
469 "-Cpasses=foopass",
470 "-Cprefer-dynamic=yes",
471 "-Crelro-level=partial",
472 "-Cremark=all",
473 "-Crpath=yes",
474 "-Csave-temps=yes",
475 "-Csplit-debuginfo=packed",
476 "-Cstrip=symbols",
477 "-Csymbol-mangling-version=v0",
478 "-Ctarget-cpu=native",
479 "-Ctarget-feature=+sve",
480 // Unstable options
481 "-Ztune-cpu=machine",
482 ];
483 check(
484 &flags.join("\u{1f}"),
485 &RustcCodegenFlags {
486 code_model: Some("tiny"),
487 control_flow_guard: Some("yes"),
488 embed_bitcode: Some(false),
489 force_frame_pointers: Some(true),
490 lto: Some("false"),
491 no_redzone: Some(true),
492 no_vectorize_loops: true,
493 no_vectorize_slp: true,
494 profile_generate: Some("fooprofile"),
495 profile_use: Some("fooprofile"),
496 relocation_model: Some("pic"),
497 soft_float: Some(true),
498 branch_protection: Some("bti,pac-ret,leaf"),
499 },
500 );
501 }
502 }