File: LLVMUtils.h

package info (click to toggle)
pocl 6.0-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 25,304 kB
  • sloc: lisp: 149,513; ansic: 103,778; cpp: 54,947; python: 1,513; sh: 949; ruby: 255; pascal: 226; tcl: 180; makefile: 173; java: 72; xml: 49
file content (223 lines) | stat: -rw-r--r-- 10,475 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Header for LLVMUtils, useful common LLVM-related functionality.
//
// Copyright (c) 2013-2019 Pekka Jääskeläinen
//               2023 Pekka Jääskeläinen / Intel Finland Oy
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#ifndef POCL_LLVM_UTILS_H
#define POCL_LLVM_UTILS_H

#include "CompilerWarnings.h"
IGNORE_COMPILER_WARNING("-Wmaybe-uninitialized")
#include <llvm/ADT/Twine.h>
POP_COMPILER_DIAGS
IGNORE_COMPILER_WARNING("-Wunused-parameter")
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include <llvm/Passes/PassBuilder.h>
#include <llvm/Passes/PassPlugin.h>
#include <llvm/Transforms/Utils/Cloning.h> // for CloneFunctionIntoAbs
POP_COMPILER_DIAGS

#include <map>
#include <string>

#include "pocl.h"
#include "pocl_spir.h"


namespace llvm {
    class Module;
    class Function;
    class GlobalVariable;
}

namespace pocl {

typedef std::map<llvm::Function*, llvm::Function*> FunctionMapping;

constexpr unsigned NumWorkgroupVariables = 18;
extern const char *WorkgroupVariablesArray[];
extern const std::vector<std::string> WorkgroupVariablesVector;
constexpr unsigned NumWIFuncNames = 11;
extern const char *WIFuncNameArray[];
extern const std::vector<std::string> WIFuncNameVec;

void regenerate_kernel_metadata(llvm::Module &M, FunctionMapping &kernels);

void breakConstantExpressions(llvm::Value *Val, llvm::Function *Func);

// Remove a function from a module, along with all callsites.
POCL_EXPORT
void eraseFunctionAndCallers(llvm::Function *Function);

bool isAutomaticLocal(llvm::Function *F, llvm::GlobalVariable &Var);

POCL_EXPORT
bool isGVarUsedByFunction(llvm::GlobalVariable *GVar, llvm::Function *F);

// Checks if the given argument of Func is a local buffer.
bool isLocalMemFunctionArg(llvm::Function *Func, unsigned ArgIndex);

// determines if GVar is OpenCL program-scope variable
// if it has empty name, sets it to __anonymous_global_as.XYZ
bool isProgramScopeVariable(llvm::GlobalVariable &GVar, unsigned DeviceLocalAS);

// Sets the address space metadata of the given function argument.
// Note: The address space ids must be SPIR ids. If it encounters
// argument indices without address space ids in the list, sets
// them to globals.
void setFuncArgAddressSpaceMD(llvm::Function *Func, unsigned ArgIndex,
                              unsigned AS);

bool hasWorkgroupBarriers(const llvm::Function &F);

POCL_EXPORT
bool isKernelToProcess(const llvm::Function &F);

llvm::Metadata *createConstantIntMD(llvm::LLVMContext &C, int32_t Val);

// Fixes switch statements that have a default case that is a simple
// unreachable instruction. LLVM does this as "optimization", however it breaks
// the (post) dominator-tree analysis, because the unreachable instruction
// creates an additional function exit path. PoCL's ImplicitConditionalBarriers
// pass then erroneously adds barriers because it thinks some basic blocks are
// inside conditional blocks, when they're not.
// TODO this is fragile, LLVM can introduce more optimizations that create
// unreachable blocks. However I couldn't find any working way to make PDT
// ignore blocks with an unreachable inst.
void removeUnreachableSwitchCases(llvm::Function &F);

/**
 * \brief Clones a DISubprogram with changed function name and scope.
 *
 * \param [in] Old The DISubprogram to clone.
 * \param [in] NewFuncName A new function name.
 * \param [in] Scope New scope.
 * \returns a new DISubprogram.
 *
 */
llvm::DISubprogram *mimicDISubprogram(llvm::DISubprogram *Old,
                                      const llvm::StringRef &NewFuncName,
                                      llvm::DIScope *Scope = nullptr);

#if LLVM_MAJOR >= MIN_LLVM_NEW_PASSMANAGER
void registerPassBuilderPasses(llvm::PassBuilder &PB);

void registerFunctionAnalyses(llvm::PassBuilder &PB);
#endif
} // namespace pocl

template <typename VectorT>
void CloneFunctionIntoAbs(llvm::Function *NewFunc,
                          const llvm::Function *OldFunc,
                          llvm::ValueToValueMapTy &VMap, VectorT &Returns,
                          bool sameModule = true,
                          const char *NameSuffix = "",
                          llvm::ClonedCodeInfo *CodeInfo = nullptr,
                          llvm::ValueMapTypeRemapper *TypeMapper = nullptr,
                          llvm::ValueMaterializer *Materializer = nullptr) {

                    // ClonedModule DifferentModule LocalChangesOnly
                    // GlobalChanges
  CloneFunctionInto(NewFunc, OldFunc, VMap,
                    (sameModule ? llvm::CloneFunctionChangeType::GlobalChanges
                                : llvm::CloneFunctionChangeType::DifferentModule),
                    Returns, NameSuffix, CodeInfo, TypeMapper, Materializer);
}

#if LLVM_MAJOR < 15
// Globals
#define getValueType getType()->getElementType
#endif /* LLVM_OPAQUE_POINTERS */

// macros for registering LLVM passes & analyses with old & new PM

#define REGISTER_NEW_FPASS(PNAME, PCLASS, PDESC)                               \
  void PCLASS::registerWithPB(llvm::PassBuilder &PB) {                         \
    PB.registerPipelineParsingCallback(                                        \
        [](::llvm::StringRef Name, ::llvm::FunctionPassManager &FPM,           \
           llvm::ArrayRef<::llvm::PassBuilder::PipelineElement>) {             \
          if (Name == PNAME) {                                                 \
            FPM.addPass(PCLASS());                                             \
            return true;                                                       \
          }                                                                    \
          return false;                                                        \
        });                                                                    \
  }

#define REGISTER_NEW_MPASS(PNAME, PCLASS, PDESC)                               \
  void PCLASS::registerWithPB(llvm::PassBuilder &PB) {                         \
    PB.registerPipelineParsingCallback(                                        \
        [](::llvm::StringRef Name, ::llvm::ModulePassManager &MPM,             \
           llvm::ArrayRef<::llvm::PassBuilder::PipelineElement>) {             \
          if (Name == PNAME) {                                                 \
            MPM.addPass(PCLASS());                                             \
            return true;                                                       \
          } else                                                               \
            return false;                                                      \
        });                                                                    \
  }

#define REGISTER_NEW_LPASS(PNAME, PCLASS, PDESC)                               \
  void PCLASS::registerWithPB(llvm::PassBuilder &PB) {                         \
    PB.registerPipelineParsingCallback(                                        \
        [](::llvm::StringRef Name, ::llvm::LoopPassManager &LPM,               \
           ::llvm::ArrayRef<::llvm::PassBuilder::PipelineElement>) {           \
          if (Name == PNAME) {                                                 \
            LPM.addPass(PCLASS());                                             \
            return true;                                                       \
          } else                                                               \
            return false;                                                      \
        });                                                                    \
  }

#define REGISTER_NEW_FANALYSIS(PNAME, PCLASS, PDESC)                           \
  void PCLASS::registerWithPB(llvm::PassBuilder &PB) {                         \
    PB.registerPipelineParsingCallback(                                        \
        [](::llvm::StringRef Name, ::llvm::FunctionPassManager &FPM,           \
           llvm::ArrayRef<::llvm::PassBuilder::PipelineElement>) {             \
          if (Name == "require<" PNAME ">") {                                  \
            FPM.addPass(RequireAnalysisPass<PCLASS, llvm::Function>());        \
            return true;                                                       \
          } else                                                               \
            return false;                                                      \
        });                                                                    \
    PB.registerAnalysisRegistrationCallback(                                   \
        [](::llvm::FunctionAnalysisManager &FAM) {                             \
          FAM.registerPass([&] { return PCLASS(); });                          \
        });                                                                    \
  }

#define REGISTER_OLD_FPASS(PNAME, PCLASS, PDESC)                               \
  static llvm::RegisterPass<PCLASS> X(PNAME, PDESC)

#define REGISTER_OLD_MPASS(PNAME, PCLASS, PDESC)                               \
  static llvm::RegisterPass<PCLASS> X(PNAME, PDESC)

#define REGISTER_OLD_LPASS(PNAME, PCLASS, PDESC)                               \
  static llvm::RegisterPass<PCLASS> X(PNAME, PDESC)

#define REGISTER_OLD_FANALYSIS(PNAME, PCLASS, PDESC)                          \
  static llvm::RegisterPass<PCLASS> X (PNAME, PDESC)

#endif