Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/SPIRVWriter.h

raw
1 //===- SPIRVWriter.h - Converts LLVM to SPIR-V ------------------*- C++ -*-===//
2 //
3 // The LLVM/SPIR-V Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of Advanced Micro Devices, Inc., nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 /// \file
35 ///
36 /// This file contains declaration of LLVMToSPIRV class which implements
37 /// conversion of LLVM intermediate language to SPIR-V
38 /// binary.
39 ///
40 //===----------------------------------------------------------------------===//
41
42 #ifndef SPIRVWRITER_H
43 #define SPIRVWRITER_H
44
45 #include "LLVMToSPIRVDbgTran.h"
46 #include "OCLTypeToSPIRV.h"
47 #include "OCLUtil.h"
48 #include "SPIRVBasicBlock.h"
49 #include "SPIRVBuiltinHelper.h"
50 #include "SPIRVEntry.h"
51 #include "SPIRVEnum.h"
52 #include "SPIRVFunction.h"
53 #include "SPIRVInstruction.h"
54 #include "SPIRVModule.h"
55 #include "SPIRVType.h"
56 #include "SPIRVTypeScavenger.h"
57 #include "SPIRVValue.h"
58
59 #include "llvm/ADT/SmallSet.h"
60 #include "llvm/ADT/StringMap.h"
61 #include "llvm/Analysis/CallGraph.h"
62 #include "llvm/IR/IntrinsicInst.h"
63
64 #include <memory>
65
66 using namespace llvm;
67 using namespace SPIRV;
68 using namespace OCLUtil;
69
70 namespace SPIRV {
71
72 class LLVMToSPIRVBase : protected BuiltinCallHelper {
73 public:
74 LLVMToSPIRVBase(SPIRVModule *SMod);
75 bool runLLVMToSPIRV(Module &Mod);
76
77 // This enum sets the mode used to translate the value which is
78 // a function, that is necessary for a convenient function pointers handling.
79 // By default transValue uses 'Decl' mode, which means every function
80 // we meet during the translation should result in its declaration generated.
81 // In 'Pointer' mode we generate OpConstantFunctionPointerINTEL constant
82 // instead.
83 enum class FuncTransMode { Decl, Pointer };
84
85 SPIRVType *transType(Type *T);
86 SPIRVType *transPointerType(Type *PointeeTy, unsigned AddrSpace);
87 SPIRVType *transPointerType(SPIRVType *PointeeTy, unsigned AddrSpace);
88 SPIRVType *transSPIRVOpaqueType(StringRef STName, unsigned AddrSpace);
89 SPIRVType *
90 transSPIRVJointMatrixINTELType(SmallVector<std::string, 8> Postfixes);
91 /// Use the type scavenger to get the correct type for V. This is equivalent
92 /// to transType(V->getType()) if V is not a pointer type; otherwise, it tries
93 /// to pick an appropriate pointee type for V.
94 SPIRVType *transScavengedType(Value *V);
95
96 SPIRVValue *getTranslatedValue(const Value *) const;
97
98 spv::LoopControlMask getLoopControl(const BranchInst *Branch,
99 std::vector<SPIRVWord> &Parameters);
100
101 // Translation functions
102 bool transAddressingMode();
103 bool transAlign(Value *V, SPIRVValue *BV);
104 std::vector<SPIRVWord> transArguments(CallInst *, SPIRVBasicBlock *,
105 SPIRVEntry *);
106 bool transSourceLanguage();
107 bool transExtension();
108 bool transBuiltinSet();
109 bool isKnownIntrinsic(Intrinsic::ID Id);
110 SPIRVValue *transIntrinsicInst(IntrinsicInst *Intrinsic, SPIRVBasicBlock *BB);
111 enum class FPBuiltinType {
112 REGULAR_MATH,
113 EXT_1OPS,
114 EXT_2OPS,
115 EXT_3OPS,
116 UNKNOWN
117 };
118 FPBuiltinType getFPBuiltinType(IntrinsicInst *II, StringRef &);
119 SPIRVValue *transFPBuiltinIntrinsicInst(IntrinsicInst *II,
120 SPIRVBasicBlock *BB);
121 SPIRVValue *transFenceInst(FenceInst *FI, SPIRVBasicBlock *BB);
122 SPIRVValue *transCallInst(CallInst *Call, SPIRVBasicBlock *BB);
123 SPIRVValue *transDirectCallInst(CallInst *Call, SPIRVBasicBlock *BB);
124 SPIRVValue *transIndirectCallInst(CallInst *Call, SPIRVBasicBlock *BB);
125 SPIRVValue *transAsmINTEL(InlineAsm *Asm);
126 SPIRVValue *transAsmCallINTEL(CallInst *Call, SPIRVBasicBlock *BB);
127 bool transDecoration(Value *V, SPIRVValue *BV);
128 bool shouldTryToAddMemAliasingDecoration(Instruction *V);
129 void transMemAliasingINTELDecorations(Instruction *V, SPIRVValue *BV);
130 SPIRVWord transFunctionControlMask(Function *);
131 SPIRVFunction *transFunctionDecl(Function *F);
132 void transVectorComputeMetadata(Function *F);
133 void transFPGAFunctionMetadata(SPIRVFunction *BF, Function *F);
134 void transFunctionMetadataAsExecutionMode(SPIRVFunction *BF, Function *F);
135 void transFunctionMetadataAsUserSemanticDecoration(SPIRVFunction *BF,
136 Function *F);
137 void transAuxDataInst(SPIRVFunction *BF, Function *F);
138
139 bool transGlobalVariables();
140
141 Op transBoolOpCode(SPIRVValue *Opn, Op OC);
142 // Translate LLVM module to SPIR-V module.
143 // Returns true if succeeds.
144 bool translate();
145 bool transExecutionMode();
146 void transFPContract();
147 SPIRVValue *transConstant(Value *V);
148 /// Translate a reference to a constant in a constant expression. This may
149 /// involve inserting extra bitcasts to correct type issues.
150 SPIRVValue *transConstantUse(Constant *V, SPIRVType *ExpectedType);
151 SPIRVValue *transValue(Value *V, SPIRVBasicBlock *BB,
152 bool CreateForward = true,
153 FuncTransMode FuncTrans = FuncTransMode::Decl);
154 void transGlobalAnnotation(GlobalVariable *V);
155 SPIRVValue *
156 transValueWithoutDecoration(Value *V, SPIRVBasicBlock *BB,
157 bool CreateForward = true,
158 FuncTransMode FuncTrans = FuncTransMode::Decl);
159 void transGlobalIOPipeStorage(GlobalVariable *V, MDNode *IO);
160
161 static SPIRVInstruction *applyRoundingModeConstraint(Value *V,
162 SPIRVInstruction *I);
163
164 typedef DenseMap<Type *, SPIRVType *> LLVMToSPIRVTypeMap;
165 typedef DenseMap<Value *, SPIRVValue *> LLVMToSPIRVValueMap;
166 typedef DenseMap<MDNode *, SmallSet<SPIRVId, 2>> LLVMToSPIRVMetadataMap;
167
168 void setOCLTypeToSPIRV(OCLTypeToSPIRVBase *OCLTypeToSPIRV) {
169 OCLTypeToSPIRVPtr = OCLTypeToSPIRV;
170 }
171 OCLTypeToSPIRVBase *getOCLTypeToSPIRV() { return OCLTypeToSPIRVPtr; }
172 ~LLVMToSPIRVBase();
173
174 private:
175 Module *M;
176 LLVMContext *Ctx;
177 SPIRVModule *BM;
178
179 // This maps LLVM types (except for pointers) to SPIRVType.
180 LLVMToSPIRVTypeMap TypeMap;
181 // This maps {struct name, addrspace} to SPIRVType, for those structs that
182 // represent special SPIRV types.
183 DenseMap<std::pair<StringRef, unsigned>, SPIRVType *> OpaqueStructMap;
184 // This maps <type-unique keys> to SPIRVType, for use in function types.
185 StringMap<SPIRVType *> PointeeTypeMap;
186
187 /// Get the SPIRVFunctionType with appropriate return and argument types,
188 /// returning an existing instance if one has already been created. This is
189 /// necessary to unique locally, as SPIRVModule does not do such uniquing.
190 SPIRVType *getSPIRVFunctionType(SPIRVType *RT,
191 const std::vector<SPIRVType *> &Args);
192
193 LLVMToSPIRVValueMap ValueMap;
194 LLVMToSPIRVMetadataMap IndexGroupArrayMap;
195 SPIRVWord SrcLang;
196 SPIRVWord SrcLangVer;
197 std::unique_ptr<LLVMToSPIRVDbgTran> DbgTran;
198 std::unique_ptr<CallGraph> CG;
199 OCLTypeToSPIRVBase *OCLTypeToSPIRVPtr = nullptr;
200 std::vector<llvm::Instruction *> UnboundInst;
201 std::unique_ptr<SPIRVTypeScavenger> Scavenger;
202
203 enum class FPContract { UNDEF, DISABLED, ENABLED };
204 DenseMap<Function *, FPContract> FPContractMap;
205 FPContract getFPContract(Function *F);
206 bool joinFPContract(Function *F, FPContract C);
207 void fpContractUpdateRecursive(Function *F, FPContract FPC);
208
209 SPIRVType *mapType(Type *T, SPIRVType *BT);
210 SPIRVValue *mapValue(Value *V, SPIRVValue *BV);
211 SPIRVErrorLog &getErrorLog() { return BM->getErrorLog(); }
212 llvm::IntegerType *getSizetType(unsigned AS = 0);
213 std::vector<SPIRVValue *> transValue(const std::vector<Value *> &Values,
214 SPIRVBasicBlock *BB);
215 std::vector<SPIRVWord> transValue(const std::vector<Value *> &Values,
216 SPIRVBasicBlock *BB, SPIRVEntry *Entry);
217 SPIRVInstruction *transBinaryInst(BinaryOperator *B, SPIRVBasicBlock *BB);
218 SPIRVInstruction *transCmpInst(CmpInst *Cmp, SPIRVBasicBlock *BB);
219 SPIRVInstruction *transLifetimeIntrinsicInst(Op OC, IntrinsicInst *Intrinsic,
220 SPIRVBasicBlock *BB);
221
222 SPIRVValue *transAtomicStore(StoreInst *ST, SPIRVBasicBlock *BB);
223 SPIRVValue *transAtomicLoad(LoadInst *LD, SPIRVBasicBlock *BB);
224
225 void dumpUsers(Value *V);
226
227 template <class ExtInstKind>
228 bool oclGetExtInstIndex(const std::string &MangledName,
229 const std::string &DemangledName,
230 SPIRVWord *EntryPoint);
231 void
232 oclGetMutatedArgumentTypesByBuiltin(llvm::FunctionType *FT,
233 std::map<unsigned, Type *> &ChangedType,
234 Function *F);
235 bool isBuiltinTransToInst(Function *F);
236 bool isBuiltinTransToExtInst(Function *F,
237 SPIRVExtInstSetKind *BuiltinSet = nullptr,
238 SPIRVWord *EntryPoint = nullptr,
239 SmallVectorImpl<std::string> *Dec = nullptr);
240 bool isKernel(Function *F);
241 bool transMetadata();
242 bool transOCLMetadata();
243 SPIRVInstruction *transBuiltinToInst(StringRef DemangledName, CallInst *CI,
244 SPIRVBasicBlock *BB);
245 SPIRVValue *transBuiltinToConstant(StringRef DemangledName, CallInst *CI);
246 SPIRVInstruction *transBuiltinToInstWithoutDecoration(Op OC, CallInst *CI,
247 SPIRVBasicBlock *BB);
248 void mutateFuncArgType(const std::map<unsigned, Type *> &ChangedType,
249 Function *F);
250
251 SPIRVValue *transSpcvCast(CallInst *CI, SPIRVBasicBlock *BB);
252 SPIRVValue *oclTransSpvcCastSampler(CallInst *CI, SPIRVBasicBlock *BB);
253 SPIRVValue *transUnaryInst(UnaryInstruction *U, SPIRVBasicBlock *BB);
254
255 void transFunction(Function *I);
256 SPIRV::SPIRVLinkageTypeKind transLinkageType(const GlobalValue *GV);
257
258 bool isAnyFunctionReachableFromFunction(
259 const Function *FS,
260 const std::unordered_set<const Function *> Funcs) const;
261 std::vector<SPIRVId> collectEntryPointInterfaces(SPIRVFunction *BF,
262 Function *F);
263 };
264
265 class LLVMToSPIRVPass : public PassInfoMixin<LLVMToSPIRVPass> {
266 public:
267 LLVMToSPIRVPass(SPIRVModule *SMod) : SMod(SMod) {}
268
269 llvm::PreservedAnalyses run(llvm::Module &M,
270 llvm::ModuleAnalysisManager &MAM) {
271 LLVMToSPIRVBase PassInstance(SMod);
272 PassInstance.setOCLTypeToSPIRV(&MAM.getResult<OCLTypeToSPIRVPass>(M));
273 return PassInstance.runLLVMToSPIRV(M) ? llvm::PreservedAnalyses::none()
274 : llvm::PreservedAnalyses::all();
275 }
276
277 private:
278 SPIRVModule *SMod;
279 };
280
281 class LLVMToSPIRVLegacy : public ModulePass, public LLVMToSPIRVBase {
282 public:
283 LLVMToSPIRVLegacy(SPIRVModule *SMod = nullptr)
284 : ModulePass(ID), LLVMToSPIRVBase(SMod) {}
285
286 virtual StringRef getPassName() const override { return "LLVMToSPIRV"; }
287
288 bool runOnModule(Module &Mod) override {
289 setOCLTypeToSPIRV(&getAnalysis<OCLTypeToSPIRVLegacy>());
290 return runLLVMToSPIRV(Mod);
291 }
292
293 void getAnalysisUsage(AnalysisUsage &AU) const override {
294 AU.addRequired<OCLTypeToSPIRVLegacy>();
295 }
296
297 static char ID;
298 };
299
300 } // namespace SPIRV
301
302 #endif // SPIRVWRITER_H