From 62597c33d89c967f7d4a4255699cd12a91b42a91 Mon Sep 17 00:00:00 2001 From: Mingchuan Wu Date: Tue, 7 Feb 2023 19:38:52 +0800 Subject: [PATCH 4/9] [Refactoring] Code refactoring of Communication Subsystem [3/3]. Code refactoring of communication subsystem. diff --git a/CMakeLists.txt b/CMakeLists.txt index d688fdf..fcd737b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -89,9 +89,12 @@ add_subdirectory(include) add_subdirectory(lib) add_library(pin_gcc_client SHARED + "lib/gccPlugin/gccPlugin.cpp" "lib/PluginClient/PluginLog.cpp" + "lib/PluginClient/PluginJson.cpp" + "lib/PluginClient/PluginInputCheck.cpp" + "lib/PluginClient/PluginGrpcPort.cpp" "lib/PluginClient/PluginClient.cpp" - "lib/IRTrans/IRTransPlugin.cpp" ) target_link_libraries(pin_gcc_client diff --git a/configs/pin-gcc-client.json b/configs/pin-gcc-client.json index 390f8bf..bd0ff0c 100755 --- a/configs/pin-gcc-client.json +++ b/configs/pin-gcc-client.json @@ -1,10 +1,10 @@ { - //server路径 + "//" : "server路径", "path" : "/usr/local/bin/pin_server", - //libuser.so sha256文件名 + "//" : "libuser.so sha256文件名", "sha256file" : "/usr/local/lib/libpin_user.sha256", - //超时时间,单位ms - "timeout" : 200, + "//" : "超时时间,单位ms", + "timeout" : 200 } \ No newline at end of file diff --git a/include/Dialect/PluginDialect.h b/include/Dialect/PluginDialect.h index c5d3ad8..8cdb593 100644 --- a/include/Dialect/PluginDialect.h +++ b/include/Dialect/PluginDialect.h @@ -16,11 +16,11 @@ */ -//===----------------------------------------------------------------------===// -// +// ===----------------------------------------------------------------------===// +// // This is the header file for the Plugin dialect. // -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// #ifndef PLUGIN_DIALECT_H #define PLUGIN_DIALECT_H diff --git a/include/Dialect/PluginOps.h b/include/Dialect/PluginOps.h index 25089fe..a2fb310 100644 --- a/include/Dialect/PluginOps.h +++ b/include/Dialect/PluginOps.h @@ -16,11 +16,11 @@ */ -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // -// This is the header file for operations in Plugin dialect. +// This is the header file for operations in Plugin dialect. // -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// #ifndef Plugin_OPS_H #define Plugin_OPS_H diff --git a/include/Dialect/PluginTypes.h b/include/Dialect/PluginTypes.h index 60ba258..157b868 100644 --- a/include/Dialect/PluginTypes.h +++ b/include/Dialect/PluginTypes.h @@ -74,13 +74,13 @@ private: unsigned size; }; // class PluginTypeBase -namespace detail { +namespace Detail { struct PluginIntegerTypeStorage; struct PluginFloatTypeStorage; struct PluginPointerTypeStorage; } -class PluginIntegerType : public Type::TypeBase { +class PluginIntegerType : public Type::TypeBase { public: using Base::Base; @@ -104,7 +104,7 @@ public: SignednessSemantics getSignedness() const; }; -class PluginFloatType : public Type::TypeBase { +class PluginFloatType : public Type::TypeBase { public: using Base::Base; @@ -115,7 +115,7 @@ public: unsigned getWidth() const; }; -class PluginPointerType : public Type::TypeBase { +class PluginPointerType : public Type::TypeBase { public: using Base::Base; @@ -133,7 +133,6 @@ public: using Base::Base; PluginTypeID getPluginTypeID (); - }; // class PluginVoidType class PluginUndefType : public Type::TypeBase { @@ -141,7 +140,6 @@ public: using Base::Base; PluginTypeID getPluginTypeID (); - }; // class PluginUndefType class PluginBooleanType : public Type::TypeBase { @@ -149,7 +147,6 @@ public: using Base::Base; PluginTypeID getPluginTypeID (); - }; // class PluginBooleanType } // namespace PluginIR diff --git a/include/PluginAPI/BasicPluginOpsAPI.h b/include/PluginAPI/BasicPluginOpsAPI.h index 5eb1eed..8c47c58 100644 --- a/include/PluginAPI/BasicPluginOpsAPI.h +++ b/include/PluginAPI/BasicPluginOpsAPI.h @@ -43,6 +43,12 @@ public: BasicPluginOpsAPI() = default; virtual ~BasicPluginOpsAPI() = default; + virtual string GetDeclSourceFile(uint64_t gccDataAddr) = 0; + virtual string VariableName(int64_t gccDataAddr) = 0; + virtual string FuncName(int64_t gccDataAddr) = 0; + virtual int GetDeclSourceLine(uint64_t gccDataAddr) = 0; + virtual int GetDeclSourceColumn(uint64_t gccDataAddr) = 0; + virtual uint64_t CreateBlock(uint64_t, uint64_t) = 0; virtual void DeleteBlock(uint64_t, uint64_t) = 0; virtual void SetImmediateDominator(uint64_t, uint64_t, uint64_t) = 0; diff --git a/include/PluginAPI/PluginClientAPI.h b/include/PluginAPI/PluginClientAPI.h index cb81986..07d6e52 100644 --- a/include/PluginAPI/PluginClientAPI.h +++ b/include/PluginAPI/PluginClientAPI.h @@ -33,6 +33,12 @@ public: PluginClientAPI () = default; ~PluginClientAPI () = default; + string GetDeclSourceFile(uint64_t gccDataAddr) override; + string VariableName(int64_t gccDataAddr) override; + string FuncName(int64_t gccDataAddr) override; + int GetDeclSourceLine(uint64_t gccDataAddr) override; + int GetDeclSourceColumn(uint64_t gccDataAddr) override; + uint64_t CreateBlock(uint64_t, uint64_t) override; void DeleteBlock(uint64_t, uint64_t) override; void SetImmediateDominator(uint64_t, uint64_t, uint64_t) override; diff --git a/include/PluginClient/GrpcKey.def b/include/PluginClient/GrpcKey.def new file mode 100755 index 0000000..f996544 --- /dev/null +++ b/include/PluginClient/GrpcKey.def @@ -0,0 +1,6 @@ +/* Definition of GRPC key name */ + +GRPC_KEY(START, "start") +GRPC_KEY(STOP, "stop") +GRPC_KEY(USERFUNC, "userFunc") +GRPC_KEY(INJECT, "injectPoint") diff --git a/include/PluginClient/GrpcValue.def b/include/PluginClient/GrpcValue.def new file mode 100755 index 0000000..d9b391b --- /dev/null +++ b/include/PluginClient/GrpcValue.def @@ -0,0 +1,6 @@ +/* Definition of GRPC value */ + +GRPC_VALUE(START_VALUE, "ok") +GRPC_VALUE(STOP_VALUE, "ok") +GRPC_VALUE(USERFUNC_VALUE, "execution completed") +GRPC_VALUE(FINISH_VALUE, "finished") diff --git a/include/PluginClient/JsonKey.def b/include/PluginClient/JsonKey.def new file mode 100755 index 0000000..adbd27e --- /dev/null +++ b/include/PluginClient/JsonKey.def @@ -0,0 +1,5 @@ +/* Definition of JsonKey */ + +JSON_KEY(PATH, "path") +JSON_KEY(SHA256, "sha256file") +JSON_KEY(TIMEOUT, "timeout") diff --git a/include/PluginClient/PassValue.def b/include/PluginClient/PassValue.def new file mode 100755 index 0000000..b9090ea --- /dev/null +++ b/include/PluginClient/PassValue.def @@ -0,0 +1,5 @@ +/* Definition of PASS value */ + +PASS_VALUE(PASS_NAME, "refPassName") +PASS_VALUE(PASS_NUM, "passNum") +PASS_VALUE(PASS_POSITION, "passPosition") diff --git a/include/PluginClient/PluginClient.h b/include/PluginClient/PluginClient.h index a0137b5..89d7573 100644 --- a/include/PluginClient/PluginClient.h +++ b/include/PluginClient/PluginClient.h @@ -18,35 +18,26 @@ Create: 2022-08-18 Description: This file contains the declaration of the PluginClient class. + 主要完成功能:完成和server之间grpc通信及数据解析,获取gcc插件数据并进行IR转换,完成 + gcc注册点注入及参数保存。提供GetInstance获取client对象唯一实例,完成插件初始化并启动 + server子进程,处理超时异常事件 */ #ifndef PLUGIN_CLIENT_H #define PLUGIN_CLIENT_H -#include -#include -#include -#include -#include -#include - #include "Dialect/PluginOps.h" #include "Dialect/PluginTypes.h" #include #include "plugin.grpc.pb.h" -#include "gcc-plugin.h" #include "PluginAPI/PluginClientAPI.h" +#include "PluginClient/PluginGrpcPort.h" +#include "PluginClient/PluginInputCheck.h" +#include "PluginClient/PluginJson.h" #include "PluginClient/PluginLog.h" #include "Dialect/PluginDialect.h" namespace PinClient { -using std::cout; -using std::string; -using std::endl; -using std::vector; -using std::map; -using std::pair; - using plugin::PluginService; using grpc::Channel; using grpc::ClientContext; @@ -55,6 +46,45 @@ using grpc::Status; using plugin::ClientMsg; using plugin::ServerMsg; +enum Grpckey { +#define GRPC_KEY(KEY, NAME) KEY, +#include "GrpcKey.def" +#undef GRPC_KEY +MAX_GRPC_KEYS +}; + +#define GRPC_KEY(KEY, NAME) NAME, +const char *const grpckey[] = { +#include "GrpcKey.def" +}; +#undef GRPC_KEY + +enum GrpcValue { +#define GRPC_VALUE(KEY, NAME) KEY, +#include "GrpcValue.def" +#undef GRPC_VALUE +MAX_GRPC_VALUES +}; + +#define GRPC_VALUE(KEY, NAME) NAME, +const char *const grpcValue[] = { +#include "GrpcValue.def" +}; +#undef GRPC_VALUE + +enum PassValue { +#define PASS_VALUE(KEY, NAME) KEY, +#include "PassValue.def" +#undef PASS_VALUE +MAX_PASS_VALUES +}; + +#define PASS_VALUE(KEY, NAME) NAME, +const char *const passValue[] = { +#include "PassValue.def" +}; +#undef PASS_VALUE + enum InjectPoint : uint8_t { HANDLE_PARSE_TYPE = 0, HANDLE_PARSE_DECL, @@ -68,8 +98,10 @@ enum InjectPoint : uint8_t { HANDLE_AFTER_ALL_PASS, HANDLE_COMPILE_END, HANDLE_MANAGER_SETUP, + HANDLE_INCLUDE_FILE, HANDLE_MAX, }; + typedef enum { STATE_WAIT_BEGIN = 0, STATE_BEGIN, @@ -101,50 +133,17 @@ struct ManagerSetupData { class PluginClient { public: - PluginClient() = default; - ~PluginClient() = default; - PluginClient(std::shared_ptr channel) : serviceStub(PluginService::NewStub(channel)) {} /* 定义的grpc服务端和客户端通信的接口函数 */ void ReceiveSendMsg(const string& attribute, const string& value); /* 获取client对象实例,有且只有一个实例对象 */ - static std::shared_ptr GetInstance(void); - void OpJsonSerialize(vector& data, string& out); - void LoopOpsJsonSerialize(vector& loops, string& out); - void LoopOpJsonSerialize(mlir::Plugin::LoopOp& loop, string& out); - void BlocksJsonSerialize(vector&, string&); - void EdgesJsonSerialize(vector >&, string&); - void EdgeJsonSerialize(pair&, string&); - void NopJsonSerialize(string&); - void FunctionOpJsonSerialize(vector& data, string& out); - void LocalDeclsJsonSerialize(vector& decls, string& out); - void GetPhiOpsJsonSerialize(vector phiOps, string& out); - Json::Value OperationJsonSerialize(mlir::Operation *, uint64_t&); - Json::Value CallOpJsonSerialize(mlir::Plugin::CallOp& data); - Json::Value CondOpJsonSerialize(mlir::Plugin::CondOp& data, uint64_t&); - Json::Value PhiOpJsonSerialize(mlir::Plugin::PhiOp& data); - Json::Value AssignOpJsonSerialize(mlir::Plugin::AssignOp& data); - Json::Value BaseOpJsonSerialize(mlir::Plugin::BaseOp data); - Json::Value FallThroughOpJsonSerialize(mlir::Plugin::FallThroughOp data, uint64_t&); - Json::Value RetOpJsonSerialize(mlir::Plugin::RetOp data, uint64_t&); - Json::Value ValueJsonSerialize(mlir::Value value); - Json::Value MemOpJsonSerialize(mlir::Plugin::MemOp& data); - Json::Value SSAOpJsonSerialize(mlir::Plugin::SSAOp& data); - /* 将Type类型数据序列化 */ - Json::Value TypeJsonSerialize(PluginIR::PluginTypeBase& type); - PluginIR::PluginTypeBase TypeJsonDeSerialize(const string& data, mlir::MLIRContext &context); + static PluginClient *GetInstance(); /* 获取gcc插件数据并进行IR转换,将转换后的数据序列化返回给server。param:函数入参序列化后的数据 */ - void IRTransBegin(const string& funname, const string& param); - /* 从配置文件读取初始化信息 */ - static int GetInitInfo(string& serverPath, string& shaPath, int& timeout); - /* 进行sha256校验 */ - static int CheckSHA256(const string& shaPath); - static void CheckSafeCompileFlag(const string& argName, const string& param); - /* 解析gcc编译时传递的-fplugin-arg参数 */ - static void GetArg(struct plugin_name_args *pluginInfo, string& serverPath, string& arg, LogPriority& logLevel); + void GetIRTransResult(void *gccData, const string& funname, const string& param); + void GetGccData(const string& funcName, const string& param, string& key, string& result); /* 将服务端传递的InjectPoint转换为plugin_event */ static int GetEvent(InjectPoint inject, plugin_event *event); - static unsigned short FindUnusedPort(void); // 查找未被使用的端口号,确保并发情况下server和client一对一 - UserFuncStateEnum GetUserFuncState(void) + void Init(struct plugin_name_args *pluginInfo, const string& pluginName, pid_t& serverPid); + UserFuncStateEnum GetUserFuncState() { return userFuncState; } @@ -168,10 +167,6 @@ public: { pluginAPIParams = name; } - void SetTimeout(int time) - { - timeout = time; - } void SetPluginName(const string& pluginName) { this->pluginName = pluginName; @@ -188,19 +183,11 @@ public: { return injectFlag; } - void SetGrpcPort(unsigned short port) - { - grpcPort = port; - } - unsigned short GetGrpcPort(void) - { - return grpcPort; - } - bool TimerInit(void); + bool TimerInit(clockid_t id); void TimerStart(int interval); /* 保存注入点和函数名信息,value格式为 注入点:函数名称 */ int AddRegisteredUserFunc(const string& value); - map>& GetRegisteredUserFunc(void) + map>& GetRegisteredUserFunc() { return registeredUserFunc; } @@ -210,13 +197,24 @@ public: } /* grpc消息处理函数 */ void ServerMsgProc(const string& attribute, const string& value); - /* grpc的server被client拉起之前将port记录在/tmp/grpc_ports_pin_client.txt中, server和client建立通信后从文件中删除port,避免多进程时端口冲突 - 文件若不存在,先创建文件 */ - static int OpenLockFile(const char *path); - /* 读取文件中保存的grpc端口号 */ - static void ReadPortsFromLockFile(int fd, string& grpcPorts); - /* server启动异常或者grpc建立通信后,将文件中记录的端口号删除 */ - static bool DeletePortFromLockFile(unsigned short port); + int ClientStart(); + int ServerStart(pid_t& pid); // pid server线程pid + bool DeleteGrpcPort() + { + return grpcPort.DeletePortFromLockFile(); + } + bool GetStartFlag() + { + return startFlag; + } + void SetStartFlag(bool flag) + { + startFlag = flag; + } + PluginJson &GetJson(void) + { + return json; + } private: std::unique_ptr serviceStub; // 保存grpc客户端stub对象 @@ -225,18 +223,17 @@ private: volatile UserFuncStateEnum userFuncState; string pluginAPIName; // 保存用户调用PluginAPI的函数名 string pluginAPIParams; // 保存用户调用PluginAPI函数的参数 - int timeout; timer_t timerId; string pluginName; // 向gcc插件注册回调函数时需要 bool injectFlag; // 是否完成将注册点信息注册到gcc - unsigned short grpcPort; // server和client使用的端口号 + PluginGrpcPort grpcPort; + PluginInputCheck input; + PluginJson json; /* 保存注册点和函数信息 */ map> registeredUserFunc; + std::shared_ptr grpcChannel; + bool startFlag; }; - -/* pid:子进程server返回的pid,port:查找到的未使用的端口号 */ -int ServerStart(int timeout, const string& serverPath, pid_t& pid, string& port, const LogPriority logLevel); -int ClientStart(int timeout, const string& arg, const string& pluginName, const string& port); } // namespace PinClient #endif diff --git a/include/PluginClient/PluginGrpcPort.h b/include/PluginClient/PluginGrpcPort.h new file mode 100755 index 0000000..cd06864 --- /dev/null +++ b/include/PluginClient/PluginGrpcPort.h @@ -0,0 +1,73 @@ +/* Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3, or (at your option) any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING3. If not see + . + + Author: Mingchuan Wu and Yancheng Li + Create: 2022-08-18 + Description: + This file contains the declaration of the PluginGrpcPort class. + 主要完成功能:查找未使用的端口号,并将端口号写入到共享文件中,通过文件锁控制多进程间访问,并提供 + DeletePortFromLockFile接口在退出时删除写入的端口号 +*/ + +#ifndef PLUGIN_GRPC_PORT_H +#define PLUGIN_GRPC_PORT_H + +#include + +namespace PinClient { +using std::string; + +class PluginGrpcPort { +public: + PluginGrpcPort() + { + const int startPort = 40000; + lockFilePath = "/tmp/grpc_ports_pin_client.txt"; + basePort = startPort; + port = 0; + } + bool FindUnusedPort(); // 查找未被使用的端口号,确保并发情况下server和client一对一 + /* grpc的server被client拉起之前将port记录在/tmp/grpc_ports_pin_client.txt中, server和client建立通信后从文件中删除port,避免多进程时端口冲突 + 文件若不存在,先创建文件 */ + int OpenFile(const char *path); + /* 读取文件中保存的grpc端口号 */ + bool ReadPortsFromLockFile(int fd, string& grpcPorts); + /* server启动异常或者grpc建立通信后,将文件中记录的端口号删除 */ + bool DeletePortFromLockFile(); + unsigned short GetPort() + { + return port; + } + void SetLockFilePath(const string& path) + { + lockFilePath = path; + } + void SetBasePort(unsigned short port) + { + basePort = port; + } + unsigned short GetBasePort() + { + return basePort; + } + +private: + unsigned short port; // server和client使用的端口号 + string lockFilePath; + unsigned short basePort; +}; +} // namespace PinClient +#endif \ No newline at end of file diff --git a/include/PluginClient/PluginInputCheck.h b/include/PluginClient/PluginInputCheck.h new file mode 100755 index 0000000..cbbfc3f --- /dev/null +++ b/include/PluginClient/PluginInputCheck.h @@ -0,0 +1,136 @@ +/* Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3, or (at your option) any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING3. If not see + . + + Author: Mingchuan Wu and Yancheng Li + Create: 2022-08-18 + Description: + This file contains the declaration of the PluginInputCheck class. + 主要完成功能:获取gcc编译时的参数,读取config.json配置文件,完成sha256校验,完成 + 安全编译选项参数检查,并保存serverPath,shaPath,timeout等信息 +*/ + +#ifndef PLUGIN_INPUT_CHECK_H +#define PLUGIN_INPUT_CHECK_H + +#include +#include +#include +#include "gcc-plugin.h" +#include "PluginClient/PluginLog.h" + +namespace PinClient { +using std::map; +using std::string; +using std::vector; + +enum Jsonkey { +#define JSON_KEY(KEY, NAME) KEY, +#include "JsonKey.def" +#undef JSON_KEY +MAX_JSON_KEYS +}; + +#define JSON_KEY(KEY, NAME) NAME, +const char *const jsonkey[] = { +#include "JsonKey.def" +}; +#undef JSON_KEY + +enum { + KEY_SERVER_PATH, + KEY_LOG_LEVEL, +}; + +class PluginInputCheck { +public: + const string shaFile = "/libpin_user.sha256"; + PluginInputCheck(); + /* 从配置文件读取初始化信息 */ + int GetInitInfo(); + int CheckServerFile(); // 对server文件进行检查 + int CheckShaFile(); // 对sha256校验文件进行检查 + bool ReadConfigfile(Json::Value& root); + /* 进行sha256校验 */ + int CheckSHA256(); + void CheckSafeCompileFlag(const string& argName, const string& param); + /* 解析gcc编译时传递的-fplugin-arg参数 */ + void GetInputArgs(struct plugin_name_args *pluginInfo); + int mapFind(const std::map& map, const string& key) + { + auto it = map.find(key); + if (it != map.end()) { + return it->second; + } + return -1; + } + string& GetArgs() + { + return args; + } + string& GetServerPath() + { + return serverPath; + } + void SetServerPath(const string& path) + { + serverPath = path; + } + LogPriority GetLogLevel() + { + return logLevel; + } + void SetLogLevel(LogPriority level) + { + logLevel = level; + } + string& GetShaPath() + { + return shaPath; + } + void SetShaPath(const string& path) + { + shaPath = path; + } + int GetTimeout() + { + return timeout; + } + void SetTimeout(int time); + void SetConfigPath(const string& path) + { + configFilePath = path; + } + string& GetConfigPath() + { + return configFilePath; + } + string GetServerDir() + { + int index = serverPath.find_last_of("/"); + return serverPath.substr(0, index); + } + +private: + string args; + string serverPath; + string configFilePath; + LogPriority logLevel; + string shaPath; + int timeout; + vector safeCompileFlags; +}; +} // namespace PinClient +#endif \ No newline at end of file diff --git a/include/PluginClient/PluginJson.h b/include/PluginClient/PluginJson.h new file mode 100755 index 0000000..91bd925 --- /dev/null +++ b/include/PluginClient/PluginJson.h @@ -0,0 +1,70 @@ +/* Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3, or (at your option) any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; see the file COPYING3. If not see + . + + Author: Mingchuan Wu and Yancheng Li + Create: 2022-08-18 + Description: + This file contains the declaration of the PluginJson class. + 主要完成功能:将operation、Decl、Type、Inter、string等类型数据序列化 +*/ + +#ifndef PLUGIN_JSON_H +#define PLUGIN_JSON_H + +#include +#include + +#include "Dialect/PluginDialect.h" +#include "Dialect/PluginOps.h" +#include "Dialect/PluginTypes.h" + +namespace PinClient { +using std::string; +using std::vector; + +class PluginJson { +public: + void OpJsonSerialize(vector& data, string& out); + void LoopOpsJsonSerialize(vector& loops, string& out); + void LoopOpJsonSerialize(mlir::Plugin::LoopOp& loop, string& out); + void BlocksJsonSerialize(vector&, string&); + void EdgesJsonSerialize(vector >&, string&); + void EdgeJsonSerialize(std::pair&, string&); + void NopJsonSerialize(string&); + void FunctionOpJsonSerialize(vector& data, string& out); + void LocalDeclsJsonSerialize(vector& decls, string& out); + void GetPhiOpsJsonSerialize(vector phiOps, string& out); + Json::Value OperationJsonSerialize(mlir::Operation *, uint64_t&); + Json::Value CallOpJsonSerialize(mlir::Plugin::CallOp& data); + Json::Value CondOpJsonSerialize(mlir::Plugin::CondOp& data, uint64_t&); + Json::Value PhiOpJsonSerialize(mlir::Plugin::PhiOp& data); + Json::Value AssignOpJsonSerialize(mlir::Plugin::AssignOp& data); + Json::Value BaseOpJsonSerialize(mlir::Plugin::BaseOp data); + Json::Value FallThroughOpJsonSerialize(mlir::Plugin::FallThroughOp data, uint64_t&); + Json::Value RetOpJsonSerialize(mlir::Plugin::RetOp data, uint64_t&); + Json::Value ValueJsonSerialize(mlir::Value value); + Json::Value MemOpJsonSerialize(mlir::Plugin::MemOp& data); + Json::Value SSAOpJsonSerialize(mlir::Plugin::SSAOp& data); + /* 将Type类型数据序列化 */ + Json::Value TypeJsonSerialize(PluginIR::PluginTypeBase& type); + PluginIR::PluginTypeBase TypeJsonDeSerialize(const string& data, mlir::MLIRContext &context); + /* 将整数型数据序列化 */ + void IntegerSerialize(int64_t data, string& out); + /* 将字符串型数据序列化 */ + void StringSerialize(const string& data, string& out); +}; +} // namespace PinClient +#endif diff --git a/include/PluginClient/PluginLog.h b/include/PluginClient/PluginLog.h index a91a1db..8fafa85 100644 --- a/include/PluginClient/PluginLog.h +++ b/include/PluginClient/PluginLog.h @@ -18,14 +18,14 @@ Create: 2022-08-18 Description: This file contains the declaration of the Plugin_Log class. + 主要完成功能:提供LOGE、LOGW、LOGI、LOGD四个log保存接口,并提供SetLogPriority接口 + 设置log级别 */ #ifndef PLUGIN_LOG_H #define PLUGIN_LOG_H namespace PinClient { -#define LOG_FILE_SIZE (10 * 1024 * 1024) - enum LogPriority : uint8_t { PRIORITY_ERROR = 0, PRIORITY_WARN, @@ -33,12 +33,13 @@ enum LogPriority : uint8_t { PRIORITY_DEBUG }; void LogPrint(LogPriority priority, const char *tag, const char *fmt, ...); -void CloseLog(void); +void CloseLog(); bool SetLogPriority(LogPriority priority); +void SetLogFileSize(unsigned int size); // 设置log文件大小,默认为10M,当日志超过10M后,重新命名 #define LOGE(...) LogPrint(PRIORITY_ERROR, "ERROR:", __VA_ARGS__) #define LOGW(...) LogPrint(PRIORITY_WARN, "WARN:", __VA_ARGS__) -#define LOGI(...) LogPrint(PRIORITY_INFO, "", __VA_ARGS__) +#define LOGI(...) LogPrint(PRIORITY_INFO, "INFO:", __VA_ARGS__) #define LOGD(...) LogPrint(PRIORITY_DEBUG, "DEBUG:", __VA_ARGS__) } // namespace PinClient diff --git a/include/Translate/GimpleToPluginOps.h b/include/Translate/GimpleToPluginOps.h index 689ece3..5f8bdf0 100644 --- a/include/Translate/GimpleToPluginOps.h +++ b/include/Translate/GimpleToPluginOps.h @@ -36,18 +36,24 @@ namespace PluginIR { using std::vector; +using std::string; using namespace mlir::Plugin; -namespace detail { +namespace Detail { class BlockFromGimpleTranslatorImpl; // class BlockToPluginIRTranslatorImpl; -} // namespace detail +} // namespace Detail class GimpleToPluginOps { public: GimpleToPluginOps (mlir::MLIRContext &); ~GimpleToPluginOps (); + string DeclSourceFile(uint64_t gccDataAddr); + string GetVariableName(uint64_t gccDataAddr); + string GetFuncName(uint64_t gccDataAddr); + int DeclSourceLine(uint64_t gccDataAddr); + int DeclSourceColumn(uint64_t gccDataAddr); /* ToPluginInterface */ uint64_t CreateBlock(uint64_t, uint64_t); void DeleteBlock(uint64_t, uint64_t); @@ -107,7 +113,7 @@ private: TypeToPluginIRTranslator pluginTypeTranslator; // process basic_block - std::unique_ptr bbTranslator; + std::unique_ptr bbTranslator; bool ProcessBasicBlock(intptr_t, Region&); bool ProcessGimpleStmt(intptr_t, Region&); }; diff --git a/include/Translate/ToPluginOpsInterface.h b/include/Translate/ToPluginOpsInterface.h deleted file mode 100644 index 6d2b74b..0000000 --- a/include/Translate/ToPluginOpsInterface.h +++ /dev/null @@ -1,59 +0,0 @@ -/* Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the - Free Software Foundation; either version 3, or (at your option) any - later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; see the file COPYING3. If not see - . - - Author: Mingchuan Wu and Yancheng Li - Create: 2022-08-18 - Description: - This file contains the declaration of the ToPluginInterface class -*/ - -#ifndef TO_PLUGINOPS_INTERFACE_H -#define TO_PLUGINOPS_INTERFACE_H - -#include -#include "Dialect/PluginOps.h" - -namespace PluginIR { -using std::vector; -using namespace mlir::Plugin; - -/* The ToPluginInterface class defines the plugin interfaces that different - compilers need to implement. */ -class ToPluginOpsInterface { -public: - /* Operation. */ - virtual vector GetAllFunction() = 0; - virtual vector GetAllDecls(uint64_t) = 0; - virtual vector GetAllLoops(uint64_t) = 0; - virtual LoopOp GetLoop(uint64_t) = 0; - virtual bool IsBlockInside(uint64_t, uint64_t) = 0; - virtual vector GetBlocksInLoop(uint64_t) = 0; - virtual uint64_t AllocateNewLoop(void) = 0; - virtual void DeleteLoop(uint64_t) = 0; - virtual void AddLoop (uint64_t, uint64_t, uint64_t) = 0; - virtual uint64_t GetHeader(uint64_t) = 0; - virtual uint64_t GetLatch(uint64_t) = 0; - virtual vector > GetLoopExits(uint64_t) = 0; - virtual std::pair GetLoopSingleExit(uint64_t) = 0; - virtual LoopOp GetBlockLoopFather(uint64_t) = 0; - virtual bool UpdateSSA() = 0; - virtual vector GetPhiOpsInsideBlock(uint64_t) = 0; - virtual bool IsDomInfoAvailable() = 0; - -}; -} // namespace PluginIR - -#endif // TO_PLUGINOPS_INTERFACE_H \ No newline at end of file diff --git a/include/Translate/TypeTranslation.h b/include/Translate/TypeTranslation.h index 964305c..98d279c 100644 --- a/include/Translate/TypeTranslation.h +++ b/include/Translate/TypeTranslation.h @@ -36,10 +36,10 @@ namespace PluginIR { using std::vector; using namespace mlir; -namespace detail { +namespace Detail { class TypeFromPluginIRTranslatorImpl; class TypeToPluginIRTranslatorImpl; -} // namespace detail +} // namespace Detail class TypeFromPluginIRTranslator { public: @@ -54,7 +54,7 @@ public: uint64_t getBitWidth (PluginTypeBase type); private: - std::unique_ptr impl; + std::unique_ptr impl; }; class TypeToPluginIRTranslator { @@ -65,7 +65,7 @@ public: uintptr_t translateType (PluginTypeBase type); private: - std::unique_ptr impl; + std::unique_ptr impl; }; } // namespace PluginIR diff --git a/include/IRTrans/IRTransPlugin.h b/include/gccPlugin/gccPlugin.h similarity index 83% rename from include/IRTrans/IRTransPlugin.h rename to include/gccPlugin/gccPlugin.h index 400e8e0..bb2e0d3 100755 --- a/include/IRTrans/IRTransPlugin.h +++ b/include/gccPlugin/gccPlugin.h @@ -18,6 +18,8 @@ Create: 2022-08-18 Description: This file contains the declaration of the RegisterPluginEvent. + 主要完成功能:提供RegisterPluginEvent和RegisterPassManagerSetup两个注册gcc + 回调点接口 */ #ifndef IRTRANS_PLUGIN_H @@ -26,6 +28,6 @@ #include "PluginClient/PluginClient.h" int RegisterPluginEvent(PinClient::InjectPoint inject, const std::string& pluginName); -int RegisterPassManagerSetup(PinClient::InjectPoint inject, const PinClient::ManagerSetupData& setupData, +void RegisterPassManagerSetup(unsigned int index, const PinClient::ManagerSetupData& setupData, const std::string& pluginName); #endif diff --git a/lib/Dialect/PluginDialect.cpp b/lib/Dialect/PluginDialect.cpp index 7071e64..527c076 100644 --- a/lib/Dialect/PluginDialect.cpp +++ b/lib/Dialect/PluginDialect.cpp @@ -16,11 +16,11 @@ */ -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // // This file defines Plugin dialect. // -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// #include "Dialect/PluginDialect.h" #include "Dialect/PluginOps.h" @@ -29,20 +29,21 @@ using namespace mlir; using namespace mlir::Plugin; -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin dialect. -//===----------------------------------------------------------------------===// - -void PluginDialect::initialize() { - addTypes(); - - addOperations< +// ===----------------------------------------------------------------------===// + +void PluginDialect::initialize() +{ + addTypes(); + + addOperations< #define GET_OP_LIST #include "Dialect/PluginOps.cpp.inc" - >(); + >(); } \ No newline at end of file diff --git a/lib/Dialect/PluginOps.cpp b/lib/Dialect/PluginOps.cpp index ac2a4ee..052ebfd 100644 --- a/lib/Dialect/PluginOps.cpp +++ b/lib/Dialect/PluginOps.cpp @@ -16,11 +16,11 @@ */ -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // // This file defines operations in the Plugin dialect. // -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// #include "Dialect/PluginDialect.h" #include "Dialect/PluginOps.h" @@ -33,7 +33,8 @@ using namespace mlir; using namespace mlir::Plugin; void FunctionOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, - uint64_t id, StringRef funcName, bool declaredInline) { + uint64_t id, StringRef funcName, bool declaredInline) +{ FunctionOp::build(builder, state, builder.getI64IntegerAttr(id), builder.getStringAttr(funcName), @@ -41,8 +42,8 @@ void FunctionOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, } void LocalDeclOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, - uint64_t id, StringRef symName, - int64_t typeID, uint64_t typeWidth) { + uint64_t id, StringRef symName, int64_t typeID, uint64_t typeWidth) +{ LocalDeclOp::build(builder, state, builder.getI64IntegerAttr(id), builder.getStringAttr(symName), @@ -51,8 +52,8 @@ void LocalDeclOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, } void LoopOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, - uint64_t id, uint32_t index, uint64_t innerLoopId, - uint64_t outerLoopId, uint32_t numBlock) { + uint64_t id, uint32_t index, uint64_t innerLoopId, uint64_t outerLoopId, uint32_t numBlock) +{ LoopOp::build(builder, state, builder.getI64IntegerAttr(id), builder.getI32IntegerAttr(index), @@ -61,12 +62,11 @@ void LoopOp::build(mlir::OpBuilder &builder, mlir::OperationState &state, builder.getI32IntegerAttr(numBlock)); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // PlaceholderOp void PlaceholderOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, IDefineCode defCode, bool readOnly, - Type retType) + uint64_t id, IDefineCode defCode, bool readOnly, Type retType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("defCode", @@ -75,12 +75,11 @@ void PlaceholderOp::build(OpBuilder &builder, OperationState &state, state.addTypes(retType); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // MemOp void MemOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, IDefineCode defCode, bool readOnly, - Value addr, Value offset, Type retType) + uint64_t id, IDefineCode defCode, bool readOnly, Value addr, Value offset, Type retType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("readOnly", builder.getBoolAttr(readOnly)); @@ -90,13 +89,11 @@ void MemOp::build(OpBuilder &builder, OperationState &state, if (retType) state.addTypes(retType); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // SSAOp -void SSAOp::build(OpBuilder &builder, OperationState &state, uint64_t id, - IDefineCode defCode, bool readOnly, uint64_t nameVarId, - uint64_t ssaParmDecl, uint64_t version, - uint64_t definingId, Type retType) +void SSAOp::build(OpBuilder &builder, OperationState &state, uint64_t id, IDefineCode defCode, bool readOnly, + uint64_t nameVarId, uint64_t ssaParmDecl, uint64_t version, uint64_t definingId, Type retType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("defCode", @@ -105,16 +102,15 @@ void SSAOp::build(OpBuilder &builder, OperationState &state, uint64_t id, state.addAttribute("nameVarId", builder.getI64IntegerAttr(nameVarId)); state.addAttribute("ssaParmDecl", builder.getI64IntegerAttr(ssaParmDecl)); state.addAttribute("version", builder.getI64IntegerAttr(version)); - state.addAttribute("definingId", builder.getI64IntegerAttr(definingId)); + state.addAttribute("definingId", builder.getI64IntegerAttr(definingId)); state.addTypes(retType); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // ConstOp void ConstOp::build(OpBuilder &builder, OperationState &state, uint64_t id, - IDefineCode defCode, bool readOnly, Attribute init, - Type retType) + IDefineCode defCode, bool readOnly, Attribute init, Type retType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("defCode", @@ -124,12 +120,11 @@ void ConstOp::build(OpBuilder &builder, OperationState &state, uint64_t id, if (retType) state.addTypes(retType); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // PointerOp void PointerOp::build(OpBuilder &builder, OperationState &state, uint64_t id, - IDefineCode defCode, bool readOnly, Type retType, - bool pointeeReadOnly) + IDefineCode defCode, bool readOnly, Type retType, bool pointeeReadOnly) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("defCode", @@ -139,12 +134,11 @@ void PointerOp::build(OpBuilder &builder, OperationState &state, uint64_t id, state.addAttribute("pointeeReadOnly", builder.getBoolAttr(pointeeReadOnly)); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // CallOp void CallOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, StringRef callee, - ArrayRef arguments, Type retType) + uint64_t id, StringRef callee, ArrayRef arguments, Type retType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addOperands(arguments); @@ -154,21 +148,25 @@ void CallOp::build(OpBuilder &builder, OperationState &state, /// Return the callee of the generic call operation, this is required by the /// call interface. -CallInterfaceCallable CallOp::getCallableForCallee() { +CallInterfaceCallable CallOp::getCallableForCallee() +{ return (*this)->getAttrOfType("callee"); } /// Get the argument operands to the called function, this is required by the /// call interface. -Operation::operand_range CallOp::getArgOperands() { return inputs(); } +Operation::operand_range CallOp::getArgOperands() +{ + return inputs(); +} -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // CondOp -void CondOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, uint64_t address, IComparisonCode condCode, - Value lhs, Value rhs, Block* tb, Block* fb, uint64_t tbaddr, - uint64_t fbaddr, Value trueLabel, Value falseLabel) { +void CondOp::build(OpBuilder &builder, OperationState &state, uint64_t id, uint64_t address, + IComparisonCode condCode, Value lhs, Value rhs, Block* tb, Block* fb, uint64_t tbaddr, + uint64_t fbaddr, Value trueLabel, Value falseLabel) +{ state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("address", builder.getI64IntegerAttr(address)); state.addOperands({lhs, rhs}); @@ -182,29 +180,29 @@ void CondOp::build(OpBuilder &builder, OperationState &state, if (falseLabel != nullptr) state.addOperands(falseLabel); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // PhiOp -void PhiOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, uint32_t capacity, uint32_t nArgs, - ArrayRef operands, Type resultType) { +void PhiOp::build(OpBuilder &builder, OperationState &state, uint64_t id, uint32_t capacity, + uint32_t nArgs, ArrayRef operands, Type resultType) +{ state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("capacity", builder.getI32IntegerAttr(capacity)); state.addAttribute("nArgs", builder.getI32IntegerAttr(nArgs)); state.addOperands(operands); - if (resultType != nullptr) state.addTypes(resultType); + if (resultType != nullptr) { + state.addTypes(resultType); + } } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // AssignOp -void AssignOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, IExprCode exprCode, - ArrayRef operands, Type resultType) +void AssignOp::build(OpBuilder &builder, OperationState &state, uint64_t id, + IExprCode exprCode, ArrayRef operands, Type resultType) { state.addAttribute("id", builder.getI64IntegerAttr(id)); - state.addAttribute("exprCode", - builder.getI32IntegerAttr(static_cast(exprCode))); + state.addAttribute("exprCode", builder.getI32IntegerAttr(static_cast(exprCode))); state.addOperands(operands); if (resultType != nullptr) state.addTypes(resultType); } @@ -216,47 +214,46 @@ void AssignOp::build(OpBuilder &builder, OperationState &state, /// or `false` on success. This allows for easily chaining together a set of /// parser rules. These rules are used to populate an `mlir::OperationState` /// similarly to the `build` methods described above. -static mlir::ParseResult parseAssignOp(mlir::OpAsmParser &parser, - mlir::OperationState &result) { - mlir::DenseElementsAttr value; - if (parser.parseOptionalAttrDict(result.attributes) || - parser.parseAttribute(value, "value", result.attributes)) - return failure(); - - result.addTypes(value.getType()); - return success(); +static mlir::ParseResult parseAssignOp(mlir::OpAsmParser &parser, mlir::OperationState &result) +{ + mlir::DenseElementsAttr value; + if (parser.parseOptionalAttrDict(result.attributes) || + parser.parseAttribute(value, "value", result.attributes)) { + return failure(); + } + + result.addTypes(value.getType()); + return success(); } /// The 'OpAsmPrinter' class is a stream that allows for formatting /// strings, attributes, operands, types, etc. -static void print(mlir::OpAsmPrinter &printer, AssignOp op) { - printer << "assign "; - printer.printType(op.getType()); -// printer << op.value(); +static void print(mlir::OpAsmPrinter &printer, AssignOp op) +{ + printer << "assign "; + printer.printType(op.getType()); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // BaseOp -void BaseOp::build(OpBuilder &builder, OperationState &state, - uint64_t id, StringRef opCode) +void BaseOp::build(OpBuilder &builder, OperationState &state, uint64_t id, StringRef opCode) { state.addAttribute("id", builder.getI64IntegerAttr(id)); state.addAttribute("opCode", builder.getStringAttr(opCode)); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // FallThroughOp -void FallThroughOp::build(OpBuilder &builder, OperationState &state, - uint64_t address, Block* dest, uint64_t destaddr) +void FallThroughOp::build(OpBuilder &builder, OperationState &state, uint64_t address, Block* dest, uint64_t destaddr) { state.addAttribute("address", builder.getI64IntegerAttr(address)); state.addAttribute("destaddr", builder.getI64IntegerAttr(destaddr)); state.addSuccessors(dest); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // RetOp void RetOp::build(OpBuilder &builder, OperationState &state, uint64_t address) @@ -264,9 +261,9 @@ void RetOp::build(OpBuilder &builder, OperationState &state, uint64_t address) state.addAttribute("address", builder.getI64IntegerAttr(address)); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // TableGen'd op method definitions -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "Dialect/PluginOps.cpp.inc" \ No newline at end of file diff --git a/lib/Dialect/PluginTypes.cpp b/lib/Dialect/PluginTypes.cpp index edccdd5..396bf0f 100644 --- a/lib/Dialect/PluginTypes.cpp +++ b/lib/Dialect/PluginTypes.cpp @@ -28,7 +28,7 @@ using namespace mlir; using namespace PluginIR; namespace PluginIR { -namespace detail { +namespace Detail { /// Integer Type Storage and Uniquing. struct PluginIntegerTypeStorage : public TypeStorage { PluginIntegerTypeStorage(unsigned width, @@ -38,16 +38,18 @@ namespace detail { /// The hash key used for uniquing. using KeyTy = std::pair; - static llvm::hash_code hashKey(const KeyTy &key) { + static llvm::hash_code hashKey(const KeyTy &key) + { return llvm::hash_value(key); } - bool operator==(const KeyTy &key) const { + bool operator==(const KeyTy &key) const + { return KeyTy(width, signedness) == key; } - static PluginIntegerTypeStorage *construct(TypeStorageAllocator &allocator, - KeyTy key) { + static PluginIntegerTypeStorage *construct(TypeStorageAllocator &allocator, KeyTy key) + { return new (allocator.allocate()) PluginIntegerTypeStorage(key.first, key.second); } @@ -62,12 +64,13 @@ namespace detail { /// The hash key used for uniquing. using KeyTy = unsigned; - bool operator==(const KeyTy &key) const { + bool operator==(const KeyTy &key) const + { return KeyTy(width) == key; } - static PluginFloatTypeStorage *construct(TypeStorageAllocator &allocator, - KeyTy key) { + static PluginFloatTypeStorage *construct(TypeStorageAllocator &allocator, KeyTy key) + { return new (allocator.allocate()) PluginFloatTypeStorage(key); } @@ -81,26 +84,27 @@ namespace detail { PluginPointerTypeStorage(const KeyTy &key) : pointee(std::get<0>(key)), readOnlyPointee(std::get<1>(key)) {} - static PluginPointerTypeStorage *construct(TypeStorageAllocator &allocator, - KeyTy key) { + static PluginPointerTypeStorage *construct(TypeStorageAllocator &allocator, KeyTy key) + { return new (allocator.allocate()) PluginPointerTypeStorage(key); } - bool operator==(const KeyTy &key) const { + bool operator==(const KeyTy &key) const + { return std::make_tuple(pointee, readOnlyPointee) == key; } Type pointee; unsigned readOnlyPointee; }; -} // namespace detail +} // namespace Detail } // namespace PluginIR -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin TypeBase -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// PluginTypeID PluginTypeBase::getPluginTypeID () { @@ -119,7 +123,7 @@ PluginTypeID PluginTypeBase::getPluginTypeID () if (auto Ty = dyn_cast()) { return Ty.getPluginTypeID (); } - return PluginTypeID::UndefTyID; + return PluginTypeID::UndefTyID; } unsigned PluginTypeBase::getPluginIntOrFloatBitWidth () @@ -159,9 +163,9 @@ unsigned PluginTypeBase::getTypeSize () return size; } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Integer Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// unsigned PluginIntegerType::getWidth() const { @@ -175,10 +179,8 @@ PluginIntegerType::SignednessSemantics PluginIntegerType::getSignedness() const PluginTypeID PluginIntegerType::getPluginTypeID() { - if (isSigned()) - { - switch (getWidth()) - { + if (isSigned()) { + switch (getWidth()) { case 1: return PluginTypeID::IntegerTy1ID; case 8: @@ -193,10 +195,8 @@ PluginTypeID PluginIntegerType::getPluginTypeID() return PluginTypeID::UndefTyID; } } - if (isUnsigned()) - { - switch (getWidth()) - { + if (isUnsigned()) { + switch (getWidth()) { case 1: return PluginTypeID::UIntegerTy1ID; case 8: @@ -214,14 +214,15 @@ PluginTypeID PluginIntegerType::getPluginTypeID() return PluginTypeID::UndefTyID; } -PluginIntegerType PluginIntegerType::get (MLIRContext *context, unsigned width, PluginIntegerType::SignednessSemantics signedness) +PluginIntegerType PluginIntegerType::get (MLIRContext *context, unsigned width, + PluginIntegerType::SignednessSemantics signedness) { return Base::get(context, width, signedness); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Float Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// unsigned PluginFloatType::getWidth () const { @@ -230,10 +231,12 @@ unsigned PluginFloatType::getWidth () const PluginTypeID PluginFloatType::getPluginTypeID() { - if (getWidth() == 32) + if (getWidth() == 32) { return PluginTypeID::FloatTyID; - if (getWidth() == 64) + } + if (getWidth() == 64) { return PluginTypeID::DoubleTyID; + } return PluginTypeID::UndefTyID; } @@ -242,36 +245,36 @@ PluginFloatType PluginFloatType::get (MLIRContext *context, unsigned width) return Base::get(context, width); } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Boolean Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// PluginTypeID PluginBooleanType::getPluginTypeID() { return PluginTypeID::BooleanTyID; } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Void Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// PluginTypeID PluginVoidType::getPluginTypeID() { return PluginTypeID::VoidTyID; } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Undef Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// PluginTypeID PluginUndefType::getPluginTypeID() { return PluginTypeID::UndefTyID; } -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// // Plugin Pointer Type -//===----------------------------------------------------------------------===// +// ===----------------------------------------------------------------------===// PluginTypeID PluginPointerType::getPluginTypeID() { @@ -291,4 +294,4 @@ unsigned PluginPointerType::isReadOnlyElem() PluginPointerType PluginPointerType::get (MLIRContext *context, Type pointee, unsigned readOnlyPointee) { return Base::get(context, pointee, readOnlyPointee); -} \ No newline at end of file +} diff --git a/lib/PluginAPI/PluginClientAPI.cpp b/lib/PluginAPI/PluginClientAPI.cpp index 1c4dbf9..5e454d7 100644 --- a/lib/PluginAPI/PluginClientAPI.cpp +++ b/lib/PluginAPI/PluginClientAPI.cpp @@ -19,6 +19,32 @@ #include "PluginAPI/PluginClientAPI.h" namespace PluginAPI { + +string PluginClientAPI::GetDeclSourceFile(uint64_t gccDataAddr) +{ + return gimpleConversion.DeclSourceFile(gccDataAddr); +} + +string PluginClientAPI::VariableName(int64_t gccDataAddr) +{ + return gimpleConversion.GetVariableName(gccDataAddr); +} + +string PluginClientAPI::FuncName(int64_t gccDataAddr) +{ + return gimpleConversion.GetFuncName(gccDataAddr); +} + +int PluginClientAPI::GetDeclSourceLine(uint64_t gccDataAddr) +{ + return gimpleConversion.DeclSourceLine(gccDataAddr); +} + +int PluginClientAPI::GetDeclSourceColumn(uint64_t gccDataAddr) +{ + return gimpleConversion.DeclSourceColumn(gccDataAddr); +} + uint64_t PluginClientAPI::CreateBlock(uint64_t funcAddr, uint64_t bbAddr) { return gimpleConversion.CreateBlock(funcAddr, bbAddr); @@ -142,20 +168,17 @@ bool PluginClientAPI::SetLhsInCallOp(uint64_t callId, uint64_t lhsId) return gimpleConversion.SetGimpleCallLHS(callId, lhsId); } -uint32_t PluginClientAPI::AddArgInPhiOp(uint64_t phiId, uint64_t argId, - uint64_t predId, uint64_t succId) +uint32_t PluginClientAPI::AddArgInPhiOp(uint64_t phiId, uint64_t argId, uint64_t predId, uint64_t succId) { return gimpleConversion.AddPhiArg(phiId, argId, predId, succId); } -uint64_t PluginClientAPI::CreateCallOp(uint64_t blockId, uint64_t funcId, - vector &argIds) +uint64_t PluginClientAPI::CreateCallOp(uint64_t blockId, uint64_t funcId, vector &argIds) { return gimpleConversion.CreateGcallVec(blockId, funcId, argIds); } -uint64_t PluginClientAPI::CreateAssignOp(uint64_t blockId, IExprCode iCode, - vector &argIds) +uint64_t PluginClientAPI::CreateAssignOp(uint64_t blockId, IExprCode iCode, vector &argIds) { return gimpleConversion.CreateGassign(blockId, iCode, argIds); } @@ -170,8 +193,7 @@ mlir::Value PluginClientAPI::CreateConstOp(mlir::Attribute attr, mlir::Type type } uint64_t PluginClientAPI::CreateCondOp(uint64_t blockId, IComparisonCode iCode, - uint64_t LHS, uint64_t RHS, - uint64_t tbaddr, uint64_t fbaddr) + uint64_t LHS, uint64_t RHS, uint64_t tbaddr, uint64_t fbaddr) { return gimpleConversion.CreateGcond(blockId, iCode, LHS, RHS, tbaddr, fbaddr); } diff --git a/lib/PluginClient/PluginLog.cpp b/lib/PluginClient/PluginLog.cpp index ad2b985..6cdf7af 100644 --- a/lib/PluginClient/PluginLog.cpp +++ b/lib/PluginClient/PluginLog.cpp @@ -36,6 +36,7 @@ constexpr int LOG_BUF_SIZE = 10240; constexpr int BASE_DATE = 1900; static LogPriority g_priority = PRIORITY_WARN; // log打印的级别控制 static std::mutex g_mutex; // 线程锁 +static unsigned int g_logFileSize = 10 * 1024 * 1024; shared_ptr g_fs; static void LogWriteInit(const string& data); @@ -44,16 +45,22 @@ static void (*g_writeToLog)(const string& data) = LogWriteInit; static void GetLogFileName(string& fileName) { time_t nowTime = time(nullptr); + if (nowTime == -1) { + printf("%s fail\n", __func__); + } struct tm *t = localtime(&nowTime); char buf[100]; - sprintf(buf, "/tmp/pin_client%d_%4d%02d%02d_%02d_%02d_%02d.log", getpid(), + int ret = sprintf(buf, "/tmp/pin_client%d_%4d%02d%02d_%02d_%02d_%02d.log", getpid(), t->tm_year + BASE_DATE, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); + if (ret < 0) { + printf("%s sprintf fail\n", __func__); + } fileName = buf; } static void LogWriteFile(const string& data) { - if (g_fs->tellg() > LOG_FILE_SIZE) { + if (g_fs->tellg() > g_logFileSize) { g_fs->close(); string fileName; GetLogFileName(fileName); @@ -75,7 +82,7 @@ static void LogWriteInit(const string& data) g_writeToLog(data); } -void CloseLog(void) +void CloseLog() { if (g_fs) { if (g_fs->is_open()) { @@ -84,14 +91,24 @@ void CloseLog(void) } } +void SetLogFileSize(unsigned int size) +{ + g_logFileSize = size; +} + static void LogWrite(const char *tag, const char *msg) { time_t nowTime = time(nullptr); + if (nowTime == -1) { + printf("%s fail\n", __func__); + } struct tm *t = localtime(&nowTime); char buf[30]; - sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d ", t->tm_year + BASE_DATE, t->tm_mon + 1, t->tm_mday, + int ret = sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d ", t->tm_year + BASE_DATE, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - + if (ret < 0) { + printf("%s sprintf fail\n", __func__); + } string stag = tag; string smsg = msg; string data = buf + stag + smsg; @@ -104,7 +121,10 @@ void LogPrint(LogPriority priority, const char *tag, const char *fmt, ...) char buf[LOG_BUF_SIZE]; va_start(ap, fmt); - vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); + int ret = vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); + if (ret < 0) { + printf("%s vsnprintf fail\n", __func__); + } va_end(ap); if (priority <= g_priority) { diff --git a/lib/Translate/GimpleToPluginOps.cpp b/lib/Translate/GimpleToPluginOps.cpp index 3a71ffe..b5974aa 100644 --- a/lib/Translate/GimpleToPluginOps.cpp +++ b/lib/Translate/GimpleToPluginOps.cpp @@ -53,7 +53,7 @@ namespace PluginIR { using namespace mlir::Plugin; using namespace mlir; -namespace detail { +namespace Detail { class BlockFromGimpleTranslatorImpl { public: std::map blockMaps; @@ -65,13 +65,13 @@ private: mlir::MLIRContext &context; }; -} // namespace detail +} // namespace Detail -GimpleToPluginOps::GimpleToPluginOps (mlir::MLIRContext &context) : - builder(&context), typeTranslator(context), bbTranslator(new detail::BlockFromGimpleTranslatorImpl(context)) +GimpleToPluginOps::GimpleToPluginOps(mlir::MLIRContext &context) : builder(&context), + typeTranslator(context), bbTranslator(new Detail::BlockFromGimpleTranslatorImpl(context)) {} -GimpleToPluginOps::~GimpleToPluginOps () +GimpleToPluginOps::~GimpleToPluginOps() {} static IComparisonCode TranslateCmpCode(enum tree_code ccode) @@ -151,7 +151,6 @@ static IExprCode TranslateExprCode(enum tree_code ccode) case NOP_EXPR: return IExprCode::Nop; default: - // printf("tcc_binary: %d not suppoted!\n", ccode); break; } return IExprCode::UNDEF; @@ -185,7 +184,6 @@ static enum tree_code TranslateExprCodeToTreeCode(IExprCode ccode) case IExprCode::Nop: return NOP_EXPR; default: - // printf("tcc_binary: %d not suppoted!\n", ccode); break; } // FIXME. @@ -220,6 +218,40 @@ static StringRef GimpleCodeToOperationName(enum gimple_code tcode) return ret; } +string GimpleToPluginOps::DeclSourceFile(uint64_t gccDataAddr) +{ + tree decl = (tree)gccDataAddr; + string sourceFile = DECL_SOURCE_FILE(decl); + return sourceFile; +} + +string GimpleToPluginOps::GetVariableName(uint64_t gccDataAddr) +{ + tree decl = (tree)gccDataAddr; + string pointer = DECL_NAME(decl) != NULL_TREE ? IDENTIFIER_POINTER(DECL_NAME(decl)) : ""; + return pointer; +} + +string GimpleToPluginOps::GetFuncName(uint64_t gccDataAddr) +{ + string funcName = function_name((function *)gccDataAddr); + return funcName; +} + +int GimpleToPluginOps::DeclSourceLine(uint64_t gccDataAddr) +{ + tree decl = (tree)gccDataAddr; + int line = DECL_SOURCE_LINE(decl); + return line; +} + +int GimpleToPluginOps::DeclSourceColumn(uint64_t gccDataAddr) +{ + tree decl = (tree)gccDataAddr; + int column = DECL_SOURCE_COLUMN(decl); + return column; +} + uint64_t GimpleToPluginOps::CreateBlock(uint64_t funcAddr, uint64_t bbAddr) { basic_block address = reinterpret_cast(bbAddr); @@ -484,7 +516,7 @@ void GimpleToPluginOps::RedirectFallthroughTarget(uint64_t src, uint64_t dest) { basic_block srcbb = reinterpret_cast(reinterpret_cast(src)); basic_block destbb = reinterpret_cast(reinterpret_cast(dest)); - assert(single_succ_p (srcbb)); + assert(single_succ_p(srcbb)); redirect_edge_and_branch (single_succ_edge(srcbb), destbb); } @@ -537,7 +569,7 @@ Operation *GimpleToPluginOps::BuildOperation(uint64_t id) break; } case GIMPLE_COND: { - assert(EDGE_COUNT (stmt->bb->succs) == 2); + assert(EDGE_COUNT(stmt->bb->succs) == 2); Block* trueBlock = bbTranslator->blockMaps[EDGE_SUCC(stmt->bb, 0)->dest]; Block* falseBlock = bbTranslator->blockMaps[EDGE_SUCC(stmt->bb, 1)->dest]; CondOp condOp = BuildCondOp(id, (uint64_t)stmt->bb, @@ -644,15 +676,13 @@ uint64_t GimpleToPluginOps::CreateGcallVec(uint64_t blockId, uint64_t funcId, gcall *ret = gimple_build_call_vec (fn, vargs); basic_block bb = reinterpret_cast(blockId); if (bb != nullptr) { - gimple_stmt_iterator si; - si = gsi_last_bb (bb); + gimple_stmt_iterator si = gsi_last_bb (bb); gsi_insert_after (&si, ret, GSI_NEW_STMT); } return reinterpret_cast(reinterpret_cast(ret)); } -uint32_t GimpleToPluginOps::AddPhiArg(uint64_t phiId, uint64_t argId, - uint64_t predId, uint64_t succId) +uint32_t GimpleToPluginOps::AddPhiArg(uint64_t phiId, uint64_t argId, uint64_t predId, uint64_t succId) { gphi *phi = reinterpret_cast(phiId); tree arg = reinterpret_cast(argId); @@ -681,31 +711,25 @@ uint64_t GimpleToPluginOps::CreateGassign(uint64_t blockId, IExprCode iCode, if (iCode == IExprCode::UNDEF) { ret = gimple_build_assign(vargs[0], vargs[1]); } else { - ret = gimple_build_assign(vargs[0], - TranslateExprCodeToTreeCode(iCode), - vargs[1]); + ret = gimple_build_assign(vargs[0], TranslateExprCodeToTreeCode(iCode), vargs[1]); } } else if (vargs.size() == 3) { - ret = gimple_build_assign(vargs[0], TranslateExprCodeToTreeCode(iCode), - vargs[1], vargs[2]); + ret = gimple_build_assign(vargs[0], TranslateExprCodeToTreeCode(iCode), vargs[1], vargs[2]); } else if (vargs.size() == 4) { - ret = gimple_build_assign(vargs[0], TranslateExprCodeToTreeCode(iCode), - vargs[1], vargs[2], vargs[3]); + ret = gimple_build_assign(vargs[0], TranslateExprCodeToTreeCode(iCode), vargs[1], vargs[2], vargs[3]); } else { printf("ERROR size: %ld.\n", vargs.size()); } basic_block bb = reinterpret_cast(blockId); if (bb != nullptr) { - gimple_stmt_iterator si; - si = gsi_last_bb (bb); + gimple_stmt_iterator si = gsi_last_bb (bb); gsi_insert_after (&si, ret, GSI_NEW_STMT); } return reinterpret_cast(reinterpret_cast(ret)); } uint64_t GimpleToPluginOps::CreateGcond(uint64_t blockId, IComparisonCode iCode, - uint64_t lhsId, uint64_t rhsId, - uint64_t tbaddr, uint64_t fbaddr) + uint64_t lhsId, uint64_t rhsId, uint64_t tbaddr, uint64_t fbaddr) { tree lhs = reinterpret_cast(lhsId); tree rhs = reinterpret_cast(rhsId); @@ -713,14 +737,13 @@ uint64_t GimpleToPluginOps::CreateGcond(uint64_t blockId, IComparisonCode iCode, lhs, rhs, NULL_TREE, NULL_TREE); basic_block bb = reinterpret_cast(blockId); if (bb != nullptr) { - gimple_stmt_iterator si; - si = gsi_last_bb (bb); + gimple_stmt_iterator si = gsi_last_bb (bb); gsi_insert_after (&si, ret, GSI_NEW_STMT); } basic_block tb = reinterpret_cast(tbaddr); basic_block fb = reinterpret_cast(fbaddr); - assert(make_edge (bb, tb, EDGE_TRUE_VALUE)); - assert(make_edge (bb, fb, EDGE_FALSE_VALUE)); + assert(make_edge(bb, tb, EDGE_TRUE_VALUE)); + assert(make_edge(bb, fb, EDGE_FALSE_VALUE)); return reinterpret_cast(reinterpret_cast(ret)); } @@ -728,12 +751,11 @@ void GimpleToPluginOps::CreateFallthroughOp(uint64_t addr, uint64_t destaddr) { basic_block src = reinterpret_cast(addr); basic_block dest = reinterpret_cast(destaddr); - assert(make_single_succ_edge (src, dest, EDGE_FALLTHRU)); + assert(make_single_succ_edge(src, dest, EDGE_FALLTHRU)); } CondOp GimpleToPluginOps::BuildCondOp(uint64_t gcondId, uint64_t address, - Block* b1, Block* b2, uint64_t tbaddr, - uint64_t fbaddr) + Block* b1, Block* b2, uint64_t tbaddr, uint64_t fbaddr) { gcond *stmt = reinterpret_cast(gcondId); tree lhsPtr = gimple_cond_lhs(stmt); @@ -812,16 +834,9 @@ Value GimpleToPluginOps::TreeToValue(uint64_t treeId) mlir::Value opValue; switch (TREE_CODE(t)) { case INTEGER_CST : { - mlir::Attribute initAttr; - if (tree_fits_shwi_p(t)) { - signed HOST_WIDE_INT sinit = tree_to_shwi(t); - initAttr = builder.getI64IntegerAttr(sinit); - } else if (tree_fits_uhwi_p(t)) { - unsigned HOST_WIDE_INT uinit = tree_to_uhwi(t); - initAttr = builder.getI64IntegerAttr(uinit); - } else { - abort(); - } + unsigned HOST_WIDE_INT init = tree_to_uhwi(t); + // FIXME : AnyAttr! + mlir::Attribute initAttr = builder.getI64IntegerAttr(init); opValue = builder.create( builder.getUnknownLoc(), treeId, IDefineCode::IntCST, readOnly, initAttr, rPluginType); @@ -863,11 +878,9 @@ Value GimpleToPluginOps::TreeToValue(uint64_t treeId) void GimpleToPluginOps::DebugValue(uint64_t valId) { tree t = reinterpret_cast(valId); - // debug_tree (t); } -mlir::Value GimpleToPluginOps::BuildMemRef(PluginIR::PluginTypeBase type, - uint64_t baseId, uint64_t offsetId) +mlir::Value GimpleToPluginOps::BuildMemRef(PluginIR::PluginTypeBase type, uint64_t baseId, uint64_t offsetId) { tree refType = (tree)pluginTypeTranslator.translateType(type); tree base = (tree)baseId; @@ -883,7 +896,7 @@ bool GimpleToPluginOps::ProcessGimpleStmt(intptr_t bbPtr, Region& rg) for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si)) { gphi *p = si.phi (); uint64_t id = reinterpret_cast(reinterpret_cast(p)); - BuildPhiOp(id); // FIXME: Check result. + BuildPhiOp(id); // FIXME: Check result. } for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si)) { @@ -892,7 +905,7 @@ bool GimpleToPluginOps::ProcessGimpleStmt(intptr_t bbPtr, Region& rg) if (BuildOperation(id) == nullptr) { printf("ERROR: BuildOperation!"); } - if(gimple_code(stmt) == GIMPLE_COND) { + if (gimple_code(stmt) == GIMPLE_COND) { putTerminator = true; } } @@ -907,7 +920,6 @@ bool GimpleToPluginOps::ProcessGimpleStmt(intptr_t bbPtr, Region& rg) // Process other condition, such as return builder.create(builder.getUnknownLoc(), (uint64_t)bb); } else { - // Should unreachable; assert(false); } } diff --git a/lib/Translate/TypeTranslation.cpp b/lib/Translate/TypeTranslation.cpp index 66521a9..7c7cff4 100644 --- a/lib/Translate/TypeTranslation.cpp +++ b/lib/Translate/TypeTranslation.cpp @@ -49,7 +49,7 @@ using namespace mlir; namespace PluginIR { -namespace detail { +namespace Detail { /* Support for translating Plugin IR types to MLIR Plugin dialect types. */ class TypeFromPluginIRTranslatorImpl { public: @@ -82,7 +82,8 @@ private: PluginTypeBase translatePrimitiveType (tree type) { if (TREE_CODE(type) == INTEGER_TYPE) - return PluginIntegerType::get(&context, getBitWidth(type), isUnsigned(type) ? PluginIntegerType::Unsigned : PluginIntegerType::Signed); + return PluginIntegerType::get(&context, getBitWidth(type), + isUnsigned(type) ? PluginIntegerType::Unsigned : PluginIntegerType::Signed); if (TREE_CODE(type) == REAL_TYPE) return PluginFloatType::get(&context, getBitWidth(type)); if (TREE_CODE(type) == BOOLEAN_TYPE) @@ -90,7 +91,8 @@ private: if (TREE_CODE(type) == VOID_TYPE) return PluginVoidType::get(&context); if (TREE_CODE(type) == POINTER_TYPE) - return PluginPointerType::get(&context, translatePrimitiveType(TREE_TYPE(type)), TYPE_READONLY(TREE_TYPE(type)) ? 1 : 0); + return PluginPointerType::get(&context, translatePrimitiveType(TREE_TYPE(type)), + TYPE_READONLY(TREE_TYPE(type)) ? 1 : 0); return PluginUndefType::get(&context); } @@ -111,19 +113,20 @@ public: } private: - unsigned getBitWidth (PluginIntegerType type) + unsigned getBitWidth(PluginIntegerType type) { return type.getWidth(); } - bool isUnsigned (PluginIntegerType type) + bool isUnsigned(PluginIntegerType type) { - if(type.isUnsigned()) + if (type.isUnsigned()) { return true; + } return false; } - tree translatePrimitiveType (PluginTypeBase type) + tree translatePrimitiveType(PluginTypeBase type) { if (auto Ty = type.dyn_cast()) { if (isUnsigned(Ty)) { @@ -178,14 +181,13 @@ private: } return NULL; } - }; -} // namespace detail +} // namespace Detail } // namespace PluginIR PluginIR::TypeFromPluginIRTranslator::TypeFromPluginIRTranslator(mlir::MLIRContext &context) - : impl(new detail::TypeFromPluginIRTranslatorImpl(context)) {} + : impl(new Detail::TypeFromPluginIRTranslatorImpl(context)) {} PluginIR::TypeFromPluginIRTranslator::~TypeFromPluginIRTranslator() {} @@ -206,7 +208,7 @@ uint64_t PluginIR::TypeFromPluginIRTranslator::getBitWidth(PluginTypeBase type) PluginIR::TypeToPluginIRTranslator::TypeToPluginIRTranslator() - : impl(new detail::TypeToPluginIRTranslatorImpl()) {} + : impl(new Detail::TypeToPluginIRTranslatorImpl()) {} PluginIR::TypeToPluginIRTranslator::~TypeToPluginIRTranslator() {} diff --git a/lib/IRTrans/IRTransPlugin.cpp b/lib/gccPlugin/gccPlugin.cpp old mode 100644 new mode 100755 similarity index 52% rename from lib/IRTrans/IRTransPlugin.cpp rename to lib/gccPlugin/gccPlugin.cpp index 459cef0..103d709 --- a/lib/IRTrans/IRTransPlugin.cpp +++ b/lib/gccPlugin/gccPlugin.cpp @@ -17,78 +17,81 @@ Author: Mingchuan Wu and Yancheng Li Create: 2022-08-18 Description: - This file contains the declaration of the PluginAPI class. + This file contains the functions of gcc plugin callback and init. + 主要完成功能:实现RegisterPluginEvent和RegisterPassManagerSetup功能,完成gcc + 版本号检查,当触发注册点对应事件时,回调server注册的用户函数 + plugin_init为整个程序入口函数 */ -#include -#include -#include #include -#include #include "PluginClient/PluginClient.h" #include "plugin-version.h" -#include "IRTrans/IRTransPlugin.h" -#include "context.h" #include "tree-pass.h" #include "tree.h" -#include "tree-cfg.h" +#include "context.h" +#include "gccPlugin/gccPlugin.h" using namespace PinClient; -using std::vector; int plugin_is_GPL_compatible; static pid_t g_serverPid; -/* gcc插件end事件回调函数 */ -static void GccEnd(void *gccData, void *userData) +/* gcc插件end事件回调函数,停止插件服务端,等待子进程结束,删除端口号 */ +void GccEnd(void *gccData, void *userData) { int status = 0; - std::shared_ptr client = PluginClient::GetInstance(); - if (client == nullptr) { + PluginClient *client = PluginClient::GetInstance(); + if (!client->GetStartFlag()) { return; } + LOGI("gcc optimize has been done! now close server...\n"); client->ReceiveSendMsg("stop", ""); if (client->GetUserFuncState() != STATE_TIMEOUT) { waitpid(g_serverPid, &status, 0); } else { - client->DeletePortFromLockFile(client->GetGrpcPort()); + client->DeleteGrpcPort(); } - LOGI("client pid:%d quit\n", getpid()); } +static void WaitIRTrans(void *gccData, PluginClient *client) +{ + while (1) { + UserFuncStateEnum state = client->GetUserFuncState(); + /* server获取到client对应函数的执行结果后,向client回复已执行完,跳出循环执行下一个函数 */ + if (state == STATE_END) { + client->SetUserFuncState(STATE_WAIT_BEGIN); + break; + } else if (state == STATE_TIMEOUT) { + break; + } else if (state == STATE_BEGIN) { + string funcName = client->GetPluginAPIName(); + string param = client->GetPluginAPIParam(); + if (funcName != "") { + client->SetUserFuncState(STATE_WAIT_IR); + client->GetIRTransResult(gccData, funcName, param); + } + } + } +} + /* gcc插件回调函数,当注册的plugin_event触发时,进入此函数 */ -static void GccEventCallback(void *gccData, void *userData) +void GccEventCallback(void *gccData, void *userData) { - std::shared_ptr client = PluginClient::GetInstance(); + PluginClient *client = PluginClient::GetInstance(); InjectPoint *inject = (InjectPoint *)userData; vector userFuncs = client->GetFuncNameByInject(*inject); string key = "injectPoint"; string value; + for (auto &userFunc : userFuncs) { if (client->GetUserFuncState() == STATE_TIMEOUT) { break; } value = std::to_string(*inject) + ":" + userFunc; client->ReceiveSendMsg(key, value); - while (1) { - UserFuncStateEnum state = client->GetUserFuncState(); - /* server获取到client对应函数的执行结果后,向client回复已执行完,跳出循环执行下一个函数 */ - if (state == STATE_END) { - client->SetUserFuncState(STATE_WAIT_BEGIN); - break; - } else if (state == STATE_TIMEOUT) { - break; - } else if (state == STATE_BEGIN) { - string funcName = client->GetPluginAPIName(); - string param = client->GetPluginAPIParam(); - if (funcName != "") { - client->SetUserFuncState(STATE_WAIT_IR); - client->IRTransBegin(funcName, param); - } - } - } + WaitIRTrans(gccData, client); } LOGI("%s end!\n", __func__); } @@ -107,6 +110,7 @@ static InjectPoint g_event[] = { HANDLE_AFTER_ALL_PASS, HANDLE_COMPILE_END, HANDLE_MANAGER_SETUP, + HANDLE_INCLUDE_FILE, HANDLE_MAX }; @@ -121,84 +125,67 @@ int RegisterPluginEvent(InjectPoint inject, const string& pluginName) return 0; } -void ManagerSetupCallback(void) +static void ManagerSetupCallback(unsigned int index, function *fun) { string key = "injectPoint"; InjectPoint inject = HANDLE_MANAGER_SETUP; - std::shared_ptr client = PluginClient::GetInstance(); + PluginClient *client = PluginClient::GetInstance(); vector userFuncs = client->GetFuncNameByInject(inject); - for (auto &userFunc : userFuncs) { - if (client->GetUserFuncState() == STATE_TIMEOUT) { - break; - } - string value = std::to_string(inject) + ":" + userFunc; + if (index < userFuncs.size()) { + string name = userFuncs[index].substr(0, userFuncs[index].find_first_of(",")); + string value = std::to_string(inject) + ":" + name + ",params:" + std::to_string((uintptr_t)fun); client->ReceiveSendMsg(key, value); - while (1) { - UserFuncStateEnum state = client->GetUserFuncState(); - /* server获取到client对应函数的执行结果后,向client回复已执行完,跳出循环执行下一个函数 */ - if (state == STATE_END) { - client->SetUserFuncState(STATE_WAIT_BEGIN); - break; - } else if (state == STATE_TIMEOUT) { - break; - } else if (state == STATE_BEGIN) { - string funcName = client->GetPluginAPIName(); - string param = client->GetPluginAPIParam(); - if (funcName != "") { - client->SetUserFuncState(STATE_WAIT_IR); - client->IRTransBegin(funcName, param); - } - } - } + WaitIRTrans(nullptr, client); } } -struct RltPass: rtl_opt_pass { +struct RtlPass: rtl_opt_pass { public: - RltPass(pass_data passData): rtl_opt_pass(passData, g) + RtlPass(pass_data passData, unsigned int indx): rtl_opt_pass(passData, g), index(indx) { } - unsigned int execute(function *fun) override + /* unsigned int execute(function *fun) override { - ManagerSetupCallback(); + ManagerSetupCallback(index, fun); return 0; - } - RltPass* clone() override - { - return this; - } + } */ + +private: + unsigned int index; }; struct SimpleIPAPass: simple_ipa_opt_pass { public: - SimpleIPAPass(pass_data passData): simple_ipa_opt_pass(passData, g) + SimpleIPAPass(pass_data passData, unsigned int indx): simple_ipa_opt_pass(passData, g), index(indx) { } - unsigned int execute(function *fun) override + /* unsigned int execute(function *fun) override { - ManagerSetupCallback(); + ManagerSetupCallback(index, fun); return 0; - } - SimpleIPAPass* clone() override - { - return this; - } + } */ + +private: + unsigned int index; }; struct GimplePass: gimple_opt_pass { public: - GimplePass(pass_data passData): gimple_opt_pass(passData, g) + GimplePass(pass_data passData, unsigned int indx): gimple_opt_pass(passData, g), index(indx) { } unsigned int execute(function *fun) override { - ManagerSetupCallback(); + ManagerSetupCallback(index, fun); return 0; } GimplePass* clone() override { return this; } + +private: + unsigned int index; }; static std::map g_refPassName { @@ -208,16 +195,13 @@ static std::map g_refPassName { {PASS_LOOP, "loop"}, }; -int RegisterPassManagerSetup(InjectPoint inject, const ManagerSetupData& setupData, const string& pluginName) +void RegisterPassManagerSetup(unsigned int index, const ManagerSetupData& setupData, const string& pluginName) { - if (inject != HANDLE_MANAGER_SETUP) { - return -1; - } - struct register_pass_info passInfo; + string passDataName = "managerSetupPass_" + g_refPassName[setupData.refPassName]; pass_data passData = { .type = GIMPLE_PASS, - .name = "managerSetupPass", + .name = passDataName.c_str(), .optinfo_flags = OPTGROUP_NONE, .tv_id = TV_NONE, .properties_required = 0, @@ -233,27 +217,28 @@ int RegisterPassManagerSetup(InjectPoint inject, const ManagerSetupData& setupDa switch (setupData.refPassName) { case PASS_CFG: passData.type = GIMPLE_PASS; - passInfo.pass = new GimplePass(passData); + passInfo.pass = new GimplePass(passData, index); break; case PASS_PHIOPT: passData.type = GIMPLE_PASS; - passInfo.pass = new GimplePass(passData); + passInfo.pass = new GimplePass(passData, index); break; case PASS_SSA: passData.type = GIMPLE_PASS; - passInfo.pass = new GimplePass(passData); + passInfo.pass = new GimplePass(passData, index); break; case PASS_LOOP: passData.type = GIMPLE_PASS; - passInfo.pass = new GimplePass(passData); + passInfo.pass = new GimplePass(passData, index); break; default: - passInfo.pass = new GimplePass(passData); + passInfo.pass = new GimplePass(passData, index); break; } - register_callback(pluginName.c_str(), PLUGIN_PASS_MANAGER_SETUP, NULL, &passInfo); - return 0; + if (pluginName != "") { + register_callback(pluginName.c_str(), PLUGIN_PASS_MANAGER_SETUP, NULL, &passInfo); + } } static bool PluginVersionCheck(struct plugin_gcc_version *gccVersion, struct plugin_gcc_version *pluginVersion) @@ -274,46 +259,14 @@ static bool PluginVersionCheck(struct plugin_gcc_version *gccVersion, struct plu int plugin_init(struct plugin_name_args *pluginInfo, struct plugin_gcc_version *version) { + if (!PluginVersionCheck(version, &gcc_version)) { + LOGE("incompatible gcc/plugin versions\n"); + return 1; + } string pluginName = pluginInfo->base_name; register_callback(pluginName.c_str(), PLUGIN_FINISH, &GccEnd, NULL); - int timeout = 200; // 默认超时时间200ms - string shaPath; - string serverPath = ""; - string arg = ""; - LogPriority logLevel = PRIORITY_WARN; - PluginClient::GetArg(pluginInfo, serverPath, arg, logLevel); - if (PluginClient::GetInitInfo(serverPath, shaPath, timeout) != 0) { - LOGD("read default info from pin-gcc-client.json fail! use the default timeout=%dms\n", timeout); - } - if (serverPath == "") { - LOGE("server path is NULL!\n"); - return 0; - } - - if (PluginClient::CheckSHA256(shaPath) != 0) { - LOGE("sha256 check sha256 file:%s fail!\n", shaPath.c_str()); - return 0; - } else { - LOGD("sha256 check success!\n"); - } - - string port; - int status; - if (ServerStart(timeout, serverPath, g_serverPid, port, logLevel) != 0) { - return 0; - } - ClientStart(timeout, arg, pluginName, port); - std::shared_ptr client = PluginClient::GetInstance(); - while (1) { - if ((client->GetInjectFlag()) || (client->GetUserFuncState() == STATE_TIMEOUT)) { - break; - } - if (g_serverPid == waitpid(-1, &status, WNOHANG)) { - PluginClient::DeletePortFromLockFile((unsigned short)atoi(port.c_str())); - break; - } - } + PluginClient::GetInstance()->Init(pluginInfo, pluginName, g_serverPid); return 0; } -- 2.27.0.windows.1