Skip to main content

cargo/core/compiler/
lto.rs

1use crate::core::compiler::{BuildContext, CompileMode, CrateType, Unit};
2use crate::core::profiles;
3use crate::util::interning::InternedString;
4use std::collections::hash_map::Entry;
5
6use crate::util::data_structures::HashMap;
7use crate::util::errors::CargoResult;
8
9/// Possible ways to run rustc and request various parts of [LTO].
10///
11/// Variant            | Flag                   | Object Code | Bitcode
12/// -------------------|------------------------|-------------|--------
13/// `Run`              | `-C lto=foo`           | n/a         | n/a
14/// `Off`              | `-C lto=off`           | n/a         | n/a
15/// `OnlyBitcode`      | `-C linker-plugin-lto` |             | ✓
16/// `ObjectAndBitcode` |                        | ✓           | ✓
17/// `OnlyObject`       | `-C embed-bitcode=no`  | ✓           |
18///
19/// [LTO]: https://doc.rust-lang.org/nightly/cargo/reference/profiles.html#lto
20#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
21pub enum Lto {
22    /// LTO is run for this rustc, and it's `-Clto=foo`. If the given value is
23    /// None, that corresponds to `-Clto` with no argument, which means do
24    /// "fat" LTO.
25    Run(Option<InternedString>),
26
27    /// LTO has been explicitly listed as "off". This means no thin-local-LTO,
28    /// no LTO anywhere, I really mean it!
29    Off,
30
31    /// This rustc invocation only needs to produce bitcode (it is *only* used
32    /// for LTO), there's no need to produce object files, so we can pass
33    /// `-Clinker-plugin-lto`
34    OnlyBitcode,
35
36    /// This rustc invocation needs to embed bitcode in object files. This means
37    /// that object files may be used for a normal link, and the crate may be
38    /// loaded for LTO later, so both are required.
39    ObjectAndBitcode,
40
41    /// This should not include bitcode. This is primarily to reduce disk
42    /// space usage.
43    OnlyObject,
44}
45
46pub fn generate(bcx: &BuildContext<'_, '_>) -> CargoResult<HashMap<Unit, Lto>> {
47    let mut map = HashMap::default();
48    for unit in bcx.roots.iter() {
49        let root_lto = match unit.profile.lto {
50            // LTO not requested, no need for bitcode.
51            profiles::Lto::Bool(false) => Lto::OnlyObject,
52            profiles::Lto::Off => Lto::Off,
53            _ => {
54                let crate_types = unit.target.rustc_crate_types();
55                if unit.target.for_host() {
56                    Lto::OnlyObject
57                } else if needs_object(&crate_types) {
58                    lto_when_needs_object(&crate_types)
59                } else {
60                    // This may or may not participate in LTO, let's start
61                    // with the minimum requirements. This may be expanded in
62                    // `calculate` below if necessary.
63                    Lto::OnlyBitcode
64                }
65            }
66        };
67        calculate(bcx, &mut map, unit, root_lto)?;
68    }
69    Ok(map)
70}
71
72/// Whether or not any of these crate types need object code.
73fn needs_object(crate_types: &[CrateType]) -> bool {
74    crate_types.iter().any(|k| k.can_lto() || k.is_dynamic())
75}
76
77/// Lto setting to use when this unit needs object code.
78fn lto_when_needs_object(crate_types: &[CrateType]) -> Lto {
79    if crate_types.iter().all(|ct| *ct == CrateType::Dylib) {
80        // A dylib whose parent is running LTO. rustc currently
81        // doesn't support LTO with dylibs, so bitcode is not
82        // needed.
83        Lto::OnlyObject
84    } else {
85        // Mixed rlib with a dylib or cdylib whose parent is running LTO. This
86        // needs both: bitcode for the rlib (for LTO) and object code for the
87        // dylib.
88        Lto::ObjectAndBitcode
89    }
90}
91
92fn calculate(
93    bcx: &BuildContext<'_, '_>,
94    map: &mut HashMap<Unit, Lto>,
95    unit: &Unit,
96    parent_lto: Lto,
97) -> CargoResult<()> {
98    let crate_types = match unit.mode {
99        // Note: Doctest ignores LTO, but for now we'll compute it as-if it is
100        // a Bin, in case it is ever supported in the future.
101        CompileMode::Test | CompileMode::Doctest => vec![CrateType::Bin],
102        // Notes on other modes:
103        // - Check: Treat as the underlying type, it doesn't really matter.
104        // - Doc: LTO is N/A for the Doc unit itself since rustdoc does not
105        //   support codegen flags. We still compute the dependencies, which
106        //   are mostly `Check`.
107        // - RunCustomBuild is ignored because it is always "for_host".
108        _ => unit.target.rustc_crate_types(),
109    };
110    // LTO can only be performed if *all* of the crate types support it.
111    // For example, a cdylib/rlib combination won't allow LTO.
112    let all_lto_types = crate_types.iter().all(CrateType::can_lto);
113    // Compute the LTO based on the profile, and what our parent requires.
114    let lto = if unit.target.for_host() {
115        // Disable LTO for host builds since we only really want to perform LTO
116        // for the final binary, and LTO on plugins/build scripts/proc macros is
117        // largely not desired.
118        Lto::OnlyObject
119    } else if all_lto_types {
120        // Note that this ignores the `parent_lto` because this isn't a
121        // linkable crate type; this unit is not being embedded in the parent.
122        match unit.profile.lto {
123            profiles::Lto::Named(s) => Lto::Run(Some(s)),
124            profiles::Lto::Off => Lto::Off,
125            profiles::Lto::Bool(true) => Lto::Run(None),
126            profiles::Lto::Bool(false) => Lto::OnlyObject,
127        }
128    } else {
129        match (parent_lto, needs_object(&crate_types)) {
130            // An rlib whose parent is running LTO, we only need bitcode.
131            (Lto::Run(_), false) => Lto::OnlyBitcode,
132            // LTO when something needs object code.
133            (Lto::Run(_), true) | (Lto::OnlyBitcode, true) => lto_when_needs_object(&crate_types),
134            // LTO is disabled, continue to disable it.
135            (Lto::Off, _) => Lto::Off,
136            // If this doesn't have any requirements, or the requirements are
137            // already satisfied, then stay with our parent.
138            (_, false) | (Lto::OnlyObject, true) | (Lto::ObjectAndBitcode, true) => parent_lto,
139        }
140    };
141
142    // Merge the computed LTO. If this unit appears multiple times in the
143    // graph, the merge may expand the requirements.
144    let merged_lto = match map.entry(unit.clone()) {
145        // If we haven't seen this unit before then insert our value and keep
146        // going.
147        Entry::Vacant(v) => *v.insert(lto),
148
149        Entry::Occupied(mut v) => {
150            let result = match (lto, v.get()) {
151                // No change in requirements.
152                (Lto::OnlyBitcode, Lto::OnlyBitcode) => Lto::OnlyBitcode,
153                (Lto::OnlyObject, Lto::OnlyObject) => Lto::OnlyObject,
154
155                // Once we're running LTO we keep running LTO. We should always
156                // calculate the same thing here each iteration because if we
157                // see this twice then it means, for example, two unit tests
158                // depend on a binary, which is normal.
159                (Lto::Run(s), _) | (_, &Lto::Run(s)) => Lto::Run(s),
160
161                // Off means off! This has the same reasoning as `Lto::Run`.
162                (Lto::Off, _) | (_, Lto::Off) => Lto::Off,
163
164                // Once a target has requested both, that's the maximal amount
165                // of work that can be done, so we just keep doing that work.
166                (Lto::ObjectAndBitcode, _) | (_, Lto::ObjectAndBitcode) => Lto::ObjectAndBitcode,
167
168                // Upgrade so that both requirements can be met.
169                //
170                // This is where the trickiness happens. This unit needs
171                // bitcode and the previously calculated value for this unit
172                // says it didn't need bitcode (or vice versa). This means that
173                // we're a shared dependency between some targets which require
174                // LTO and some which don't. This means that instead of being
175                // either only-objects or only-bitcode we have to embed both in
176                // rlibs (used for different compilations), so we switch to
177                // including both.
178                (Lto::OnlyObject, Lto::OnlyBitcode) | (Lto::OnlyBitcode, Lto::OnlyObject) => {
179                    Lto::ObjectAndBitcode
180                }
181            };
182            // No need to recurse if we calculated the same value as before.
183            if result == *v.get() {
184                return Ok(());
185            }
186            v.insert(result);
187            result
188        }
189    };
190
191    for dep in &bcx.unit_graph[unit] {
192        calculate(bcx, map, &dep.unit, merged_lto)?;
193    }
194    Ok(())
195}