bcc_strip_attr.cpp revision bfa9fc93c88510184399bb98e0faa8cc474061fb
1/*
2 * Copyright 2013, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "llvm/Analysis/Verifier.h"
18#include "llvm/Bitcode/ReaderWriter.h"
19#include "llvm/IR/LLVMContext.h"
20#include "llvm/IR/Module.h"
21#include "llvm/Pass.h"
22#include "llvm/PassManager.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/IRReader.h"
25#include "llvm/Support/ManagedStatic.h"
26#include "llvm/Support/PrettyStackTrace.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/SystemUtils.h"
29#include "llvm/Support/ToolOutputFile.h"
30using namespace llvm;
31
32static cl::list<std::string>
33InputFilenames(cl::Positional,
34               cl::desc("<input bitcode files>"));
35
36static cl::opt<std::string>
37OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
38               cl::value_desc("filename"));
39
40static cl::opt<bool>
41OutputAssembly("S",
42               cl::desc("Write output as LLVM assembly"), cl::Hidden);
43
44namespace {
45  class StripAttributes : public ModulePass {
46  public:
47    static char ID;
48
49    StripAttributes() : ModulePass(ID) {
50    }
51
52    bool runOnFunction(Function &F) {
53      // Remove any target-cpu and/or target-features attributes from each
54      // Function or Function declaration.
55      if (F.hasFnAttribute("target-cpu") ||
56          F.hasFnAttribute("target-features")) {
57
58        AttrBuilder B;
59        B.addAttribute("target-cpu").addAttribute("target-features");
60        AttributeSet ToStrip = AttributeSet::get(F.getContext(),
61            AttributeSet::FunctionIndex, B);
62        F.removeAttributes(AttributeSet::FunctionIndex, ToStrip);
63        return true;
64      }
65      return false;
66    }
67
68    // We have to use a ModulePass, since a FunctionPass only gets run on
69    // defined Functions (and not declared Functions).
70    virtual bool runOnModule(Module &M) {
71      bool Changed = false;
72      for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
73        Changed |= runOnFunction(*I);
74      }
75      return Changed;
76    }
77  };
78
79  llvm::ModulePass * createStripAttributePass() {
80    return new StripAttributes();
81  }
82}
83
84
85char StripAttributes::ID = 0;
86static RegisterPass<StripAttributes> RPSA("StripAttributes",
87    "Strip Function Attributes Pass");
88
89
90static inline std::auto_ptr<Module> LoadFile(const char *argv0,
91                                             const std::string &FN,
92                                             LLVMContext& Context) {
93  sys::Path Filename;
94  if (!Filename.set(FN)) {
95    errs() << "Invalid file name: '" << FN << "'\n";
96    return std::auto_ptr<Module>();
97  }
98
99  SMDiagnostic Err;
100  Module* Result = 0;
101
102  const std::string &FNStr = Filename.str();
103  Result = ParseIRFile(FNStr, Err, Context);
104  if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
105
106  Err.print(argv0, errs());
107  return std::auto_ptr<Module>();
108}
109
110
111int main(int argc, char **argv) {
112  // Print a stack trace if we signal out.
113  sys::PrintStackTraceOnErrorSignal();
114  PrettyStackTraceProgram X(argc, argv);
115
116  LLVMContext &Context = getGlobalContext();
117  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
118  cl::ParseCommandLineOptions(argc, argv, "strip function attribute pass\n");
119
120  std::string ErrorMessage;
121
122  std::auto_ptr<Module> M(LoadFile(argv[0], InputFilenames[0], Context));
123  if (M.get() == 0) {
124    errs() << argv[0] << ": error loading file '"
125           << InputFilenames[0] << "'\n";
126    return 1;
127  }
128
129  // Perform the actual function attribute stripping.
130  PassManager PM;
131  PM.add(createStripAttributePass());
132  PM.run(*M.get());
133
134  std::string ErrorInfo;
135  tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
136                       raw_fd_ostream::F_Binary);
137  if (!ErrorInfo.empty()) {
138    errs() << ErrorInfo << '\n';
139    return 1;
140  }
141
142  if (verifyModule(*M)) {
143    errs() << argv[0] << ": stripped module is broken!\n";
144    return 1;
145  }
146
147  if (OutputAssembly) {
148    Out.os() << *M;
149  } else if (!CheckBitcodeOutputToConsole(Out.os(), true)) {
150    WriteBitcodeToFile(M.get(), Out.os());
151  }
152
153  Out.keep();
154
155  return 0;
156}
157