1 //===- SymbolRewriter.cpp - Symbol Rewriter ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // SymbolRewriter is a LLVM pass which can rewrite symbols transparently within
11 // existing code. It is implemented as a compiler pass and is configured via a
12 // YAML configuration file.
14 // The YAML configuration file format is as follows:
16 // RewriteMapFile := RewriteDescriptors
17 // RewriteDescriptors := RewriteDescriptor | RewriteDescriptors
18 // RewriteDescriptor := RewriteDescriptorType ':' '{' RewriteDescriptorFields '}'
19 // RewriteDescriptorFields := RewriteDescriptorField | RewriteDescriptorFields
20 // RewriteDescriptorField := FieldIdentifier ':' FieldValue ','
21 // RewriteDescriptorType := Identifier
22 // FieldIdentifier := Identifier
23 // FieldValue := Identifier
24 // Identifier := [0-9a-zA-Z]+
26 // Currently, the following descriptor types are supported:
28 // - function: (function rewriting)
29 // + Source (original name of the function)
30 // + Target (explicit transformation)
31 // + Transform (pattern transformation)
32 // + Naked (boolean, whether the function is undecorated)
33 // - global variable: (external linkage global variable rewriting)
34 // + Source (original name of externally visible variable)
35 // + Target (explicit transformation)
36 // + Transform (pattern transformation)
37 // - global alias: (global alias rewriting)
38 // + Source (original name of the aliased name)
39 // + Target (explicit transformation)
40 // + Transform (pattern transformation)
42 // Note that source and exactly one of [Target, Transform] must be provided
44 // New rewrite descriptors can be created. Addding a new rewrite descriptor
47 // a) extended the rewrite descriptor kind enumeration
48 // (<anonymous>::RewriteDescriptor::RewriteDescriptorType)
49 // b) implementing the new descriptor
50 // (c.f. <anonymous>::ExplicitRewriteFunctionDescriptor)
51 // c) extending the rewrite map parser
52 // (<anonymous>::RewriteMapParser::parseEntry)
54 // Specify to rewrite the symbols using the `-rewrite-symbols` option, and
55 // specify the map file to use for the rewriting via the `-rewrite-map-file`
58 //===----------------------------------------------------------------------===//
60 #define DEBUG_TYPE "symbol-rewriter"
61 #include "llvm/CodeGen/Passes.h"
62 #include "llvm/Pass.h"
63 #include "llvm/PassManager.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/Regex.h"
68 #include "llvm/Support/SourceMgr.h"
69 #include "llvm/Support/YAMLParser.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
72 #include "llvm/Transforms/Utils/SymbolRewriter.h"
76 static cl::list<std::string> RewriteMapFiles("rewrite-map-file",
77 cl::desc("Symbol Rewrite Map"),
78 cl::value_desc("filename"));
81 namespace SymbolRewriter {
82 template <RewriteDescriptor::Type DT, typename ValueType,
83 ValueType *(llvm::Module::*Get)(StringRef) const>
84 class ExplicitRewriteDescriptor : public RewriteDescriptor {
86 const std::string Source;
87 const std::string Target;
89 ExplicitRewriteDescriptor(StringRef S, StringRef T, const bool Naked)
90 : RewriteDescriptor(DT), Source(Naked ? StringRef("\01" + S.str()) : S),
93 bool performOnModule(Module &M) override;
95 static bool classof(const RewriteDescriptor *RD) {
96 return RD->getType() == DT;
100 template <RewriteDescriptor::Type DT, typename ValueType,
101 ValueType *(llvm::Module::*Get)(StringRef) const>
102 bool ExplicitRewriteDescriptor<DT, ValueType, Get>::performOnModule(Module &M) {
103 bool Changed = false;
104 if (ValueType *S = (M.*Get)(Source)) {
105 if (Value *T = (M.*Get)(Target))
106 S->setValueName(T->getValueName());
114 template <RewriteDescriptor::Type DT, typename ValueType,
115 ValueType *(llvm::Module::*Get)(StringRef) const,
116 iterator_range<typename iplist<ValueType>::iterator> (llvm::Module::*Iterator)()>
117 class PatternRewriteDescriptor : public RewriteDescriptor {
119 const std::string Pattern;
120 const std::string Transform;
122 PatternRewriteDescriptor(StringRef P, StringRef T)
123 : RewriteDescriptor(DT), Pattern(P), Transform(T) { }
125 bool performOnModule(Module &M) override;
127 static bool classof(const RewriteDescriptor *RD) {
128 return RD->getType() == DT;
132 template <RewriteDescriptor::Type DT, typename ValueType,
133 ValueType *(llvm::Module::*Get)(StringRef) const,
134 iterator_range<typename iplist<ValueType>::iterator> (llvm::Module::*Iterator)()>
135 bool PatternRewriteDescriptor<DT, ValueType, Get, Iterator>::
136 performOnModule(Module &M) {
137 bool Changed = false;
138 for (auto &C : (M.*Iterator)()) {
141 std::string Name = Regex(Pattern).sub(Transform, C.getName(), &Error);
143 report_fatal_error("unable to transforn " + C.getName() + " in " +
144 M.getModuleIdentifier() + ": " + Error);
146 if (Value *V = (M.*Get)(Name))
147 C.setValueName(V->getValueName());
156 /// Represents a rewrite for an explicitly named (function) symbol. Both the
157 /// source function name and target function name of the transformation are
158 /// explicitly spelt out.
159 using ExplicitRewriteFunctionDescriptor =
160 ExplicitRewriteDescriptor<RewriteDescriptor::Type::Function, llvm::Function,
161 &llvm::Module::getFunction>;
163 /// Represents a rewrite for an explicitly named (global variable) symbol. Both
164 /// the source variable name and target variable name are spelt out. This
165 /// applies only to module level variables.
166 using ExplicitRewriteGlobalVariableDescriptor =
167 ExplicitRewriteDescriptor<RewriteDescriptor::Type::GlobalVariable,
168 llvm::GlobalVariable,
169 &llvm::Module::getGlobalVariable>;
171 /// Represents a rewrite for an explicitly named global alias. Both the source
172 /// and target name are explicitly spelt out.
173 using ExplicitRewriteNamedAliasDescriptor =
174 ExplicitRewriteDescriptor<RewriteDescriptor::Type::NamedAlias,
175 llvm::GlobalAlias, &llvm::Module::getNamedAlias>;
177 /// Represents a rewrite for a regular expression based pattern for functions.
178 /// A pattern for the function name is provided and a transformation for that
179 /// pattern to determine the target function name create the rewrite rule.
180 using PatternRewriteFunctionDescriptor =
181 PatternRewriteDescriptor<RewriteDescriptor::Type::Function, llvm::Function,
182 &llvm::Module::getFunction,
183 &llvm::Module::functions>;
186 /// Represents a rewrite for a global variable based upon a matching pattern.
187 /// Each global variable matching the provided pattern will be transformed as
188 /// described in the transformation pattern for the target. Applies only to
189 /// module level variables.
190 using PatternRewriteGlobalVariableDescriptor =
191 PatternRewriteDescriptor<RewriteDescriptor::Type::GlobalVariable,
192 llvm::GlobalVariable,
193 &llvm::Module::getGlobalVariable,
194 &llvm::Module::globals>;
196 /// PatternRewriteNamedAliasDescriptor - represents a rewrite for global
197 /// aliases which match a given pattern. The provided transformation will be
198 /// applied to each of the matching names.
199 using PatternRewriteNamedAliasDescriptor =
200 PatternRewriteDescriptor<RewriteDescriptor::Type::NamedAlias,
202 &llvm::Module::getNamedAlias,
203 &llvm::Module::aliases>;
206 bool RewriteMapParser::parse(const std::string &MapFile,
207 RewriteDescriptorList *DL) {
208 ErrorOr<std::unique_ptr<MemoryBuffer>> Mapping =
209 MemoryBuffer::getFile(MapFile);
212 report_fatal_error("unable to read rewrite map '" + MapFile + "': " +
213 Mapping.getError().message());
215 if (!parse(*Mapping, DL))
216 report_fatal_error("unable to parse rewrite map '" + MapFile + "'");
221 bool RewriteMapParser::parse(std::unique_ptr<MemoryBuffer> &MapFile,
222 RewriteDescriptorList *DL) {
224 yaml::Stream YS(MapFile->getBuffer(), SM);
226 for (auto &Document : YS) {
227 yaml::MappingNode *DescriptorList;
229 // ignore empty documents
230 if (isa<yaml::NullNode>(Document.getRoot()))
233 DescriptorList = dyn_cast<yaml::MappingNode>(Document.getRoot());
234 if (!DescriptorList) {
235 YS.printError(Document.getRoot(), "DescriptorList node must be a map");
239 for (auto &Descriptor : *DescriptorList)
240 if (!parseEntry(YS, Descriptor, DL))
247 bool RewriteMapParser::parseEntry(yaml::Stream &YS, yaml::KeyValueNode &Entry,
248 RewriteDescriptorList *DL) {
249 const std::string kRewriteTypeFunction = "function";
250 const std::string kRewriteTypeGlobalVariable = "global variable";
251 const std::string kRewriteTypeGlobalAlias = "global alias";
253 yaml::ScalarNode *Key;
254 yaml::MappingNode *Value;
255 SmallString<32> KeyStorage;
256 StringRef RewriteType;
258 Key = dyn_cast<yaml::ScalarNode>(Entry.getKey());
260 YS.printError(Entry.getKey(), "rewrite type must be a scalar");
264 Value = dyn_cast<yaml::MappingNode>(Entry.getValue());
266 YS.printError(Entry.getValue(), "rewrite descriptor must be a map");
270 RewriteType = Key->getValue(KeyStorage);
271 if (RewriteType == kRewriteTypeFunction)
272 return parseRewriteFunctionDescriptor(YS, Key, Value, DL);
273 else if (RewriteType == kRewriteTypeGlobalVariable)
274 return parseRewriteGlobalVariableDescriptor(YS, Key, Value, DL);
275 else if (RewriteType == kRewriteTypeGlobalAlias)
276 return parseRewriteGlobalAliasDescriptor(YS, Key, Value, DL);
278 YS.printError(Entry.getKey(), "unknown rewrite type");
282 bool RewriteMapParser::
283 parseRewriteFunctionDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
284 yaml::MappingNode *Descriptor,
285 RewriteDescriptorList *DL) {
286 const std::string kDescriptorFieldSource = "source";
287 const std::string kDescriptorFieldTarget = "target";
288 const std::string kDescriptorFieldTransform = "transform";
289 const std::string kDescriptorFieldNaked = "naked";
294 std::string Transform;
296 for (auto &Field : *Descriptor) {
297 yaml::ScalarNode *Key;
298 yaml::ScalarNode *Value;
299 SmallString<32> KeyStorage;
300 SmallString<32> ValueStorage;
303 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
305 YS.printError(Field.getKey(), "descriptor key must be a scalar");
309 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
311 YS.printError(Field.getValue(), "descriptor value must be a scalar");
315 KeyValue = Key->getValue(KeyStorage);
316 if (KeyValue == kDescriptorFieldSource) {
319 Source = Value->getValue(ValueStorage);
320 if (!Regex(Source).isValid(Error)) {
321 YS.printError(Field.getKey(), "invalid regex: " + Error);
324 } else if (KeyValue == kDescriptorFieldTarget) {
325 Target = Value->getValue(ValueStorage);
326 } else if (KeyValue == kDescriptorFieldTransform) {
327 Transform = Value->getValue(ValueStorage);
328 } else if (KeyValue == kDescriptorFieldNaked) {
329 std::string Undecorated;
331 Undecorated = Value->getValue(ValueStorage);
332 Naked = StringRef(Undecorated).lower() == "true" || Undecorated == "1";
334 YS.printError(Field.getKey(), "unknown key for function");
339 if (Transform.empty() == Target.empty()) {
340 YS.printError(Descriptor,
341 "exactly one of transform or target must be specified");
345 // TODO see if there is a more elegant solution to selecting the rewrite
348 DL->push_back(new ExplicitRewriteFunctionDescriptor(Source, Target, Naked));
350 DL->push_back(new PatternRewriteFunctionDescriptor(Source, Transform));
355 bool RewriteMapParser::
356 parseRewriteGlobalVariableDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
357 yaml::MappingNode *Descriptor,
358 RewriteDescriptorList *DL) {
359 const std::string kDescriptorFieldSource = "source";
360 const std::string kDescriptorFieldTarget = "target";
361 const std::string kDescriptorFieldTransform = "transform";
365 std::string Transform;
367 for (auto &Field : *Descriptor) {
368 yaml::ScalarNode *Key;
369 yaml::ScalarNode *Value;
370 SmallString<32> KeyStorage;
371 SmallString<32> ValueStorage;
374 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
376 YS.printError(Field.getKey(), "descriptor Key must be a scalar");
380 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
382 YS.printError(Field.getValue(), "descriptor value must be a scalar");
386 KeyValue = Key->getValue(KeyStorage);
387 if (KeyValue == kDescriptorFieldSource) {
390 Source = Value->getValue(ValueStorage);
391 if (!Regex(Source).isValid(Error)) {
392 YS.printError(Field.getKey(), "invalid regex: " + Error);
395 } else if (KeyValue == kDescriptorFieldTarget) {
396 Target = Value->getValue(ValueStorage);
397 } else if (KeyValue == kDescriptorFieldTransform) {
398 Transform = Value->getValue(ValueStorage);
400 YS.printError(Field.getKey(), "unknown Key for Global Variable");
405 if (Transform.empty() == Target.empty()) {
406 YS.printError(Descriptor,
407 "exactly one of transform or target must be specified");
412 DL->push_back(new ExplicitRewriteGlobalVariableDescriptor(Source, Target,
415 DL->push_back(new PatternRewriteGlobalVariableDescriptor(Source,
421 bool RewriteMapParser::
422 parseRewriteGlobalAliasDescriptor(yaml::Stream &YS, yaml::ScalarNode *K,
423 yaml::MappingNode *Descriptor,
424 RewriteDescriptorList *DL) {
425 const std::string kDescriptorFieldSource = "source";
426 const std::string kDescriptorFieldTarget = "target";
427 const std::string kDescriptorFieldTransform = "transform";
431 std::string Transform;
433 for (auto &Field : *Descriptor) {
434 yaml::ScalarNode *Key;
435 yaml::ScalarNode *Value;
436 SmallString<32> KeyStorage;
437 SmallString<32> ValueStorage;
440 Key = dyn_cast<yaml::ScalarNode>(Field.getKey());
442 YS.printError(Field.getKey(), "descriptor key must be a scalar");
446 Value = dyn_cast<yaml::ScalarNode>(Field.getValue());
448 YS.printError(Field.getValue(), "descriptor value must be a scalar");
452 KeyValue = Key->getValue(KeyStorage);
453 if (KeyValue == kDescriptorFieldSource) {
456 Source = Value->getValue(ValueStorage);
457 if (!Regex(Source).isValid(Error)) {
458 YS.printError(Field.getKey(), "invalid regex: " + Error);
461 } else if (KeyValue == kDescriptorFieldTarget) {
462 Target = Value->getValue(ValueStorage);
463 } else if (KeyValue == kDescriptorFieldTransform) {
464 Transform = Value->getValue(ValueStorage);
466 YS.printError(Field.getKey(), "unknown key for Global Alias");
471 if (Transform.empty() == Target.empty()) {
472 YS.printError(Descriptor,
473 "exactly one of transform or target must be specified");
478 DL->push_back(new ExplicitRewriteNamedAliasDescriptor(Source, Target,
481 DL->push_back(new PatternRewriteNamedAliasDescriptor(Source, Transform));
489 class RewriteSymbols : public ModulePass {
491 static char ID; // Pass identification, replacement for typeid
494 RewriteSymbols(SymbolRewriter::RewriteDescriptorList &DL);
496 virtual bool runOnModule(Module &M) override;
499 void loadAndParseMapFiles();
501 SymbolRewriter::RewriteDescriptorList Descriptors;
504 char RewriteSymbols::ID = 0;
506 RewriteSymbols::RewriteSymbols() : ModulePass(ID) {
507 initializeRewriteSymbolsPass(*PassRegistry::getPassRegistry());
508 loadAndParseMapFiles();
511 RewriteSymbols::RewriteSymbols(SymbolRewriter::RewriteDescriptorList &DL)
513 std::swap(Descriptors, DL);
516 bool RewriteSymbols::runOnModule(Module &M) {
520 for (auto &Descriptor : Descriptors)
521 Changed |= Descriptor.performOnModule(M);
526 void RewriteSymbols::loadAndParseMapFiles() {
527 const std::vector<std::string> MapFiles(RewriteMapFiles);
528 SymbolRewriter::RewriteMapParser parser;
530 for (const auto &MapFile : MapFiles)
531 parser.parse(MapFile, &Descriptors);
535 INITIALIZE_PASS(RewriteSymbols, "rewrite-symbols", "Rewrite Symbols", false,
538 ModulePass *llvm::createRewriteSymbolsPass() { return new RewriteSymbols(); }
541 llvm::createRewriteSymbolsPass(SymbolRewriter::RewriteDescriptorList &DL) {
542 return new RewriteSymbols(DL);