Skip to content
This repository was archived by the owner on Jan 19, 2025. It is now read-only.

levashov_evgeniy_labs #311

Open
wants to merge 1 commit into
base: course-spring-2024
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions clang/labs/lab1/levashov_evgeniy/AlwaysInline.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "llvm/Support/raw_ostream.h"

namespace {
class AlwaysInlineVisitor
: public clang::RecursiveASTVisitor<AlwaysInlineVisitor> {
public:
explicit AlwaysInlineVisitor(clang::ASTContext *context_)
: context(context_) {}
bool VisitFunctionDecl(clang::FunctionDecl *decl) {
if (decl->isFunctionOrFunctionTemplate() &&
!decl->hasAttr<clang::AlwaysInlineAttr>()) {
auto body = decl->getBody();
if (body && !containsConditionalStatement(body)) {
auto loc = decl->getSourceRange();
if (loc.isValid()) {
decl->addAttr(
clang::AlwaysInlineAttr::Create(*context, loc.getBegin()));
}
}
}
return true;
}

private:
bool containsConditionalStatement(clang::Stmt *statement) {
if (!statement) {
return false;
}

if (llvm::isa<clang::IfStmt>(statement) || llvm::isa<clang::SwitchStmt>(statement) ||
llvm::isa<clang::WhileStmt>(statement) || llvm::isa<clang::DoStmt>(statement) ||
llvm::isa<clang::ForStmt>(statement)) {
return true;
}

for (clang::Stmt *Child : statement->children()) {
if (containsConditionalStatement(Child)) {
return true;
}
}

return false;
}

private:
clang::ASTContext *context;
};

class AlwaysInlineConsumer : public clang::ASTConsumer {
public:
explicit AlwaysInlineConsumer(clang::ASTContext *сontext)
: visitor(сontext) {}

bool HandleTopLevelDecl(clang::DeclGroupRef groupDecl) override {
for (clang::Decl *Decl : groupDecl) {
visitor.TraverseDecl(Decl);
}
return true;
}

private:
AlwaysInlineVisitor visitor;
};

class AlwaysInlinePlugin final : public clang::PluginASTAction {
public:
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &ci, llvm::StringRef) override {
return std::make_unique<AlwaysInlineConsumer>(&ci.getASTContext());
}

bool ParseArgs(const clang::CompilerInstance &ci,
const std::vector<std::string> &args) override {
for (const auto &arg : args) {
if (arg == "--help") {
llvm::outs() << "Applies the always_inline attribute to functions that "
"don't contain conditional statements\n";
}
}
return true;
}
};
} // namespace

static clang::FrontendPluginRegistry::Add<AlwaysInlinePlugin>
X("always-inline", "Applies the always_inline attribute to functions that "
"don't contain conditional statements");
14 changes: 14 additions & 0 deletions clang/labs/lab1/levashov_evgeniy/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
add_llvm_library(PluginAlwaysInlineLevashov MODULE AddAttrAlwaysInline.cpp PLUGIN_TOOL clang)

if(WIN32 OR CYGWIN)
set(LLVM_LINK_COMPONENTS
Support
)
clang_target_link_libraries(PluginAlwaysInlineLevashov PRIVATE
clangAST
clangBasic
clangFrontend
)
endif()

set(CLANG_TEST_DEPS "PluginAlwaysInlineLevashov" ${CLANG_TEST_DEPS} PARENT_SCOPE)
44 changes: 44 additions & 0 deletions clang/test/lab1/levashov_evgeniy/tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// RUN: %clang_cc1 -load %llvmshlibdir/PluginAlwaysInlineLevashov%pluginext\
// RUN: -add-plugin always-inline %s\
// RUN: -ast-dump %s -ast-dump-filter test | FileCheck %s

namespace {
// CHECK: FunctionDecl {{0[xX][0-9a-fA-F]+ <.+tests\.cpp:([0-9]+:[0-9]|[0-9]+), (line|col):([0-9]+:[0-9]|[0-9]+)> (line|col):([0-9]+:[0-9]|[0-9]+) testMultiply 'int \(int, int\)'}}
// CHECK: `-AlwaysInlineAttr {{.* always_inline}}
int testMultiply(int valueOne, int valueTwo) { return valueOne * valueTwo; }

// CHECK: FunctionDecl {{0[xX][0-9a-fA-F]+ <.+tests\.cpp:([0-9]+:[0-9]|[0-9]+), (line|col):([0-9]+:[0-9]|[0-9]+)> (line|col):([0-9]+:[0-9]|[0-9]+) testSum 'int \(int, int\)'}}
// CHECK: `-AlwaysInlineAttr {{.* always_inline}}
int testSum(int valueOne, int valueTwo) {
{} {} {{} {}} {} {{{}} {} {}} {} {
{ return valueOne + valueTwo; }
}
}

// CHECK: FunctionDecl {{0[xX][0-9a-fA-F]+ <.+tests\.cpp:([0-9]+:[0-9]|[0-9]+), (line|col):([0-9]+:[0-9]|[0-9]+)> (line|col):([0-9]+:[0-9]|[0-9]+) testEmptyFunc 'void \(\)'}}
// CHECK: `-AlwaysInlineAttr {{.* always_inline}}
void testEmptyFunc() {
{} {{}} {{} {} {{{{}}}}} {}
}

// CHECK: FunctionDecl {{0[xX][0-9a-fA-F]+ <.+tests\.cpp:([0-9]+:[0-9]|[0-9]+), (line|col):([0-9]+:[0-9]|[0-9]+)> (line|col):([0-9]+:[0-9]|[0-9]+) testIfStmt 'bool \(int, int\)'}}
bool testIfStmt(int a, int b) {
if (a < b)
return true;
return false;
}
// CHECK-NOT: `-AlwaysInlineAttr {{0[xX][0-9a-fA-F]+ <(line|col):([0-9]+:[0-9]|[0-9]+)> Implicit always_inline}}

// CHECK: FunctionDecl {{0[xX][0-9a-fA-F]+ <.+tests\.cpp:([0-9]+:[0-9]|[0-9]+), (line|col):([0-9]+:[0-9]|[0-9]+)> (line|col):([0-9]+:[0-9]|[0-9]+) testLoop 'void \(int\)'}}
void testLoop(int value) {
for (int i = 0; i < value; ++i) {
// do nothing
}
}
// CHECK-NOT: `-AlwaysInlineAttr {{0[xX][0-9a-fA-F]+ <(line|col):([0-9]+:[0-9]|[0-9]+)> Implicit always_inline}}
} // namespace

// RUN: %clang_cc1 -load %llvmshlibdir/PluginAlwaysInlineLevashov%pluginext\
// RUN: -plugin always-inline\
// RUN: -plugin-arg-always-inline --help %s 2>&1 | FileCheck %s --check-prefix=CHECK-HELP
// CHECK-HELP: Applies the always_inline attribute to functions that don't contain conditional statements
12 changes: 12 additions & 0 deletions llvm/labs/lab2/levashov_evgeniy/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
set(Plugin_Name "levashov_evgeniy_inline_pass")
if (NOT WIN32 AND NOT CYGWIN)

file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h *.hpp)
add_llvm_pass_plugin( ${Plugin_Name} ${ALL_SOURCE_FILES}
DEPENDS intrinsics_gen BUILDTREE_ONLY)
set(LLVM_TEST_DEPENDS ${Plugin_Name} ${LLVM_TEST_DEPENDS} PARENT_SCOPE)

message(STATUS "Plugin: ${Plugin_Name} -- BUILDED")
else()
message(STATUS "Plugin: ${Plugin_Name} -- NOT BUILT")
endif()
197 changes: 197 additions & 0 deletions llvm/labs/lab2/levashov_evgeniy/levashov_inline.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/PassPlugin.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <string>

using namespace llvm;

namespace {

struct LevashovInlinePass : public PassInfoMixin<LevashovInlinePass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
std::vector<CallInst *> callsToInline = findCallsToInline(F);

if (callsToInline.empty())
return PreservedAnalyses::all();

processCallSites(F, callsToInline);

return PreservedAnalyses::none();
}

static bool isRequired() { return true; }

private:
std::vector<CallInst *> findCallsToInline(Function &F) {
std::vector<CallInst *> callsToInline{};
for (auto &BB : F) {
for (auto &I : BB) {
if (auto *CI = dyn_cast<CallInst>(&I)) {
if (Function *Callee = CI->getCalledFunction()) {
if (Callee->arg_size() == 0 &&
Callee->getReturnType()->isVoidTy()) {
callsToInline.push_back(CI);
}
}
}
}
}
return callsToInline;
}

void processCallSites(Function &F, std::vector<CallInst *> &callsToInline) {
size_t counter_splited = 0;
size_t counter_inlined = 0;

for (CallInst *CI : callsToInline) {
BasicBlock *InsertBB = CI->getParent();
Instruction *InsertPt = CI->getNextNode();

DenseMap<BasicBlock *, BasicBlock *> BlockMap;
Function *Callee = CI->getCalledFunction();
ValueToValueMapTy VMap;

BasicBlock *SplitBB =
splitBlockAtCallSite(InsertBB, InsertPt, counter_splited);
createNewBlocksForFunction(F, Callee, BlockMap, counter_inlined);
updateTerminatorOfInsertBB(InsertBB, Callee, BlockMap);

copyInstructionsFromCallee(F, Callee, BlockMap, VMap);
updateBranchInstructions(F, BlockMap);
remapInstructions(Callee, BlockMap, VMap);

handleReturnInstructions(F, SplitBB);
CI->eraseFromParent();
moveSplitBBAfterNextBlock(F, SplitBB);
}
}

BasicBlock *splitBlockAtCallSite(BasicBlock *InsertBB, Instruction *InsertPt,
size_t &counter_splited) {
return InsertBB->splitBasicBlock(InsertPt,
InsertBB->getName() + ".splited." +
std::to_string(counter_splited++));
}

void
createNewBlocksForFunction(Function &F, Function *Callee,
DenseMap<BasicBlock *, BasicBlock *> &BlockMap,
size_t &counter_inlined) {
for (BasicBlock &CalleeBB : *Callee) {
BasicBlock *NewBB = BasicBlock::Create(
F.getContext(),
CalleeBB.getName() + ".inlined." + std::to_string(counter_inlined),
&F);
BlockMap[&CalleeBB] = NewBB;
}
counter_inlined++;
}

void
updateTerminatorOfInsertBB(BasicBlock *InsertBB, Function *Callee,
DenseMap<BasicBlock *, BasicBlock *> &BlockMap) {
InsertBB->getTerminator()->setSuccessor(0,
BlockMap[&Callee->getEntryBlock()]);
}

void
copyInstructionsFromCallee(Function &F, Function *Callee,
DenseMap<BasicBlock *, BasicBlock *> &BlockMap,
ValueToValueMapTy &VMap) {
for (BasicBlock &CalleeBB : *Callee) {
BasicBlock *NewBB = BlockMap[&CalleeBB];
for (Instruction &Inst : CalleeBB) {
IRBuilder<> Builder(NewBB);
Instruction *NewInst = Inst.clone();
Builder.Insert(NewInst);
VMap[&Inst] = NewInst;
}
}
}

void
updateBranchInstructions(Function &F,
DenseMap<BasicBlock *, BasicBlock *> &BlockMap) {
for (BasicBlock &CalleeBB : F) {
for (Instruction &Branch : CalleeBB) {
if (auto *BI = dyn_cast<BranchInst>(&Branch)) {
for (size_t i = 0, e = BI->getNumSuccessors(); i != e; ++i) {
BasicBlock *Successor = BI->getSuccessor(i);
if (BlockMap[Successor] != nullptr) {
BI->setSuccessor(i, BlockMap[Successor]);
}
}
}
}
}
}

void remapInstructions(Function *Callee,
DenseMap<BasicBlock *, BasicBlock *> &BlockMap,
ValueToValueMapTy &VMap) {
for (BasicBlock &CalleeBB : *Callee) {
BasicBlock *NewBB = BlockMap[&CalleeBB];
for (Instruction &Inst : *NewBB) {
RemapInstruction(&Inst, VMap, RF_IgnoreMissingLocals, nullptr, nullptr);
}
}
}

void handleReturnInstructions(Function &F, BasicBlock *SplitBB) {
IRBuilder<> Builder(F.getContext());
for (BasicBlock &BB : F) {
SmallVector<ReturnInst *, 16> ReturnInstructions;
for (Instruction &I : BB) {
if (auto *RI = dyn_cast<ReturnInst>(&I)) {
ReturnInstructions.push_back(RI);
}
}

for (ReturnInst *RI : ReturnInstructions) {
if (RI->getParent() != SplitBB) {
RI->eraseFromParent();
Builder.SetInsertPoint(&BB);
Builder.CreateBr(SplitBB);
}
}
}
}

void moveSplitBBAfterNextBlock(Function &F, BasicBlock *SplitBB) {
Function::iterator it = F.begin();
while (it != F.end() && &*it != SplitBB) {
++it;
}
Function::iterator next_it{};
while (it != F.end() && std::next(it) != F.end()) {
next_it = std::next(it++);
}
if (it != F.end())
SplitBB->moveAfter(&*next_it);
}
};

} // end anonymous namespace

extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo() {
return {LLVM_PLUGIN_API_VERSION, "LevashovInlinePass", "v0.1",
[](PassBuilder &PB) {
PB.registerPipelineParsingCallback(
[](StringRef Name, FunctionPassManager &FPM,
ArrayRef<PassBuilder::PipelineElement>) {
if (Name == "levashov-inline") {
FPM.addPass(LevashovInlinePass());
return true;
}
return false;
});
}};
}
13 changes: 13 additions & 0 deletions llvm/lib/Target/X86/lab3/levashov_evgeniy/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
set(PluginName X86LevashovPass)

file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp)
add_llvm_pass_plugin(${PluginName}
${ALL_SOURCE_FILES}
DEPENDS
intrinsics_gen
X86
BUILDTREE_ONLY)

target_include_directories(${PluginName} PUBLIC ${PATH_TO_X86})

set(LLVM_TEST_DEPENDS ${PluginName} ${LLVM_TEST_DEPENDS} PARENT_SCOPE)
Loading
Loading