1//===- ForceFunctionAttrs.cpp - Force function attrs for debugging --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
10#include "IPOOptions.h"
11#include "llvm/IR/Function.h"
12#include "llvm/IR/Module.h"
13#include "llvm/Support/CommandLine.h"
14#include "llvm/Support/Debug.h"
15#include "llvm/Support/LineIterator.h"
16#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/Support/raw_ostream.h"
18using namespace llvm;
19
20#define DEBUG_TYPE "forceattrs"
21
22static cl::list<std::string> ForceAttributes(
23 "force-attribute", cl::Hidden,
24 cl::desc(
25 "Add an attribute to a function. This can be a "
26 "pair of 'function-name:attribute-name', to apply an attribute to a "
27 "specific function. For "
28 "example -force-attribute=foo:noinline. Specifying only an attribute "
29 "will apply the attribute to every function in the module. This "
30 "option can be specified multiple times."));
31
32static cl::list<std::string> ForceRemoveAttributes(
33 "force-remove-attribute", cl::Hidden,
34 cl::desc("Remove an attribute from a function. This can be a "
35 "pair of 'function-name:attribute-name' to remove an attribute "
36 "from a specific function. For "
37 "example -force-remove-attribute=foo:noinline. Specifying only an "
38 "attribute will remove the attribute from all functions in the "
39 "module. This "
40 "option can be specified multiple times."));
41
42static bool hasConflictingFnAttr(Attribute::AttrKind Kind, Function &F) {
43 switch (Kind) {
44 case Attribute::AlwaysInline:
45 return F.hasFnAttribute(Kind: Attribute::NoInline);
46
47 case Attribute::NoInline:
48 return F.hasFnAttribute(Kind: Attribute::AlwaysInline);
49
50 case Attribute::OptimizeNone:
51 return F.hasFnAttribute(Kind: Attribute::MinSize) ||
52 F.hasFnAttribute(Kind: Attribute::OptimizeForSize) ||
53 F.hasFnAttribute(Kind: Attribute::OptimizeForDebugging);
54
55 case Attribute::MinSize:
56 return F.hasFnAttribute(Kind: Attribute::OptimizeNone) ||
57 F.hasFnAttribute(Kind: Attribute::OptimizeForDebugging);
58
59 case Attribute::OptimizeForSize:
60 return F.hasFnAttribute(Kind: Attribute::OptimizeNone) ||
61 F.hasFnAttribute(Kind: Attribute::OptimizeForDebugging);
62
63 case Attribute::OptimizeForDebugging:
64 return F.hasFnAttribute(Kind: Attribute::OptimizeNone) ||
65 F.hasFnAttribute(Kind: Attribute::MinSize) ||
66 F.hasFnAttribute(Kind: Attribute::OptimizeForSize);
67
68 default:
69 return false;
70 }
71}
72
73/// If F has any forced attributes given on the command line, add them.
74/// If F has any forced remove attributes given on the command line, remove
75/// them. When both force and force-remove are given to a function, the latter
76/// takes precedence.
77static void forceAttributes(Function &F) {
78 auto ParseFunctionAndAttr = [&](StringRef S) {
79 StringRef AttributeText;
80 if (S.contains(C: ':')) {
81 auto KV = StringRef(S).split(Separator: ':');
82 if (KV.first != F.getName())
83 return Attribute::None;
84 AttributeText = KV.second;
85 } else {
86 AttributeText = S;
87 }
88 auto Kind = Attribute::getAttrKindFromName(AttrName: AttributeText);
89 if (Kind == Attribute::None || !Attribute::canUseAsFnAttr(Kind)) {
90 LLVM_DEBUG(dbgs() << "ForcedAttribute: " << AttributeText
91 << " unknown or not a function attribute!\n");
92 }
93 return Kind;
94 };
95
96 for (const auto &S : ForceAttributes) {
97 auto Kind = ParseFunctionAndAttr(S);
98 if (Kind == Attribute::None || F.hasFnAttribute(Kind) ||
99 hasConflictingFnAttr(Kind, F))
100 continue;
101 F.addFnAttr(Kind);
102 }
103
104 for (const auto &S : ForceRemoveAttributes) {
105 auto Kind = ParseFunctionAndAttr(S);
106 if (Kind == Attribute::None || !F.hasFnAttribute(Kind))
107 continue;
108 F.removeFnAttr(Kind);
109 }
110}
111
112static bool hasForceAttributes() {
113 return !ForceAttributes.empty() || !ForceRemoveAttributes.empty();
114}
115
116PreservedAnalyses ForceFunctionAttrsPass::run(Module &M,
117 ModuleAnalysisManager &) {
118 const IPOOptions &Opts = getIPOOptions(M);
119 bool Changed = false;
120 if (!Opts.forceattrs_csv_path.empty()) {
121 auto BufferOrError = MemoryBuffer::getFileOrSTDIN(Filename: Opts.forceattrs_csv_path);
122 if (!BufferOrError) {
123 std::error_code EC = BufferOrError.getError();
124 M.getContext().emitError(ErrorStr: "cannot open CSV file: " + EC.message());
125 return PreservedAnalyses::all();
126 }
127
128 StringRef Buffer = BufferOrError.get()->getBuffer();
129 auto MemoryBuffer = MemoryBuffer::getMemBuffer(InputData: Buffer);
130 line_iterator It(*MemoryBuffer);
131 for (; !It.is_at_end(); ++It) {
132 auto SplitPair = It->split(Separator: ',');
133 if (SplitPair.second.empty())
134 continue;
135 Function *Func = M.getFunction(Name: SplitPair.first);
136 if (Func) {
137 if (Func->isDeclaration())
138 continue;
139 auto SecondSplitPair = SplitPair.second.split(Separator: '=');
140 if (!SecondSplitPair.second.empty()) {
141 Func->addFnAttr(Kind: SecondSplitPair.first, Val: SecondSplitPair.second);
142 Changed = true;
143 } else {
144 auto AttrKind = Attribute::getAttrKindFromName(AttrName: SplitPair.second);
145 if (AttrKind != Attribute::None &&
146 Attribute::canUseAsFnAttr(Kind: AttrKind) &&
147 !hasConflictingFnAttr(Kind: AttrKind, F&: *Func)) {
148 // TODO: There could be string attributes without a value, we should
149 // support those, too.
150 Func->addFnAttr(Kind: AttrKind);
151 Changed = true;
152 } else
153 errs() << "Cannot add " << SplitPair.second
154 << " as an attribute name.\n";
155 }
156 } else {
157 errs() << "Function in CSV file at line " << It.line_number()
158 << " does not exist.\n";
159 // TODO: `report_fatal_error at end of pass for missing functions.
160 continue;
161 }
162 }
163 }
164 if (hasForceAttributes()) {
165 for (Function &F : M.functions())
166 forceAttributes(F);
167 Changed = true;
168 }
169 // Just conservatively invalidate analyses if we've made any changes, this
170 // isn't likely to be important.
171 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
172}
173