From a9863e2b6e6783aa9be0b9d1d187084fd4b32a3a Mon Sep 17 00:00:00 2001
From: Muhammad Asif Manzoor <muhammad.asif.manzoor1@huawei.com>
Date: Thu, 21 Mar 2024 12:50:38 -0400
Subject: [PATCH] Add BiSheng Autotuner support for LLVM compiler

Automatic tuning is an automatic iterative process that optimizes a given
program by manipulating compilation options for optimal performance.
BiSheng Autotuner provides a resumable interface for tuning process. BiSheng
Autotuner can tune 1) individual code segments/blocks (fine grain turning) like
loops, callsites, instructions, etc. and 2) entire modules/programs (coarse
grain tuning) for compiler flags, pass ordering, etc.
This patch enables LLVM compiler to extract tuneable code regions and then apply
suggested configuration (by Autotuner) to find out the optimal configurations.
---
 lld/ELF/Driver.cpp | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp
index c2059c70e15a..ffd0842b9078 100644
--- a/lld/ELF/Driver.cpp
+++ b/lld/ELF/Driver.cpp
@@ -341,6 +341,18 @@ void LinkerDriver::addLibrary(StringRef name) {
 // Technically this can be delayed until we read bitcode files, but
 // we don't bother to do lazily because the initialization is fast.
 static void initLLVM() {
+#if defined(ENABLE_AUTOTUNER)
+  // AUTO-TUNING - initialization
+  if (Error E = autotuning::Engine.init(config->outputFile.data())) {
+    error(toString(std::move(E)));
+    return;
+  }
+  if (autotuning::Engine.isEnabled() && autotuning::Engine.isParseInput() &&
+      (autotuning::Engine.LLVMParams.size() ||
+       autotuning::Engine.ProgramParams.size()))
+    llvm::cl::ParseAutoTunerOptions(autotuning::Engine.LLVMParams,
+                                    autotuning::Engine.ProgramParams);
+#endif
   InitializeAllTargets();
   InitializeAllTargetMCs();
   InitializeAllAsmPrinters();
@@ -2814,6 +2826,12 @@ void LinkerDriver::link(opt::InputArgList &args) {
   reportBackrefs();
   writeArchiveStats();
   writeWhyExtract();
+#if defined(ENABLE_AUTOTUNER)
+  // AUTO-TUNING - finalization
+  if (Error E = autotuning::Engine.finalize()) {
+    error(toString(std::move(E)));
+  }
+#endif
   if (errorCount())
     return;
 
-- 
2.33.0

