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