1 /* 2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd. 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 */ 15 16 #ifndef LIBLLVMBACKEND_MIR_COMPILER_H 17 #define LIBLLVMBACKEND_MIR_COMPILER_H 18 19 #include <unordered_map> 20 21 #include <llvm/IR/LegacyPassManager.h> 22 #include <llvm/Pass.h> 23 #include <llvm/Target/TargetMachine.h> 24 25 #include "object_code/created_object_file.h" 26 27 namespace ark::llvmbackend { 28 29 class InsertingPassManager : public llvm::legacy::PassManager { 30 public: 31 void add(llvm::Pass *p) override; 32 InsertBefore(llvm::AnalysisID before,llvm::Pass * pass)33 void InsertBefore(llvm::AnalysisID before, llvm::Pass *pass) 34 { 35 befores_[before] = pass; 36 } 37 38 private: 39 std::unordered_map<llvm::AnalysisID, llvm::Pass *> befores_; 40 }; 41 42 class MIRCompiler { 43 public: 44 using PassInserterFunction = std::function<void(InsertingPassManager *manager)>; 45 46 // Construct a compile functor with the given target builder. MIRCompiler(const std::unique_ptr<llvm::TargetMachine> & targetMachine,PassInserterFunction insertPasses)47 explicit MIRCompiler(const std::unique_ptr<llvm::TargetMachine> &targetMachine, PassInserterFunction insertPasses) 48 : targetMachine_(std::move(targetMachine)), insertPasses_(std::move(insertPasses)) 49 { 50 } 51 52 // Compile a Module to an ObjectFile. 53 llvm::Expected<std::unique_ptr<CreatedObjectFile>> CompileModule(llvm::Module &module); 54 GetTargetMachine()55 const std::unique_ptr<llvm::TargetMachine> &GetTargetMachine() 56 { 57 return targetMachine_; 58 } 59 60 private: 61 const std::unique_ptr<llvm::TargetMachine> &targetMachine_; 62 PassInserterFunction insertPasses_; 63 }; 64 65 } // namespace ark::llvmbackend 66 67 #endif // LIBLLVMBACKEND_MIR_COMPILER_H 68