1// Copyright 2022 The Android Open Source Project
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
15package rust
16
17import (
18	"fmt"
19
20	"android/soong/android"
21	"android/soong/cc"
22
23	"github.com/google/blueprint"
24)
25
26const afdoFlagFormat = "-Zprofile-sample-use=%s"
27
28type afdo struct {
29	Properties cc.AfdoProperties
30}
31
32func (afdo *afdo) props() []interface{} {
33	return []interface{}{&afdo.Properties}
34}
35
36func (afdo *afdo) addDep(ctx BaseModuleContext, actx android.BottomUpMutatorContext) {
37	// afdo is not supported outside of Android
38	if ctx.Host() {
39		return
40	}
41
42	if mod, ok := ctx.Module().(*Module); ok && mod.Enabled(ctx) {
43		fdoProfileName, err := actx.DeviceConfig().AfdoProfile(actx.ModuleName())
44		if err != nil {
45			ctx.ModuleErrorf("%s", err.Error())
46		}
47		if fdoProfileName != "" {
48			actx.AddFarVariationDependencies(
49				[]blueprint.Variation{
50					{Mutator: "arch", Variation: actx.Target().ArchVariation()},
51					{Mutator: "os", Variation: "android"},
52				},
53				cc.FdoProfileTag,
54				[]string{fdoProfileName}...,
55			)
56		}
57	}
58}
59
60func (afdo *afdo) flags(ctx android.ModuleContext, flags Flags, deps PathDeps) (Flags, PathDeps) {
61	if ctx.Host() {
62		return flags, deps
63	}
64
65	if !afdo.Properties.Afdo {
66		return flags, deps
67	}
68
69	ctx.VisitDirectDepsWithTag(cc.FdoProfileTag, func(m android.Module) {
70		if info, ok := android.OtherModuleProvider(ctx, m, cc.FdoProfileProvider); ok {
71			path := info.Path
72			profileUseFlag := fmt.Sprintf(afdoFlagFormat, path.String())
73			flags.RustFlags = append(flags.RustFlags, profileUseFlag)
74
75			deps.AfdoProfiles = append(deps.AfdoProfiles, path)
76		}
77	})
78
79	return flags, deps
80}
81