blob: b3f72609db52a999b0a7f579b15a7dca3dc05238 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
alan-bakere0902602020-03-23 08:43:40 -040046#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040047
David Neto85082642018-03-24 06:55:20 -070048#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050049#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040050#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070051#include "clspv/spirv_c_strings.hpp"
52#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040053
David Neto4feb7a42017-10-06 17:29:42 -040054#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050055#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050056#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070057#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040058#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040059#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040060#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040061#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040062#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040063#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050064#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040065
David Neto22f144c2017-06-12 14:26:21 -040066#if defined(_MSC_VER)
67#pragma warning(pop)
68#endif
69
70using namespace llvm;
71using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050072using namespace clspv::Builtins;
David Neto156783e2017-07-05 15:39:41 -040073using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040074
75namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040076
David Neto862b7d82018-06-14 18:48:37 -040077cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
78 cl::desc("Show resource variable creation"));
79
alan-baker5ed87542020-03-23 11:05:22 -040080cl::opt<bool>
81 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
82 cl::desc("Dump the IR at the start of SPIRVProducer"));
83
David Neto862b7d82018-06-14 18:48:37 -040084// These hacks exist to help transition code generation algorithms
85// without making huge noise in detailed test output.
86const bool Hack_generate_runtime_array_stride_early = true;
87
David Neto3fbb4072017-10-16 11:28:14 -040088// The value of 1/pi. This value is from MSDN
89// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
90const double kOneOverPi = 0.318309886183790671538;
91const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
92
alan-bakerb6b09dc2018-11-08 16:59:28 -050093const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040094
SJW69939d52020-04-16 07:29:07 -050095// SPIRV Module Sections (per 2.4 of the SPIRV spec)
96// These are used to collect SPIRVInstructions by type on-the-fly.
97enum SPIRVSection {
98 kCapabilities,
99 kExtensions,
100 kImports,
101 kMemoryModel,
102 kEntryPoints,
103 kExecutionModes,
104
105 kDebug,
106 kAnnotations,
107
108 kTypes,
109 kConstants = kTypes,
110 kGlobalVariables,
111
112 kFunctions,
113
114 kSectionCount
115};
116
David Neto22f144c2017-06-12 14:26:21 -0400117enum SPIRVOperandType {
118 NUMBERID,
119 LITERAL_INTEGER,
120 LITERAL_STRING,
121 LITERAL_FLOAT
122};
123
124struct SPIRVOperand {
125 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
126 : Type(Ty), LiteralNum(1, Num) {}
127 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
128 : Type(Ty), LiteralStr(Str) {}
129 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
130 : Type(Ty), LiteralStr(Str) {}
131 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
132 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
133
James Price11010dc2019-12-19 13:53:09 -0500134 SPIRVOperandType getType() const { return Type; };
135 uint32_t getNumID() const { return LiteralNum[0]; };
136 std::string getLiteralStr() const { return LiteralStr; };
137 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400138
David Neto87846742018-04-11 17:36:22 -0400139 uint32_t GetNumWords() const {
140 switch (Type) {
141 case NUMBERID:
142 return 1;
143 case LITERAL_INTEGER:
144 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400145 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400146 case LITERAL_STRING:
147 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400148 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400149 }
150 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
151 }
152
David Neto22f144c2017-06-12 14:26:21 -0400153private:
154 SPIRVOperandType Type;
155 std::string LiteralStr;
156 SmallVector<uint32_t, 4> LiteralNum;
157};
158
David Netoc6f3ab22018-04-06 18:02:31 -0400159class SPIRVOperandList {
160public:
David Netoef5ba2b2019-12-20 08:35:54 -0500161 typedef std::unique_ptr<SPIRVOperand> element_type;
162 typedef SmallVector<element_type, 8> container_type;
163 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400164 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500165 SPIRVOperandList(const SPIRVOperandList &other) = delete;
166 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400167 contents_ = std::move(other.contents_);
168 other.contents_.clear();
169 }
David Netoef5ba2b2019-12-20 08:35:54 -0500170 iterator begin() { return contents_.begin(); }
171 iterator end() { return contents_.end(); }
172 operator ArrayRef<element_type>() { return contents_; }
173 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500174 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400175 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500176 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400177
David Netoef5ba2b2019-12-20 08:35:54 -0500178 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400179
David Netoc6f3ab22018-04-06 18:02:31 -0400180private:
David Netoef5ba2b2019-12-20 08:35:54 -0500181 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400182};
183
James Price11010dc2019-12-19 13:53:09 -0500184SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500185 std::unique_ptr<SPIRVOperand> elem) {
186 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400187 return list;
188}
189
David Netoef5ba2b2019-12-20 08:35:54 -0500190std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
191 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400192}
David Netoef5ba2b2019-12-20 08:35:54 -0500193std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
194 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400195}
David Netoef5ba2b2019-12-20 08:35:54 -0500196std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
197 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400198}
David Netoef5ba2b2019-12-20 08:35:54 -0500199std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
200 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500201}
David Netoef5ba2b2019-12-20 08:35:54 -0500202std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
203 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400204}
David Netoc6f3ab22018-04-06 18:02:31 -0400205
David Neto22f144c2017-06-12 14:26:21 -0400206struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500207 // Creates an instruction with an opcode and no result ID, and with the given
208 // operands. This computes its own word count. Takes ownership of the
209 // operands and clears |Ops|.
210 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
211 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500212 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400213 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400214 }
David Netoef5ba2b2019-12-20 08:35:54 -0500215 Operands.reserve(Ops.size());
216 for (auto &ptr : Ops) {
217 Operands.emplace_back(std::move(ptr));
218 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400219 }
David Netoef5ba2b2019-12-20 08:35:54 -0500220 Ops.clear();
221 }
222 // Creates an instruction with an opcode and a no-zero result ID, and
223 // with the given operands. This computes its own word count. Takes ownership
224 // of the operands and clears |Ops|.
225 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
226 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500227 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400228 WordCount += operand->GetNumWords();
229 }
David Netoef5ba2b2019-12-20 08:35:54 -0500230 Operands.reserve(Ops.size());
231 for (auto &ptr : Ops) {
232 Operands.emplace_back(std::move(ptr));
233 ptr.reset(nullptr);
234 }
235 if (ResID == 0) {
236 llvm_unreachable("Result ID of 0 was provided");
237 }
238 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400239 }
David Neto22f144c2017-06-12 14:26:21 -0400240
David Netoef5ba2b2019-12-20 08:35:54 -0500241 // Creates an instruction with an opcode and no result ID, and with the single
242 // operand. This computes its own word count.
243 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
244 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
245 WordCount += operand->GetNumWords();
246 Operands.emplace_back(std::move(operand));
247 operand.reset(nullptr);
248 }
249 // Creates an instruction with an opcode and a non-zero result ID, and
250 // with the single operand. This computes its own word count.
251 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
252 SPIRVOperandList::element_type operand)
253 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
254 WordCount += operand->GetNumWords();
255 if (ResID == 0) {
256 llvm_unreachable("Result ID of 0 was provided");
257 }
258 Operands.emplace_back(std::move(operand));
259 operand.reset(nullptr);
260 }
261 // Creates an instruction with an opcode and a no-zero result ID, and no
262 // operands.
263 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
264 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
265 if (ResID == 0) {
266 llvm_unreachable("Result ID of 0 was provided");
267 }
268 }
269 // Creates an instruction with an opcode, no result ID, no type ID, and no
270 // operands.
271 SPIRVInstruction(spv::Op Opc)
272 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
273
David Netoee2660d2018-06-28 16:31:29 -0400274 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400275 uint16_t getOpcode() const { return Opcode; }
276 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500277 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500278 return Operands;
279 }
David Neto22f144c2017-06-12 14:26:21 -0400280
281private:
David Netoee2660d2018-06-28 16:31:29 -0400282 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400283 uint16_t Opcode;
284 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500285 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400286};
287
288struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400289 typedef DenseMap<Type *, uint32_t> TypeMapType;
290 typedef UniqueVector<Type *> TypeList;
291 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400292 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400293 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
294 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400295 // A vector of tuples, each of which is:
296 // - the LLVM instruction that we will later generate SPIR-V code for
297 // - where the SPIR-V instruction should be inserted
298 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400299 typedef std::vector<
300 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
301 DeferredInstVecType;
302 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
303 GlobalConstFuncMapType;
304
David Neto44795152017-07-13 15:45:28 -0400305 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500306 raw_pwrite_stream &out,
307 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400308 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400309 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400310 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400311 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400312 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400313 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500314 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
315 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
alan-bakera1be3322020-04-20 12:48:18 -0400316 WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400317
James Price11010dc2019-12-19 13:53:09 -0500318 virtual ~SPIRVProducerPass() {
SJW69939d52020-04-16 07:29:07 -0500319 for (int i = 0; i < kSectionCount; ++i) {
320 for (auto *Inst : SPIRVSections[i]) {
321 delete Inst;
322 }
James Price11010dc2019-12-19 13:53:09 -0500323 }
324 }
325
David Neto22f144c2017-06-12 14:26:21 -0400326 void getAnalysisUsage(AnalysisUsage &AU) const override {
327 AU.addRequired<DominatorTreeWrapperPass>();
328 AU.addRequired<LoopInfoWrapperPass>();
329 }
330
331 virtual bool runOnModule(Module &module) override;
332
333 // output the SPIR-V header block
334 void outputHeader();
335
336 // patch the SPIR-V header block
337 void patchHeader();
338
339 uint32_t lookupType(Type *Ty) {
340 if (Ty->isPointerTy() &&
341 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
342 auto PointeeTy = Ty->getPointerElementType();
343 if (PointeeTy->isStructTy() &&
344 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
345 Ty = PointeeTy;
346 }
347 }
348
David Neto862b7d82018-06-14 18:48:37 -0400349 auto where = TypeMap.find(Ty);
350 if (where == TypeMap.end()) {
351 if (Ty) {
352 errs() << "Unhandled type " << *Ty << "\n";
353 } else {
354 errs() << "Unhandled type (null)\n";
355 }
David Netoe439d702018-03-23 13:14:08 -0700356 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400357 }
358
David Neto862b7d82018-06-14 18:48:37 -0400359 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400360 }
361 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500362 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400363 TypeList &getTypeList() { return Types; };
364 ValueList &getConstantList() { return Constants; };
365 ValueMapType &getValueMap() { return ValueMap; }
366 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
SJW69939d52020-04-16 07:29:07 -0500367 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
368 return SPIRVSections[Section];
369 };
David Neto22f144c2017-06-12 14:26:21 -0400370 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
371 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
372 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
373 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
374 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500375
alan-baker5b86ed72019-02-15 08:26:50 -0500376 bool hasVariablePointersStorageBuffer() {
377 return HasVariablePointersStorageBuffer;
378 }
379 void setVariablePointersStorageBuffer(bool Val) {
380 HasVariablePointersStorageBuffer = Val;
381 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400382 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400383 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500384 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
385 return samplerMap;
386 }
David Neto22f144c2017-06-12 14:26:21 -0400387 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
388 return GlobalConstFuncTypeMap;
389 }
390 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
391 return GlobalConstArgumentSet;
392 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400394
SJW77b87ad2020-04-21 14:37:52 -0500395 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500396 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
397 // *not* be converted to a storage buffer, replace each such global variable
398 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500399 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400400 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
401 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500402 void FindResourceVars();
403 void FindWorkgroupVars();
404 bool FindExtInst();
David Neto22f144c2017-06-12 14:26:21 -0400405 void FindTypePerGlobalVar(GlobalVariable &GV);
406 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500407 void FindTypesForSamplerMap();
408 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500409 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
410 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400411 void FindType(Type *Ty);
412 void FindConstantPerGlobalVar(GlobalVariable &GV);
413 void FindConstantPerFunc(Function &F);
414 void FindConstant(Value *V);
415 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400416 // Generates instructions for SPIR-V types corresponding to the LLVM types
417 // saved in the |Types| member. A type follows its subtypes. IDs are
418 // allocated sequentially starting with the current value of nextID, and
419 // with a type following its subtypes. Also updates nextID to just beyond
420 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500421 void GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400422 void GenerateSPIRVConstants();
SJW77b87ad2020-04-21 14:37:52 -0500423 void GenerateModuleInfo();
424 void GeneratePushConstantDescriptorMapEntries();
425 void GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400426 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500427 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400428 // Generate descriptor map entries for resource variables associated with
429 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500430 void GenerateDescriptorMapInfo(Function &F);
431 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400432 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500433 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400434 void GenerateFuncPrologue(Function &F);
435 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400436 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400437 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
438 spv::Op GetSPIRVCastOpcode(Instruction &I);
439 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
440 void GenerateInstruction(Instruction &I);
441 void GenerateFuncEpilogue();
442 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500443 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400444 bool is4xi8vec(Type *Ty) const;
445 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400446 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400447 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400448 // Returns the GLSL extended instruction enum that the given function
449 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400450 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400451 // Returns the GLSL extended instruction enum indirectly used by the given
452 // function. That is, to implement the given function, we use an extended
453 // instruction plus one more instruction. If none, then returns the 0 value,
454 // i.e. GLSLstd4580Bad.
455 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
456 // Returns the single GLSL extended instruction used directly or
457 // indirectly by the given function call.
458 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400459 void WriteOneWord(uint32_t Word);
460 void WriteResultID(SPIRVInstruction *Inst);
461 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500462 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400463 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500464 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400465
Alan Baker9bf93fb2018-08-28 16:59:26 -0400466 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500467 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400468
Alan Bakerfcda9482018-10-02 17:09:59 -0400469 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500470 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400471
alan-baker06cad652019-12-03 17:56:47 -0500472 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500473 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500474
Alan Bakerfcda9482018-10-02 17:09:59 -0400475 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
476 // uses the internal map, otherwise it falls back on the data layout.
477 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
478 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
479 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000480 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
481 unsigned member,
482 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400483
alan-baker5b86ed72019-02-15 08:26:50 -0500484 // Returns the base pointer of |v|.
485 Value *GetBasePointer(Value *v);
486
487 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
488 // |address_space|.
489 void setVariablePointersCapabilities(unsigned address_space);
490
491 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
492 // variable.
493 bool sameResource(Value *lhs, Value *rhs) const;
494
495 // Returns true if |inst| is phi or select that selects from the same
496 // structure (or null).
497 bool selectFromSameObject(Instruction *inst);
498
alan-bakere9308012019-03-15 10:25:13 -0400499 // Returns true if |Arg| is called with a coherent resource.
500 bool CalledWithCoherentResource(Argument &Arg);
501
David Neto22f144c2017-06-12 14:26:21 -0400502private:
503 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500504
505 Module *module;
506
David Neto44795152017-07-13 15:45:28 -0400507 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400508 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400509
510 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
511 // convert to other formats on demand?
512
513 // When emitting a C initialization list, the WriteSPIRVBinary method
514 // will actually write its words to this vector via binaryTempOut.
515 SmallVector<char, 100> binaryTempUnderlyingVector;
516 raw_svector_ostream binaryTempOut;
517
518 // Binary output writes to this stream, which might be |out| or
519 // |binaryTempOut|. It's the latter when we really want to write a C
520 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400521 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500522 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400523 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400524 uint64_t patchBoundOffset;
525 uint32_t nextID;
526
alan-bakerf67468c2019-11-25 15:51:49 -0500527 // ID for OpTypeInt 32 1.
528 uint32_t int32ID = 0;
529 // ID for OpTypeVector %int 4.
530 uint32_t v4int32ID = 0;
531
David Neto19a1bad2017-08-25 15:01:41 -0400532 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400533 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400534 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400535 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500536 // A unique-vector of LLVM image types. This list is used to provide
537 // deterministic traversal of image types.
538 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400539 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400540 TypeList Types;
541 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400542 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400543 ValueMapType ValueMap;
544 ValueMapType AllocatedValueMap;
SJW69939d52020-04-16 07:29:07 -0500545 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400546
David Neto22f144c2017-06-12 14:26:21 -0400547 EntryPointVecType EntryPointVec;
548 DeferredInstVecType DeferredInstVec;
549 ValueList EntryPointInterfacesVec;
550 uint32_t OpExtInstImportID;
551 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500552 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400553 bool HasVariablePointers;
554 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500555 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700556
557 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700558 // will map F's type to (G, index of the parameter), where in a first phase
559 // G is F's type. During FindTypePerFunc, G will be changed to F's type
560 // but replacing the pointer-to-constant parameter with
561 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700562 // TODO(dneto): This doesn't seem general enough? A function might have
563 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400564 GlobalConstFuncMapType GlobalConstFuncTypeMap;
565 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400566 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700567 // or array types, and which point into transparent memory (StorageBuffer
568 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400569 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700570 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400571
572 // This is truly ugly, but works around what look like driver bugs.
573 // For get_local_size, an earlier part of the flow has created a module-scope
574 // variable in Private address space to hold the value for the workgroup
575 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
576 // When this is present, save the IDs of the initializer value and variable
577 // in these two variables. We only ever do a vector load from it, and
578 // when we see one of those, substitute just the value of the intializer.
579 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700580 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400581 uint32_t WorkgroupSizeValueID;
582 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400583
David Neto862b7d82018-06-14 18:48:37 -0400584 // Bookkeeping for mapping kernel arguments to resource variables.
585 struct ResourceVarInfo {
586 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400587 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400588 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400589 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400590 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
591 const int index; // Index into ResourceVarInfoList
592 const unsigned descriptor_set;
593 const unsigned binding;
594 Function *const var_fn; // The @clspv.resource.var.* function.
595 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400596 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400597 const unsigned addr_space; // The LLVM address space
598 // The SPIR-V ID of the OpVariable. Not populated at construction time.
599 uint32_t var_id = 0;
600 };
601 // A list of resource var info. Each one correponds to a module-scope
602 // resource variable we will have to create. Resource var indices are
603 // indices into this vector.
604 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
605 // This is a vector of pointers of all the resource vars, but ordered by
606 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500607 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400608 // Map a function to the ordered list of resource variables it uses, one for
609 // each argument. If an argument does not use a resource variable, it
610 // will have a null pointer entry.
611 using FunctionToResourceVarsMapType =
612 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
613 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
614
615 // What LLVM types map to SPIR-V types needing layout? These are the
616 // arrays and structures supporting storage buffers and uniform buffers.
617 TypeList TypesNeedingLayout;
618 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
619 UniqueVector<StructType *> StructTypesNeedingBlock;
620 // For a call that represents a load from an opaque type (samplers, images),
621 // map it to the variable id it should load from.
622 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700623
David Netoc6f3ab22018-04-06 18:02:31 -0400624 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500625 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400626 LocalArgList LocalArgs;
627 // Information about a pointer-to-local argument.
628 struct LocalArgInfo {
629 // The SPIR-V ID of the array variable.
630 uint32_t variable_id;
631 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500632 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // The ID of the array type.
634 uint32_t array_size_id;
635 // The ID of the array type.
636 uint32_t array_type_id;
637 // The ID of the pointer to the array type.
638 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400639 // The specialization constant ID of the array size.
640 int spec_id;
641 };
Alan Baker202c8c72018-08-13 13:47:44 -0400642 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500643 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400644 // A mapping from SpecId to its LocalArgInfo.
645 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400646 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500647 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400648 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500649 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
650 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500651
652 // Maps basic block to its merge block.
653 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
654 // Maps basic block to its continue block.
655 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400656};
657
658char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400659
alan-bakerb6b09dc2018-11-08 16:59:28 -0500660} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400661
662namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500663ModulePass *createSPIRVProducerPass(
664 raw_pwrite_stream &out,
665 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400666 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500667 bool outputCInitList) {
668 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400669 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400670}
David Netoc2c368d2017-06-30 16:50:17 -0400671} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400672
SJW77b87ad2020-04-21 14:37:52 -0500673bool SPIRVProducerPass::runOnModule(Module &M) {
674 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400675 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500676 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400677 }
David Neto0676e6f2017-07-11 18:47:44 -0400678 binaryOut = outputCInitList ? &binaryTempOut : &out;
679
SJW77b87ad2020-04-21 14:37:52 -0500680 PopulateUBOTypeMaps();
681 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400682
David Neto22f144c2017-06-12 14:26:21 -0400683 // SPIR-V always begins with its header information
684 outputHeader();
685
686 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500687 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400688
David Neto22f144c2017-06-12 14:26:21 -0400689 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500690 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400691 // If the GV is one of our special __spirv_* variables, remove the
692 // initializer as it was only placed there to force LLVM to not throw the
693 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000694 if (GV.getName().startswith("__spirv_") ||
695 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400696 GV.setInitializer(nullptr);
697 }
698
699 // Collect types' information from global variable.
700 FindTypePerGlobalVar(GV);
701
702 // Collect constant information from global variable.
703 FindConstantPerGlobalVar(GV);
704
705 // If the variable is an input, entry points need to know about it.
706 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400707 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400708 }
709 }
710
711 // If there are extended instructions, generate OpExtInstImport.
SJW77b87ad2020-04-21 14:37:52 -0500712 if (FindExtInst()) {
David Neto22f144c2017-06-12 14:26:21 -0400713 GenerateExtInstImport();
714 }
715
716 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500717 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400718
719 // Generate SPIRV constants.
720 GenerateSPIRVConstants();
721
alan-baker09cb9802019-12-10 13:16:27 -0500722 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500723 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400724
Kévin Petitbbbda972020-03-03 19:16:31 +0000725 // Generate descriptor map entries for all push constants
SJW77b87ad2020-04-21 14:37:52 -0500726 GeneratePushConstantDescriptorMapEntries();
Kévin Petitbbbda972020-03-03 19:16:31 +0000727
David Neto22f144c2017-06-12 14:26:21 -0400728 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500729 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400730 GenerateGlobalVar(GV);
731 }
SJW77b87ad2020-04-21 14:37:52 -0500732 GenerateResourceVars();
733 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400734
735 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500736 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400737 if (F.isDeclaration()) {
738 continue;
739 }
740
SJW77b87ad2020-04-21 14:37:52 -0500741 GenerateDescriptorMapInfo(F);
David Neto862b7d82018-06-14 18:48:37 -0400742
David Neto22f144c2017-06-12 14:26:21 -0400743 // Generate Function Prologue.
744 GenerateFuncPrologue(F);
745
746 // Generate SPIRV instructions for function body.
747 GenerateFuncBody(F);
748
749 // Generate Function Epilogue.
750 GenerateFuncEpilogue();
751 }
752
753 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500754 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400755
756 // Generate descriptor map entries for module scope specialization constants.
SJW77b87ad2020-04-21 14:37:52 -0500757 GenerateSpecConstantDescriptorMapEntries();
David Neto22f144c2017-06-12 14:26:21 -0400758
759 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500760 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400761
alan-baker00e7a582019-06-07 12:54:21 -0400762 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // We need to patch the SPIR-V header to set bound correctly.
765 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400766
767 if (outputCInitList) {
768 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400769 std::ostringstream os;
770
David Neto57fb0b92017-08-04 15:35:09 -0400771 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400772 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400773 os << ",\n";
774 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400775 first = false;
776 };
777
778 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400779 const std::string str(binaryTempOut.str());
780 for (unsigned i = 0; i < str.size(); i += 4) {
781 const uint32_t a = static_cast<unsigned char>(str[i]);
782 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
783 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
784 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
785 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400786 }
787 os << "}\n";
788 out << os.str();
789 }
790
David Neto22f144c2017-06-12 14:26:21 -0400791 return false;
792}
793
794void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400795 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
796 sizeof(spv::MagicNumber));
alan-bakere0902602020-03-23 08:43:40 -0400797 const uint32_t spv_version = 0x10000; // SPIR-V 1.0
798 binaryOut->write(reinterpret_cast<const char *>(&spv_version),
799 sizeof(spv_version));
David Neto22f144c2017-06-12 14:26:21 -0400800
alan-baker0c18ab02019-06-12 10:23:21 -0400801 // use Google's vendor ID
802 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400803 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400804
alan-baker00e7a582019-06-07 12:54:21 -0400805 // we record where we need to come back to and patch in the bound value
806 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker00e7a582019-06-07 12:54:21 -0400808 // output a bad bound for now
809 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400810
alan-baker00e7a582019-06-07 12:54:21 -0400811 // output the schema (reserved for use and must be 0)
812 const uint32_t schema = 0;
813 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400814}
815
816void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400817 // for a binary we just write the value of nextID over bound
818 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
819 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400820}
821
SJW77b87ad2020-04-21 14:37:52 -0500822void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400823 // This function generates LLVM IR for function such as global variable for
824 // argument, constant and pointer type for argument access. These information
825 // is artificial one because we need Vulkan SPIR-V output. This function is
826 // executed ahead of FindType and FindConstant.
SJW77b87ad2020-04-21 14:37:52 -0500827 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -0400828
SJW77b87ad2020-04-21 14:37:52 -0500829 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400830
SJW77b87ad2020-04-21 14:37:52 -0500831 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400832
833 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500834 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400835 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
836 if (spv::BuiltInWorkgroupSize == BuiltinType) {
837 HasWorkGroupBuiltin = true;
838 }
839 }
840
SJW77b87ad2020-04-21 14:37:52 -0500841 FindTypesForSamplerMap();
842 FindTypesForResourceVars();
843 FindWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400844
SJW77b87ad2020-04-21 14:37:52 -0500845 for (Function &F : *module) {
Kévin Petitabef4522019-03-27 13:08:01 +0000846 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400847 continue;
848 }
849
850 for (BasicBlock &BB : F) {
851 for (Instruction &I : BB) {
852 if (I.getOpcode() == Instruction::ZExt ||
853 I.getOpcode() == Instruction::SExt ||
854 I.getOpcode() == Instruction::UIToFP) {
855 // If there is zext with i1 type, it will be changed to OpSelect. The
856 // OpSelect needs constant 0 and 1 so the constants are added here.
857
858 auto OpTy = I.getOperand(0)->getType();
859
Kévin Petit24272b62018-10-18 19:16:12 +0000860 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400861 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400862 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000863 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400864 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400865 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000866 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400867 } else {
868 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
869 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
870 }
871 }
872 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400873 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400874
875 // Handle image type specially.
SJW173c7e92020-03-16 08:44:47 -0500876 if (IsImageBuiltin(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400877 TypeMapType &OpImageTypeMap = getImageTypeMap();
878 Type *ImageTy =
879 Call->getArgOperand(0)->getType()->getPointerElementType();
880 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500881 getImageTypeList().insert(ImageTy);
alan-baker75090e42020-02-20 11:21:04 -0500882 }
David Neto22f144c2017-06-12 14:26:21 -0400883
SJW173c7e92020-03-16 08:44:47 -0500884 if (IsSampledImageRead(callee_name)) {
alan-bakerf67468c2019-11-25 15:51:49 -0500885 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400886 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
SJW2c317da2020-03-23 07:39:13 -0500887 } else if (IsUnsampledImageRead(callee_name)) {
alan-baker75090e42020-02-20 11:21:04 -0500888 // All unsampled reads need an integer 0 for the Lod operand.
889 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
SJW2c317da2020-03-23 07:39:13 -0500890 } else if (IsImageQuery(callee_name)) {
alan-bakerce179f12019-12-06 19:02:22 -0500891 Type *ImageTy = Call->getOperand(0)->getType();
892 const uint32_t dim = ImageDimensionality(ImageTy);
alan-baker7150a1d2020-02-25 08:31:06 -0500893 uint32_t components =
894 dim + (clspv::IsArrayImageType(ImageTy) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -0500895 if (components > 1) {
896 // OpImageQuerySize* return |components| components.
897 FindType(VectorType::get(Type::getInt32Ty(Context), components));
898 if (dim == 3 && IsGetImageDim(callee_name)) {
899 // get_image_dim for 3D images returns an int4.
900 FindType(
901 VectorType::get(Type::getInt32Ty(Context), components + 1));
902 }
903 }
904
SJW173c7e92020-03-16 08:44:47 -0500905 if (IsSampledImageType(ImageTy)) {
alan-bakerce179f12019-12-06 19:02:22 -0500906 // All sampled image queries need a integer 0 for the Lod
907 // operand.
908 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
909 }
David Neto5c22a252018-03-15 16:07:41 -0400910 }
David Neto22f144c2017-06-12 14:26:21 -0400911 }
912 }
913 }
914
Kévin Petitabef4522019-03-27 13:08:01 +0000915 // More things to do on kernel functions
916 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
917 if (const MDNode *MD =
918 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
919 // We generate constants if the WorkgroupSize builtin is being used.
920 if (HasWorkGroupBuiltin) {
921 // Collect constant information for work group size.
922 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
923 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
924 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400925 }
926 }
927 }
928
alan-bakerf67468c2019-11-25 15:51:49 -0500929 // TODO(alan-baker): make this better.
SJW77b87ad2020-04-21 14:37:52 -0500930 if (module->getTypeByName("opencl.image1d_ro_t.float") ||
931 module->getTypeByName("opencl.image1d_ro_t.float.sampled") ||
932 module->getTypeByName("opencl.image1d_wo_t.float") ||
933 module->getTypeByName("opencl.image2d_ro_t.float") ||
934 module->getTypeByName("opencl.image2d_ro_t.float.sampled") ||
935 module->getTypeByName("opencl.image2d_wo_t.float") ||
936 module->getTypeByName("opencl.image3d_ro_t.float") ||
937 module->getTypeByName("opencl.image3d_ro_t.float.sampled") ||
938 module->getTypeByName("opencl.image3d_wo_t.float") ||
939 module->getTypeByName("opencl.image1d_array_ro_t.float") ||
940 module->getTypeByName("opencl.image1d_array_ro_t.float.sampled") ||
941 module->getTypeByName("opencl.image1d_array_wo_t.float") ||
942 module->getTypeByName("opencl.image2d_array_ro_t.float") ||
943 module->getTypeByName("opencl.image2d_array_ro_t.float.sampled") ||
944 module->getTypeByName("opencl.image2d_array_wo_t.float")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500945 FindType(Type::getFloatTy(Context));
SJW77b87ad2020-04-21 14:37:52 -0500946 } else if (module->getTypeByName("opencl.image1d_ro_t.uint") ||
947 module->getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
948 module->getTypeByName("opencl.image1d_wo_t.uint") ||
949 module->getTypeByName("opencl.image2d_ro_t.uint") ||
950 module->getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
951 module->getTypeByName("opencl.image2d_wo_t.uint") ||
952 module->getTypeByName("opencl.image3d_ro_t.uint") ||
953 module->getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
954 module->getTypeByName("opencl.image3d_wo_t.uint") ||
955 module->getTypeByName("opencl.image1d_array_ro_t.uint") ||
956 module->getTypeByName(
957 "opencl.image1d_array_ro_t.uint.sampled") ||
958 module->getTypeByName("opencl.image1d_array_wo_t.uint") ||
959 module->getTypeByName("opencl.image2d_array_ro_t.uint") ||
960 module->getTypeByName(
961 "opencl.image2d_array_ro_t.uint.sampled") ||
962 module->getTypeByName("opencl.image2d_array_wo_t.uint")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500963 FindType(Type::getInt32Ty(Context));
SJW77b87ad2020-04-21 14:37:52 -0500964 } else if (module->getTypeByName("opencl.image1d_ro_t.int") ||
965 module->getTypeByName("opencl.image1d_ro_t.int.sampled") ||
966 module->getTypeByName("opencl.image1d_wo_t.int") ||
967 module->getTypeByName("opencl.image2d_ro_t.int") ||
968 module->getTypeByName("opencl.image2d_ro_t.int.sampled") ||
969 module->getTypeByName("opencl.image2d_wo_t.int") ||
970 module->getTypeByName("opencl.image3d_ro_t.int") ||
971 module->getTypeByName("opencl.image3d_ro_t.int.sampled") ||
972 module->getTypeByName("opencl.image3d_wo_t.int") ||
973 module->getTypeByName("opencl.image1d_array_ro_t.int") ||
974 module->getTypeByName("opencl.image1d_array_ro_t.int.sampled") ||
975 module->getTypeByName("opencl.image1d_array_wo_t.int") ||
976 module->getTypeByName("opencl.image2d_array_ro_t.int") ||
977 module->getTypeByName("opencl.image2d_array_ro_t.int.sampled") ||
978 module->getTypeByName("opencl.image2d_array_wo_t.int")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500979 // Nothing for now...
980 } else {
981 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400982 FindType(Type::getFloatTy(Context));
983 }
984
985 // Collect types' information from function.
986 FindTypePerFunc(F);
987
988 // Collect constant information from function.
989 FindConstantPerFunc(F);
990 }
991}
992
SJW77b87ad2020-04-21 14:37:52 -0500993void SPIRVProducerPass::FindGlobalConstVars() {
994 clspv::NormalizeGlobalVariables(*module);
995 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400996
David Neto862b7d82018-06-14 18:48:37 -0400997 SmallVector<GlobalVariable *, 8> GVList;
998 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500999 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -04001000 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
1001 if (GV.use_empty()) {
1002 DeadGVList.push_back(&GV);
1003 } else {
1004 GVList.push_back(&GV);
1005 }
1006 }
1007 }
1008
1009 // Remove dead global __constant variables.
1010 for (auto GV : DeadGVList) {
1011 GV->eraseFromParent();
1012 }
1013 DeadGVList.clear();
1014
1015 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1016 // For now, we only support a single storage buffer.
1017 if (GVList.size() > 0) {
1018 assert(GVList.size() == 1);
1019 const auto *GV = GVList[0];
1020 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -04001021 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -04001022 const size_t kConstantMaxSize = 65536;
1023 if (constants_byte_size > kConstantMaxSize) {
1024 outs() << "Max __constant capacity of " << kConstantMaxSize
1025 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
1026 llvm_unreachable("Max __constant capacity exceeded");
1027 }
1028 }
1029 } else {
1030 // Change global constant variable's address space to ModuleScopePrivate.
1031 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1032 for (auto GV : GVList) {
1033 // Create new gv with ModuleScopePrivate address space.
1034 Type *NewGVTy = GV->getType()->getPointerElementType();
1035 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -05001036 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -04001037 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1038 NewGV->takeName(GV);
1039
1040 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1041 SmallVector<User *, 8> CandidateUsers;
1042
1043 auto record_called_function_type_as_user =
1044 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1045 // Find argument index.
1046 unsigned index = 0;
1047 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1048 if (gv == call->getOperand(i)) {
1049 // TODO(dneto): Should we break here?
1050 index = i;
1051 }
1052 }
1053
1054 // Record function type with global constant.
1055 GlobalConstFuncTyMap[call->getFunctionType()] =
1056 std::make_pair(call->getFunctionType(), index);
1057 };
1058
1059 for (User *GVU : GVUsers) {
1060 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1061 record_called_function_type_as_user(GV, Call);
1062 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1063 // Check GEP users.
1064 for (User *GEPU : GEP->users()) {
1065 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1066 record_called_function_type_as_user(GEP, GEPCall);
1067 }
1068 }
1069 }
1070
1071 CandidateUsers.push_back(GVU);
1072 }
1073
1074 for (User *U : CandidateUsers) {
1075 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001076 if (!isa<Constant>(U)) {
1077 // #254: Can't change operands of a constant, but this shouldn't be
1078 // something that sticks around in the module.
1079 U->replaceUsesOfWith(GV, NewGV);
1080 }
David Neto862b7d82018-06-14 18:48:37 -04001081 }
1082
1083 // Delete original gv.
1084 GV->eraseFromParent();
1085 }
1086 }
1087}
1088
SJW77b87ad2020-04-21 14:37:52 -05001089void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001090 ResourceVarInfoList.clear();
1091 FunctionToResourceVarsMap.clear();
1092 ModuleOrderedResourceVars.reset();
1093 // Normally, there is one resource variable per clspv.resource.var.*
1094 // function, since that is unique'd by arg type and index. By design,
1095 // we can share these resource variables across kernels because all
1096 // kernels use the same descriptor set.
1097 //
1098 // But if the user requested distinct descriptor sets per kernel, then
1099 // the descriptor allocator has made different (set,binding) pairs for
1100 // the same (type,arg_index) pair. Since we can decorate a resource
1101 // variable with only exactly one DescriptorSet and Binding, we are
1102 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001103 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001104 // (set,binding) values.
1105 const bool always_distinct_sets =
1106 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -05001107 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001108 // Rely on the fact the resource var functions have a stable ordering
1109 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001110 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001111 // Find all calls to this function with distinct set and binding pairs.
1112 // Save them in ResourceVarInfoList.
1113
1114 // Determine uniqueness of the (set,binding) pairs only withing this
1115 // one resource-var builtin function.
1116 using SetAndBinding = std::pair<unsigned, unsigned>;
1117 // Maps set and binding to the resource var info.
1118 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1119 bool first_use = true;
1120 for (auto &U : F.uses()) {
1121 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1122 const auto set = unsigned(
1123 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1124 const auto binding = unsigned(
1125 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1126 const auto arg_kind = clspv::ArgKind(
1127 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1128 const auto arg_index = unsigned(
1129 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001130 const auto coherent = unsigned(
1131 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001132
1133 // Find or make the resource var info for this combination.
1134 ResourceVarInfo *rv = nullptr;
1135 if (always_distinct_sets) {
1136 // Make a new resource var any time we see a different
1137 // (set,binding) pair.
1138 SetAndBinding key{set, binding};
1139 auto where = set_and_binding_map.find(key);
1140 if (where == set_and_binding_map.end()) {
1141 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001142 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001143 ResourceVarInfoList.emplace_back(rv);
1144 set_and_binding_map[key] = rv;
1145 } else {
1146 rv = where->second;
1147 }
1148 } else {
1149 // The default is to make exactly one resource for each
1150 // clspv.resource.var.* function.
1151 if (first_use) {
1152 first_use = false;
1153 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001154 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001155 ResourceVarInfoList.emplace_back(rv);
1156 } else {
1157 rv = ResourceVarInfoList.back().get();
1158 }
1159 }
1160
1161 // Now populate FunctionToResourceVarsMap.
1162 auto &mapping =
1163 FunctionToResourceVarsMap[call->getParent()->getParent()];
1164 while (mapping.size() <= arg_index) {
1165 mapping.push_back(nullptr);
1166 }
1167 mapping[arg_index] = rv;
1168 }
1169 }
1170 }
1171 }
1172
1173 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001174 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001175 auto where = FunctionToResourceVarsMap.find(&F);
1176 if (where != FunctionToResourceVarsMap.end()) {
1177 for (auto &rv : where->second) {
1178 if (rv != nullptr) {
1179 ModuleOrderedResourceVars.insert(rv);
1180 }
1181 }
1182 }
1183 }
1184 if (ShowResourceVars) {
1185 for (auto *info : ModuleOrderedResourceVars) {
1186 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1187 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1188 << "\n";
1189 }
1190 }
1191}
1192
SJW77b87ad2020-04-21 14:37:52 -05001193bool SPIRVProducerPass::FindExtInst() {
1194 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04001195 bool HasExtInst = false;
1196
SJW77b87ad2020-04-21 14:37:52 -05001197 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -04001198 for (BasicBlock &BB : F) {
1199 for (Instruction &I : BB) {
1200 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1201 Function *Callee = Call->getCalledFunction();
1202 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001203 auto callee_name = Callee->getName();
1204 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1205 const glsl::ExtInst IndirectEInst =
1206 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001207
David Neto3fbb4072017-10-16 11:28:14 -04001208 HasExtInst |=
1209 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1210
1211 if (IndirectEInst) {
1212 // Register extra constants if needed.
1213
1214 // Registers a type and constant for computing the result of the
1215 // given instruction. If the result of the instruction is a vector,
1216 // then make a splat vector constant with the same number of
1217 // elements.
1218 auto register_constant = [this, &I](Constant *constant) {
1219 FindType(constant->getType());
1220 FindConstant(constant);
1221 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1222 // Register the splat vector of the value with the same
1223 // width as the result of the instruction.
1224 auto *vec_constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04001225 {static_cast<unsigned>(vectorTy->getNumElements()), false},
David Neto3fbb4072017-10-16 11:28:14 -04001226 constant);
1227 FindConstant(vec_constant);
1228 FindType(vec_constant->getType());
1229 }
1230 };
1231 switch (IndirectEInst) {
1232 case glsl::ExtInstFindUMsb:
1233 // clz needs OpExtInst and OpISub with constant 31, or splat
1234 // vector of 31. Add it to the constant list here.
1235 register_constant(
1236 ConstantInt::get(Type::getInt32Ty(Context), 31));
1237 break;
1238 case glsl::ExtInstAcos:
1239 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001240 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001241 case glsl::ExtInstAtan2:
1242 // We need 1/pi for acospi, asinpi, atan2pi.
1243 register_constant(
1244 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1245 break;
1246 default:
1247 assert(false && "internally inconsistent");
1248 }
David Neto22f144c2017-06-12 14:26:21 -04001249 }
1250 }
1251 }
1252 }
1253 }
1254
1255 return HasExtInst;
1256}
1257
1258void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1259 // Investigate global variable's type.
1260 FindType(GV.getType());
1261}
1262
1263void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1264 // Investigate function's type.
1265 FunctionType *FTy = F.getFunctionType();
1266
1267 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1268 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001269 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001270 if (GlobalConstFuncTyMap.count(FTy)) {
1271 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1272 SmallVector<Type *, 4> NewFuncParamTys;
1273 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1274 Type *ParamTy = FTy->getParamType(i);
1275 if (i == GVCstArgIdx) {
1276 Type *EleTy = ParamTy->getPointerElementType();
1277 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1278 }
1279
1280 NewFuncParamTys.push_back(ParamTy);
1281 }
1282
1283 FunctionType *NewFTy =
1284 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1285 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1286 FTy = NewFTy;
1287 }
1288
1289 FindType(FTy);
1290 } else {
1291 // As kernel functions do not have parameters, create new function type and
1292 // add it to type map.
1293 SmallVector<Type *, 4> NewFuncParamTys;
1294 FunctionType *NewFTy =
1295 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1296 FindType(NewFTy);
1297 }
1298
1299 // Investigate instructions' type in function body.
1300 for (BasicBlock &BB : F) {
1301 for (Instruction &I : BB) {
1302 if (isa<ShuffleVectorInst>(I)) {
1303 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1304 // Ignore type for mask of shuffle vector instruction.
1305 if (i == 2) {
1306 continue;
1307 }
1308
1309 Value *Op = I.getOperand(i);
1310 if (!isa<MetadataAsValue>(Op)) {
1311 FindType(Op->getType());
1312 }
1313 }
1314
1315 FindType(I.getType());
1316 continue;
1317 }
1318
David Neto862b7d82018-06-14 18:48:37 -04001319 CallInst *Call = dyn_cast<CallInst>(&I);
1320
1321 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001322 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001323 // This is a fake call representing access to a resource variable.
1324 // We handle that elsewhere.
1325 continue;
1326 }
1327
Alan Baker202c8c72018-08-13 13:47:44 -04001328 if (Call && Call->getCalledFunction()->getName().startswith(
1329 clspv::WorkgroupAccessorFunction())) {
1330 // This is a fake call representing access to a workgroup variable.
1331 // We handle that elsewhere.
1332 continue;
1333 }
1334
alan-bakerf083bed2020-01-29 08:15:42 -05001335 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1336 // OpCompositeExtract which takes literal values for indices. As a result
1337 // don't map the type of indices.
1338 if (I.getOpcode() == Instruction::ExtractValue) {
1339 FindType(I.getOperand(0)->getType());
1340 continue;
1341 }
1342 if (I.getOpcode() == Instruction::InsertValue) {
1343 FindType(I.getOperand(0)->getType());
1344 FindType(I.getOperand(1)->getType());
1345 continue;
1346 }
1347
1348 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1349 // the index is a constant. In such a case don't map the index type.
1350 if (I.getOpcode() == Instruction::ExtractElement) {
1351 FindType(I.getOperand(0)->getType());
1352 Value *op1 = I.getOperand(1);
1353 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1354 FindType(op1->getType());
1355 }
1356 continue;
1357 }
1358 if (I.getOpcode() == Instruction::InsertElement) {
1359 FindType(I.getOperand(0)->getType());
1360 FindType(I.getOperand(1)->getType());
1361 Value *op2 = I.getOperand(2);
1362 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1363 FindType(op2->getType());
1364 }
1365 continue;
1366 }
1367
David Neto22f144c2017-06-12 14:26:21 -04001368 // Work through the operands of the instruction.
1369 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1370 Value *const Op = I.getOperand(i);
1371 // If any of the operands is a constant, find the type!
1372 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1373 FindType(Op->getType());
1374 }
1375 }
1376
1377 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001378 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001379 // Avoid to check call instruction's type.
1380 break;
1381 }
Alan Baker202c8c72018-08-13 13:47:44 -04001382 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1383 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1384 clspv::WorkgroupAccessorFunction())) {
1385 // This is a fake call representing access to a workgroup variable.
1386 // We handle that elsewhere.
1387 continue;
1388 }
1389 }
David Neto22f144c2017-06-12 14:26:21 -04001390 if (!isa<MetadataAsValue>(&Op)) {
1391 FindType(Op->getType());
1392 continue;
1393 }
1394 }
1395
David Neto22f144c2017-06-12 14:26:21 -04001396 // We don't want to track the type of this call as we are going to replace
1397 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001398 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001399 Call->getCalledFunction()->getName())) {
1400 continue;
1401 }
1402
1403 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1404 // If gep's base operand has ModuleScopePrivate address space, make gep
1405 // return ModuleScopePrivate address space.
1406 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1407 // Add pointer type with private address space for global constant to
1408 // type list.
1409 Type *EleTy = I.getType()->getPointerElementType();
1410 Type *NewPTy =
1411 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1412
1413 FindType(NewPTy);
1414 continue;
1415 }
1416 }
1417
1418 FindType(I.getType());
1419 }
1420 }
1421}
1422
SJW77b87ad2020-04-21 14:37:52 -05001423void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001424 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001425 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001426 0 < getSamplerMap().size()) {
SJW77b87ad2020-04-21 14:37:52 -05001427 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001428 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001429 SamplerStructTy =
1430 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001431 }
1432
1433 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1434
1435 FindType(SamplerTy);
1436 }
1437}
1438
SJW77b87ad2020-04-21 14:37:52 -05001439void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001440 // Record types so they are generated.
1441 TypesNeedingLayout.reset();
1442 StructTypesNeedingBlock.reset();
1443
1444 // To match older clspv codegen, generate the float type first if required
1445 // for images.
1446 for (const auto *info : ModuleOrderedResourceVars) {
1447 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1448 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001449 if (IsIntImageType(info->var_fn->getReturnType())) {
1450 // Nothing for now...
1451 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001452 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001453 }
1454
1455 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001456 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001457 }
1458 }
1459
1460 for (const auto *info : ModuleOrderedResourceVars) {
1461 Type *type = info->var_fn->getReturnType();
1462
1463 switch (info->arg_kind) {
1464 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001465 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001466 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1467 StructTypesNeedingBlock.insert(sty);
1468 } else {
1469 errs() << *type << "\n";
1470 llvm_unreachable("Buffer arguments must map to structures!");
1471 }
1472 break;
1473 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001474 case clspv::ArgKind::PodUBO:
1475 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001476 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1477 StructTypesNeedingBlock.insert(sty);
1478 } else {
1479 errs() << *type << "\n";
1480 llvm_unreachable("POD arguments must map to structures!");
1481 }
1482 break;
1483 case clspv::ArgKind::ReadOnlyImage:
1484 case clspv::ArgKind::WriteOnlyImage:
1485 case clspv::ArgKind::Sampler:
1486 // Sampler and image types map to the pointee type but
1487 // in the uniform constant address space.
1488 type = PointerType::get(type->getPointerElementType(),
1489 clspv::AddressSpace::UniformConstant);
1490 break;
1491 default:
1492 break;
1493 }
1494
1495 // The converted type is the type of the OpVariable we will generate.
1496 // If the pointee type is an array of size zero, FindType will convert it
1497 // to a runtime array.
1498 FindType(type);
1499 }
1500
alan-bakerdcd97412019-09-16 15:32:30 -04001501 // If module constants are clustered in a storage buffer then that struct
1502 // needs layout decorations.
1503 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001504 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001505 PointerType *PTy = cast<PointerType>(GV.getType());
1506 const auto AS = PTy->getAddressSpace();
1507 const bool module_scope_constant_external_init =
1508 (AS == AddressSpace::Constant) && GV.hasInitializer();
1509 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1510 if (module_scope_constant_external_init &&
1511 spv::BuiltInMax == BuiltinType) {
1512 StructTypesNeedingBlock.insert(
1513 cast<StructType>(PTy->getPointerElementType()));
1514 }
1515 }
1516 }
1517
SJW77b87ad2020-04-21 14:37:52 -05001518 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001519 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1520 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1521 assert(Ty->isStructTy() && "Push constants have to be structures.");
1522 auto STy = cast<StructType>(Ty);
1523 StructTypesNeedingBlock.insert(STy);
1524 }
1525 }
1526
David Neto862b7d82018-06-14 18:48:37 -04001527 // Traverse the arrays and structures underneath each Block, and
1528 // mark them as needing layout.
1529 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1530 StructTypesNeedingBlock.end());
1531 while (!work_list.empty()) {
1532 Type *type = work_list.back();
1533 work_list.pop_back();
1534 TypesNeedingLayout.insert(type);
1535 switch (type->getTypeID()) {
1536 case Type::ArrayTyID:
1537 work_list.push_back(type->getArrayElementType());
1538 if (!Hack_generate_runtime_array_stride_early) {
1539 // Remember this array type for deferred decoration.
1540 TypesNeedingArrayStride.insert(type);
1541 }
1542 break;
1543 case Type::StructTyID:
1544 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1545 work_list.push_back(elem_ty);
1546 }
1547 default:
1548 // This type and its contained types don't get layout.
1549 break;
1550 }
1551 }
1552}
1553
SJW77b87ad2020-04-21 14:37:52 -05001554void SPIRVProducerPass::FindWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001555 // The SpecId assignment for pointer-to-local arguments is recorded in
1556 // module-level metadata. Translate that information into local argument
1557 // information.
SJW77b87ad2020-04-21 14:37:52 -05001558 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001559 if (!nmd)
1560 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001561 for (auto operand : nmd->operands()) {
1562 MDTuple *tuple = cast<MDTuple>(operand);
1563 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1564 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001565 ConstantAsMetadata *arg_index_md =
1566 cast<ConstantAsMetadata>(tuple->getOperand(1));
1567 int arg_index = static_cast<int>(
1568 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1569 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001570
1571 ConstantAsMetadata *spec_id_md =
1572 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001573 int spec_id = static_cast<int>(
1574 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001575
Alan Baker202c8c72018-08-13 13:47:44 -04001576 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001577 if (LocalSpecIdInfoMap.count(spec_id))
1578 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001579
1580 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1581 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1582 nextID + 1, nextID + 2,
1583 nextID + 3, spec_id};
1584 LocalSpecIdInfoMap[spec_id] = info;
1585 nextID += 4;
1586
1587 // Ensure the types necessary for this argument get generated.
SJW77b87ad2020-04-21 14:37:52 -05001588 Type *IdxTy = Type::getInt32Ty(module->getContext());
Alan Baker202c8c72018-08-13 13:47:44 -04001589 FindConstant(ConstantInt::get(IdxTy, 0));
1590 FindType(IdxTy);
1591 FindType(arg->getType());
1592 }
1593}
1594
David Neto22f144c2017-06-12 14:26:21 -04001595void SPIRVProducerPass::FindType(Type *Ty) {
1596 TypeList &TyList = getTypeList();
1597
1598 if (0 != TyList.idFor(Ty)) {
1599 return;
1600 }
1601
1602 if (Ty->isPointerTy()) {
1603 auto AddrSpace = Ty->getPointerAddressSpace();
1604 if ((AddressSpace::Constant == AddrSpace) ||
1605 (AddressSpace::Global == AddrSpace)) {
1606 auto PointeeTy = Ty->getPointerElementType();
1607
1608 if (PointeeTy->isStructTy() &&
1609 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1610 FindType(PointeeTy);
1611 auto ActualPointerTy =
1612 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1613 FindType(ActualPointerTy);
1614 return;
1615 }
1616 }
1617 }
1618
David Neto862b7d82018-06-14 18:48:37 -04001619 // By convention, LLVM array type with 0 elements will map to
1620 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1621 // has a constant number of elements. We need to support type of the
1622 // constant.
1623 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1624 if (arrayTy->getNumElements() > 0) {
1625 LLVMContext &Context = Ty->getContext();
1626 FindType(Type::getInt32Ty(Context));
1627 }
David Neto22f144c2017-06-12 14:26:21 -04001628 }
1629
1630 for (Type *SubTy : Ty->subtypes()) {
1631 FindType(SubTy);
1632 }
1633
1634 TyList.insert(Ty);
1635}
1636
1637void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1638 // If the global variable has a (non undef) initializer.
1639 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001640 // Generate the constant if it's not the initializer to a module scope
1641 // constant that we will expect in a storage buffer.
1642 const bool module_scope_constant_external_init =
1643 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1644 clspv::Option::ModuleConstantsInStorageBuffer();
1645 if (!module_scope_constant_external_init) {
1646 FindConstant(GV.getInitializer());
1647 }
David Neto22f144c2017-06-12 14:26:21 -04001648 }
1649}
1650
1651void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1652 // Investigate constants in function body.
1653 for (BasicBlock &BB : F) {
1654 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001655 if (auto *call = dyn_cast<CallInst>(&I)) {
1656 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001657 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001658 // We've handled these constants elsewhere, so skip it.
1659 continue;
1660 }
Alan Baker202c8c72018-08-13 13:47:44 -04001661 if (name.startswith(clspv::ResourceAccessorFunction())) {
1662 continue;
1663 }
1664 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001665 continue;
1666 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001667 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1668 // Skip the first operand that has the SPIR-V Opcode
1669 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1670 if (isa<Constant>(I.getOperand(i)) &&
1671 !isa<GlobalValue>(I.getOperand(i))) {
1672 FindConstant(I.getOperand(i));
1673 }
1674 }
1675 continue;
1676 }
David Neto22f144c2017-06-12 14:26:21 -04001677 }
1678
1679 if (isa<AllocaInst>(I)) {
1680 // Alloca instruction has constant for the number of element. Ignore it.
1681 continue;
1682 } else if (isa<ShuffleVectorInst>(I)) {
1683 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1684 // Ignore constant for mask of shuffle vector instruction.
1685 if (i == 2) {
1686 continue;
1687 }
1688
1689 if (isa<Constant>(I.getOperand(i)) &&
1690 !isa<GlobalValue>(I.getOperand(i))) {
1691 FindConstant(I.getOperand(i));
1692 }
1693 }
1694
1695 continue;
1696 } else if (isa<InsertElementInst>(I)) {
1697 // Handle InsertElement with <4 x i8> specially.
1698 Type *CompositeTy = I.getOperand(0)->getType();
1699 if (is4xi8vec(CompositeTy)) {
1700 LLVMContext &Context = CompositeTy->getContext();
1701 if (isa<Constant>(I.getOperand(0))) {
1702 FindConstant(I.getOperand(0));
1703 }
1704
1705 if (isa<Constant>(I.getOperand(1))) {
1706 FindConstant(I.getOperand(1));
1707 }
1708
1709 // Add mask constant 0xFF.
1710 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1711 FindConstant(CstFF);
1712
1713 // Add shift amount constant.
1714 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1715 uint64_t Idx = CI->getZExtValue();
1716 Constant *CstShiftAmount =
1717 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1718 FindConstant(CstShiftAmount);
1719 }
1720
1721 continue;
1722 }
1723
1724 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1725 // Ignore constant for index of InsertElement instruction.
1726 if (i == 2) {
1727 continue;
1728 }
1729
1730 if (isa<Constant>(I.getOperand(i)) &&
1731 !isa<GlobalValue>(I.getOperand(i))) {
1732 FindConstant(I.getOperand(i));
1733 }
1734 }
1735
1736 continue;
1737 } else if (isa<ExtractElementInst>(I)) {
1738 // Handle ExtractElement with <4 x i8> specially.
1739 Type *CompositeTy = I.getOperand(0)->getType();
1740 if (is4xi8vec(CompositeTy)) {
1741 LLVMContext &Context = CompositeTy->getContext();
1742 if (isa<Constant>(I.getOperand(0))) {
1743 FindConstant(I.getOperand(0));
1744 }
1745
1746 // Add mask constant 0xFF.
1747 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1748 FindConstant(CstFF);
1749
1750 // Add shift amount constant.
1751 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1752 uint64_t Idx = CI->getZExtValue();
1753 Constant *CstShiftAmount =
1754 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1755 FindConstant(CstShiftAmount);
1756 } else {
1757 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1758 FindConstant(Cst8);
1759 }
1760
1761 continue;
1762 }
1763
1764 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1765 // Ignore constant for index of ExtractElement instruction.
1766 if (i == 1) {
1767 continue;
1768 }
1769
1770 if (isa<Constant>(I.getOperand(i)) &&
1771 !isa<GlobalValue>(I.getOperand(i))) {
1772 FindConstant(I.getOperand(i));
1773 }
1774 }
1775
1776 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001777 } else if ((Instruction::Xor == I.getOpcode()) &&
1778 I.getType()->isIntegerTy(1)) {
1779 // We special case for Xor where the type is i1 and one of the arguments
1780 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1781 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001782 bool foundConstantTrue = false;
1783 for (Use &Op : I.operands()) {
1784 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1785 auto CI = cast<ConstantInt>(Op);
1786
1787 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001788 // If we already found the true constant, we might (probably only
1789 // on -O0) have an OpLogicalNot which is taking a constant
1790 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001791 FindConstant(Op);
1792 } else {
1793 foundConstantTrue = true;
1794 }
1795 }
1796 }
1797
1798 continue;
David Netod2de94a2017-08-28 17:27:47 -04001799 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001800 // Special case if i8 is not generally handled.
1801 if (!clspv::Option::Int8Support()) {
1802 // For truncation to i8 we mask against 255.
1803 Type *ToTy = I.getType();
1804 if (8u == ToTy->getPrimitiveSizeInBits()) {
1805 LLVMContext &Context = ToTy->getContext();
1806 Constant *Cst255 =
1807 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1808 FindConstant(Cst255);
1809 }
David Netod2de94a2017-08-28 17:27:47 -04001810 }
Neil Henning39672102017-09-29 14:33:13 +01001811 } else if (isa<AtomicRMWInst>(I)) {
1812 LLVMContext &Context = I.getContext();
1813
1814 FindConstant(
1815 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1816 FindConstant(ConstantInt::get(
1817 Type::getInt32Ty(Context),
1818 spv::MemorySemanticsUniformMemoryMask |
1819 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001820 }
1821
1822 for (Use &Op : I.operands()) {
1823 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1824 FindConstant(Op);
1825 }
1826 }
1827 }
1828 }
1829}
1830
1831void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001832 ValueList &CstList = getConstantList();
1833
David Netofb9a7972017-08-25 17:08:24 -04001834 // If V is already tracked, ignore it.
1835 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001836 return;
1837 }
1838
David Neto862b7d82018-06-14 18:48:37 -04001839 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1840 return;
1841 }
1842
David Neto22f144c2017-06-12 14:26:21 -04001843 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001844 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001845
1846 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001847 if (is4xi8vec(CstTy)) {
1848 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001849 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001850 }
1851 }
1852
1853 if (Cst->getNumOperands()) {
1854 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1855 ++I) {
1856 FindConstant(*I);
1857 }
1858
David Netofb9a7972017-08-25 17:08:24 -04001859 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001860 return;
1861 } else if (const ConstantDataSequential *CDS =
1862 dyn_cast<ConstantDataSequential>(Cst)) {
1863 // Add constants for each element to constant list.
1864 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1865 Constant *EleCst = CDS->getElementAsConstant(i);
1866 FindConstant(EleCst);
1867 }
1868 }
1869
1870 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001871 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001872 }
1873}
1874
1875spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1876 switch (AddrSpace) {
1877 default:
1878 llvm_unreachable("Unsupported OpenCL address space");
1879 case AddressSpace::Private:
1880 return spv::StorageClassFunction;
1881 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001882 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001883 case AddressSpace::Constant:
1884 return clspv::Option::ConstantArgsInUniformBuffer()
1885 ? spv::StorageClassUniform
1886 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001887 case AddressSpace::Input:
1888 return spv::StorageClassInput;
1889 case AddressSpace::Local:
1890 return spv::StorageClassWorkgroup;
1891 case AddressSpace::UniformConstant:
1892 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001893 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001894 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001895 case AddressSpace::ModuleScopePrivate:
1896 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001897 case AddressSpace::PushConstant:
1898 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001899 }
1900}
1901
David Neto862b7d82018-06-14 18:48:37 -04001902spv::StorageClass
1903SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1904 switch (arg_kind) {
1905 case clspv::ArgKind::Buffer:
1906 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001907 case clspv::ArgKind::BufferUBO:
1908 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001909 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001910 return spv::StorageClassStorageBuffer;
1911 case clspv::ArgKind::PodUBO:
1912 return spv::StorageClassUniform;
1913 case clspv::ArgKind::PodPushConstant:
1914 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001915 case clspv::ArgKind::Local:
1916 return spv::StorageClassWorkgroup;
1917 case clspv::ArgKind::ReadOnlyImage:
1918 case clspv::ArgKind::WriteOnlyImage:
1919 case clspv::ArgKind::Sampler:
1920 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001921 default:
1922 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001923 }
1924}
1925
David Neto22f144c2017-06-12 14:26:21 -04001926spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1927 return StringSwitch<spv::BuiltIn>(Name)
1928 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1929 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1930 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1931 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1932 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001933 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
David Neto22f144c2017-06-12 14:26:21 -04001934 .Default(spv::BuiltInMax);
1935}
1936
1937void SPIRVProducerPass::GenerateExtInstImport() {
SJW69939d52020-04-16 07:29:07 -05001938 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kImports);
David Neto22f144c2017-06-12 14:26:21 -04001939 uint32_t &ExtInstImportID = getOpExtInstImportID();
1940
1941 //
1942 // Generate OpExtInstImport.
1943 //
1944 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001945 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001946 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1947 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001948}
1949
SJW77b87ad2020-04-21 14:37:52 -05001950void SPIRVProducerPass::GenerateSPIRVTypes() {
SJW69939d52020-04-16 07:29:07 -05001951 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kTypes);
David Neto22f144c2017-06-12 14:26:21 -04001952 ValueMapType &VMap = getValueMap();
1953 ValueMapType &AllocatedVMap = getAllocatedValueMap();
SJW77b87ad2020-04-21 14:37:52 -05001954 const auto &DL = module->getDataLayout();
1955 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04001956
1957 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1958 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1959 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1960
1961 for (Type *Ty : getTypeList()) {
1962 // Update TypeMap with nextID for reference later.
1963 TypeMap[Ty] = nextID;
1964
1965 switch (Ty->getTypeID()) {
1966 default: {
1967 Ty->print(errs());
1968 llvm_unreachable("Unsupported type???");
1969 break;
1970 }
1971 case Type::MetadataTyID:
1972 case Type::LabelTyID: {
1973 // Ignore these types.
1974 break;
1975 }
1976 case Type::PointerTyID: {
1977 PointerType *PTy = cast<PointerType>(Ty);
1978 unsigned AddrSpace = PTy->getAddressSpace();
1979
1980 // For the purposes of our Vulkan SPIR-V type system, constant and global
1981 // are conflated.
1982 bool UseExistingOpTypePointer = false;
1983 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001984 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1985 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001986 // Check to see if we already created this type (for instance, if we
1987 // had a constant <type>* and a global <type>*, the type would be
1988 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001989 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1990 if (0 < TypeMap.count(GlobalTy)) {
1991 TypeMap[PTy] = TypeMap[GlobalTy];
1992 UseExistingOpTypePointer = true;
1993 break;
1994 }
David Neto22f144c2017-06-12 14:26:21 -04001995 }
1996 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001997 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1998 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001999
alan-bakerb6b09dc2018-11-08 16:59:28 -05002000 // Check to see if we already created this type (for instance, if we
2001 // had a constant <type>* and a global <type>*, the type would be
2002 // created by one of these types, and shared by both).
2003 auto ConstantTy =
2004 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04002005 if (0 < TypeMap.count(ConstantTy)) {
2006 TypeMap[PTy] = TypeMap[ConstantTy];
2007 UseExistingOpTypePointer = true;
2008 }
David Neto22f144c2017-06-12 14:26:21 -04002009 }
2010 }
2011
David Neto862b7d82018-06-14 18:48:37 -04002012 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04002013
David Neto862b7d82018-06-14 18:48:37 -04002014 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04002015 //
2016 // Generate OpTypePointer.
2017 //
2018
2019 // OpTypePointer
2020 // Ops[0] = Storage Class
2021 // Ops[1] = Element Type ID
2022 SPIRVOperandList Ops;
2023
David Neto257c3892018-04-11 13:19:45 -04002024 Ops << MkNum(GetStorageClass(AddrSpace))
2025 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04002026
David Neto87846742018-04-11 17:36:22 -04002027 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002028 SPIRVInstList.push_back(Inst);
2029 }
David Neto22f144c2017-06-12 14:26:21 -04002030 break;
2031 }
2032 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002033 StructType *STy = cast<StructType>(Ty);
2034
2035 // Handle sampler type.
2036 if (STy->isOpaque()) {
2037 if (STy->getName().equals("opencl.sampler_t")) {
2038 //
2039 // Generate OpTypeSampler
2040 //
2041 // Empty Ops.
2042 SPIRVOperandList Ops;
2043
David Neto87846742018-04-11 17:36:22 -04002044 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002045 SPIRVInstList.push_back(Inst);
2046 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05002047 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
2048 STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002049 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2050 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05002051 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002052 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002053 STy->getName().startswith("opencl.image2d_array_ro_t") ||
2054 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002055 STy->getName().startswith("opencl.image3d_ro_t") ||
2056 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002057 //
2058 // Generate OpTypeImage
2059 //
2060 // Ops[0] = Sampled Type ID
2061 // Ops[1] = Dim ID
2062 // Ops[2] = Depth (Literal Number)
2063 // Ops[3] = Arrayed (Literal Number)
2064 // Ops[4] = MS (Literal Number)
2065 // Ops[5] = Sampled (Literal Number)
2066 // Ops[6] = Image Format ID
2067 //
2068 SPIRVOperandList Ops;
2069
alan-bakerf67468c2019-11-25 15:51:49 -05002070 uint32_t ImageTyID = nextID++;
2071 uint32_t SampledTyID = 0;
2072 if (STy->getName().contains(".float")) {
2073 SampledTyID = lookupType(Type::getFloatTy(Context));
2074 } else if (STy->getName().contains(".uint")) {
2075 SampledTyID = lookupType(Type::getInt32Ty(Context));
2076 } else if (STy->getName().contains(".int")) {
2077 // Generate a signed 32-bit integer if necessary.
2078 if (int32ID == 0) {
2079 int32ID = nextID++;
2080 SPIRVOperandList intOps;
2081 intOps << MkNum(32);
2082 intOps << MkNum(1);
2083 auto signed_int =
2084 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
2085 SPIRVInstList.push_back(signed_int);
2086 }
2087 SampledTyID = int32ID;
2088
2089 // Generate a vec4 of the signed int if necessary.
2090 if (v4int32ID == 0) {
2091 v4int32ID = nextID++;
2092 SPIRVOperandList vecOps;
2093 vecOps << MkId(int32ID);
2094 vecOps << MkNum(4);
2095 auto int_vec =
2096 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
2097 SPIRVInstList.push_back(int_vec);
2098 }
2099 } else {
2100 // This was likely an UndefValue.
2101 SampledTyID = lookupType(Type::getFloatTy(Context));
2102 }
David Neto257c3892018-04-11 13:19:45 -04002103 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04002104
2105 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05002106 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002107 STy->getName().startswith("opencl.image1d_wo_t") ||
2108 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2109 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05002110 DimID = spv::Dim1D;
2111 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
2112 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002113 DimID = spv::Dim3D;
2114 }
David Neto257c3892018-04-11 13:19:45 -04002115 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04002116
2117 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04002118 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002119
alan-baker7150a1d2020-02-25 08:31:06 -05002120 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
2121 Ops << MkNum(arrayed);
David Neto22f144c2017-06-12 14:26:21 -04002122
2123 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04002124 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002125
alan-baker7150a1d2020-02-25 08:31:06 -05002126 // Set up Sampled.
David Neto22f144c2017-06-12 14:26:21 -04002127 //
2128 // From Spec
2129 //
2130 // 0 indicates this is only known at run time, not at compile time
2131 // 1 indicates will be used with sampler
2132 // 2 indicates will be used without a sampler (a storage image)
2133 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002134 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002135 Sampled = 2;
2136 }
David Neto257c3892018-04-11 13:19:45 -04002137 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002138
2139 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002140 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002141
alan-bakerf67468c2019-11-25 15:51:49 -05002142 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002143 SPIRVInstList.push_back(Inst);
2144 break;
2145 }
2146 }
2147
2148 //
2149 // Generate OpTypeStruct
2150 //
2151 // Ops[0] ... Ops[n] = Member IDs
2152 SPIRVOperandList Ops;
2153
2154 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002155 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002156 }
2157
David Neto22f144c2017-06-12 14:26:21 -04002158 uint32_t STyID = nextID;
2159
alan-bakerb6b09dc2018-11-08 16:59:28 -05002160 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002161 SPIRVInstList.push_back(Inst);
2162
2163 // Generate OpMemberDecorate.
Kévin Petitbbbda972020-03-03 19:16:31 +00002164 if (TypesNeedingLayout.idFor(STy)) {
2165 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2166 MemberIdx++) {
2167 // Ops[0] = Structure Type ID
2168 // Ops[1] = Member Index(Literal Number)
2169 // Ops[2] = Decoration (Offset)
2170 // Ops[3] = Byte Offset (Literal Number)
2171 Ops.clear();
David Netoc463b372017-08-10 15:32:21 -04002172
Kévin Petitbbbda972020-03-03 19:16:31 +00002173 Ops << MkId(STyID) << MkNum(MemberIdx)
2174 << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002175
Kévin Petitbbbda972020-03-03 19:16:31 +00002176 const auto ByteOffset =
2177 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
David Neto22f144c2017-06-12 14:26:21 -04002178
Kévin Petitbbbda972020-03-03 19:16:31 +00002179 Ops << MkNum(ByteOffset);
2180
2181 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002182 getSPIRVInstList(kAnnotations).push_back(DecoInst);
Alan Bakerfcda9482018-10-02 17:09:59 -04002183 }
David Neto22f144c2017-06-12 14:26:21 -04002184 }
2185
2186 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002187 if (StructTypesNeedingBlock.idFor(STy)) {
2188 Ops.clear();
2189 // Use Block decorations with StorageBuffer storage class.
2190 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002191
David Neto862b7d82018-06-14 18:48:37 -04002192 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002193 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002194 }
2195 break;
2196 }
2197 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002198 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002199
2200 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002201 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002202 SPIRVInstList.push_back(Inst);
2203 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002204 if (!clspv::Option::Int8Support()) {
2205 // i8 is added to TypeMap as i32.
2206 // No matter what LLVM type is requested first, always alias the
2207 // second one's SPIR-V type to be the same as the one we generated
2208 // first.
2209 unsigned aliasToWidth = 0;
2210 if (BitWidth == 8) {
2211 aliasToWidth = 32;
2212 BitWidth = 32;
2213 } else if (BitWidth == 32) {
2214 aliasToWidth = 8;
2215 }
2216 if (aliasToWidth) {
2217 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2218 auto where = TypeMap.find(otherType);
2219 if (where == TypeMap.end()) {
2220 // Go ahead and make it, but also map the other type to it.
2221 TypeMap[otherType] = nextID;
2222 } else {
2223 // Alias this SPIR-V type the existing type.
2224 TypeMap[Ty] = where->second;
2225 break;
2226 }
David Neto391aeb12017-08-26 15:51:58 -04002227 }
David Neto22f144c2017-06-12 14:26:21 -04002228 }
2229
David Neto257c3892018-04-11 13:19:45 -04002230 SPIRVOperandList Ops;
2231 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002232
2233 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002234 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002235 }
2236 break;
2237 }
2238 case Type::HalfTyID:
2239 case Type::FloatTyID:
2240 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002241 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002242 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002243
2244 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002245 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002246 break;
2247 }
2248 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002249 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002250 const uint64_t Length = ArrTy->getArrayNumElements();
2251 if (Length == 0) {
2252 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002253
David Neto862b7d82018-06-14 18:48:37 -04002254 // Only generate the type once.
2255 // TODO(dneto): Can it ever be generated more than once?
2256 // Doesn't LLVM type uniqueness guarantee we'll only see this
2257 // once?
2258 Type *EleTy = ArrTy->getArrayElementType();
2259 if (OpRuntimeTyMap.count(EleTy) == 0) {
2260 uint32_t OpTypeRuntimeArrayID = nextID;
2261 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002262
David Neto862b7d82018-06-14 18:48:37 -04002263 //
2264 // Generate OpTypeRuntimeArray.
2265 //
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 // OpTypeRuntimeArray
2268 // Ops[0] = Element Type ID
2269 SPIRVOperandList Ops;
2270 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002271
David Neto862b7d82018-06-14 18:48:37 -04002272 SPIRVInstList.push_back(
2273 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002274
David Neto862b7d82018-06-14 18:48:37 -04002275 if (Hack_generate_runtime_array_stride_early) {
2276 // Generate OpDecorate.
David Neto22f144c2017-06-12 14:26:21 -04002277
David Neto862b7d82018-06-14 18:48:37 -04002278 // Ops[0] = Target ID
2279 // Ops[1] = Decoration (ArrayStride)
2280 // Ops[2] = Stride Number(Literal Number)
2281 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002282
David Neto862b7d82018-06-14 18:48:37 -04002283 Ops << MkId(OpTypeRuntimeArrayID)
2284 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002285 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002286
David Neto862b7d82018-06-14 18:48:37 -04002287 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002288 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002289 }
2290 }
David Neto22f144c2017-06-12 14:26:21 -04002291
David Neto862b7d82018-06-14 18:48:37 -04002292 } else {
David Neto22f144c2017-06-12 14:26:21 -04002293
David Neto862b7d82018-06-14 18:48:37 -04002294 //
2295 // Generate OpConstant and OpTypeArray.
2296 //
2297
2298 //
2299 // Generate OpConstant for array length.
2300 //
2301 // Ops[0] = Result Type ID
2302 // Ops[1] .. Ops[n] = Values LiteralNumber
2303 SPIRVOperandList Ops;
2304
2305 Type *LengthTy = Type::getInt32Ty(Context);
2306 uint32_t ResTyID = lookupType(LengthTy);
2307 Ops << MkId(ResTyID);
2308
2309 assert(Length < UINT32_MAX);
2310 Ops << MkNum(static_cast<uint32_t>(Length));
2311
2312 // Add constant for length to constant list.
2313 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2314 AllocatedVMap[CstLength] = nextID;
2315 VMap[CstLength] = nextID;
2316 uint32_t LengthID = nextID;
2317
2318 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2319 SPIRVInstList.push_back(CstInst);
2320
2321 // Remember to generate ArrayStride later
2322 getTypesNeedingArrayStride().insert(Ty);
2323
2324 //
2325 // Generate OpTypeArray.
2326 //
2327 // Ops[0] = Element Type ID
2328 // Ops[1] = Array Length Constant ID
2329 Ops.clear();
2330
2331 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2332 Ops << MkId(EleTyID) << MkId(LengthID);
2333
2334 // Update TypeMap with nextID.
2335 TypeMap[Ty] = nextID;
2336
2337 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2338 SPIRVInstList.push_back(ArrayInst);
2339 }
David Neto22f144c2017-06-12 14:26:21 -04002340 break;
2341 }
James Price59a1c752020-04-23 23:06:16 -04002342 case Type::FixedVectorTyID: {
James Pricecf53df42020-04-20 14:41:24 -04002343 auto VecTy = cast<VectorType>(Ty);
alan-bakerb39c8262019-03-08 14:03:37 -05002344 // <4 x i8> is changed to i32 if i8 is not generally supported.
2345 if (!clspv::Option::Int8Support() &&
James Pricecf53df42020-04-20 14:41:24 -04002346 VecTy->getElementType() == Type::getInt8Ty(Context)) {
2347 if (VecTy->getNumElements() == 4) {
2348 TypeMap[Ty] = lookupType(VecTy->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002349 break;
2350 } else {
2351 Ty->print(errs());
2352 llvm_unreachable("Support above i8 vector type");
2353 }
2354 }
2355
2356 // Ops[0] = Component Type ID
2357 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002358 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04002359 Ops << MkId(lookupType(VecTy->getElementType()))
2360 << MkNum(VecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002361
alan-bakerb6b09dc2018-11-08 16:59:28 -05002362 SPIRVInstruction *inst =
2363 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002364 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002365 break;
2366 }
2367 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002368 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002369 SPIRVInstList.push_back(Inst);
2370 break;
2371 }
2372 case Type::FunctionTyID: {
2373 // Generate SPIRV instruction for function type.
2374 FunctionType *FTy = cast<FunctionType>(Ty);
2375
2376 // Ops[0] = Return Type ID
2377 // Ops[1] ... Ops[n] = Parameter Type IDs
2378 SPIRVOperandList Ops;
2379
2380 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002381 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002382
2383 // Find SPIRV instructions for parameter types
2384 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2385 // Find SPIRV instruction for parameter type.
2386 auto ParamTy = FTy->getParamType(k);
2387 if (ParamTy->isPointerTy()) {
2388 auto PointeeTy = ParamTy->getPointerElementType();
2389 if (PointeeTy->isStructTy() &&
2390 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2391 ParamTy = PointeeTy;
2392 }
2393 }
2394
David Netoc6f3ab22018-04-06 18:02:31 -04002395 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002396 }
2397
David Neto87846742018-04-11 17:36:22 -04002398 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002399 SPIRVInstList.push_back(Inst);
2400 break;
2401 }
2402 }
2403 }
2404
2405 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002406 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002407 //
2408 // Generate OpTypeSampledImage.
2409 //
2410 // Ops[0] = Image Type ID
2411 //
2412 SPIRVOperandList Ops;
2413
David Netoc6f3ab22018-04-06 18:02:31 -04002414 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002415
alan-bakerabd82722019-12-03 17:14:51 -05002416 // Update the image type map.
2417 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002418
David Neto87846742018-04-11 17:36:22 -04002419 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002420 SPIRVInstList.push_back(Inst);
2421 }
David Netoc6f3ab22018-04-06 18:02:31 -04002422
2423 // Generate types for pointer-to-local arguments.
SJW77b87ad2020-04-21 14:37:52 -05002424 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04002425 auto kind = pair.first;
2426 auto spec_id = pair.second;
2427
2428 if (kind != SpecConstant::kLocalMemorySize)
2429 continue;
2430
alan-bakerb6b09dc2018-11-08 16:59:28 -05002431 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002432
2433 // Generate the spec constant.
2434 SPIRVOperandList Ops;
2435 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002436 SPIRVInstList.push_back(
2437 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002438
2439 // Generate the array type.
2440 Ops.clear();
2441 // The element type must have been created.
2442 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2443 assert(elem_ty_id);
2444 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2445
2446 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002447 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002448
2449 Ops.clear();
2450 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002451 SPIRVInstList.push_back(new SPIRVInstruction(
2452 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002453 }
David Neto22f144c2017-06-12 14:26:21 -04002454}
2455
2456void SPIRVProducerPass::GenerateSPIRVConstants() {
SJW69939d52020-04-16 07:29:07 -05002457 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kConstants);
David Neto22f144c2017-06-12 14:26:21 -04002458 ValueMapType &VMap = getValueMap();
2459 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2460 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002461 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002462
2463 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002464 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002465 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002466
2467 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002468 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002469 continue;
2470 }
2471
David Netofb9a7972017-08-25 17:08:24 -04002472 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002473 VMap[Cst] = nextID;
2474
2475 //
2476 // Generate OpConstant.
2477 //
2478
2479 // Ops[0] = Result Type ID
2480 // Ops[1] .. Ops[n] = Values LiteralNumber
2481 SPIRVOperandList Ops;
2482
David Neto257c3892018-04-11 13:19:45 -04002483 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002484
2485 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002486 spv::Op Opcode = spv::OpNop;
2487
2488 if (isa<UndefValue>(Cst)) {
2489 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002490 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002491 if (hack_undef && IsTypeNullable(Cst->getType())) {
2492 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002493 }
David Neto22f144c2017-06-12 14:26:21 -04002494 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2495 unsigned BitWidth = CI->getBitWidth();
2496 if (BitWidth == 1) {
2497 // If the bitwidth of constant is 1, generate OpConstantTrue or
2498 // OpConstantFalse.
2499 if (CI->getZExtValue()) {
2500 // Ops[0] = Result Type ID
2501 Opcode = spv::OpConstantTrue;
2502 } else {
2503 // Ops[0] = Result Type ID
2504 Opcode = spv::OpConstantFalse;
2505 }
David Neto22f144c2017-06-12 14:26:21 -04002506 } else {
2507 auto V = CI->getZExtValue();
2508 LiteralNum.push_back(V & 0xFFFFFFFF);
2509
2510 if (BitWidth > 32) {
2511 LiteralNum.push_back(V >> 32);
2512 }
2513
2514 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto257c3892018-04-11 13:19:45 -04002516 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002517 }
2518 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2519 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2520 Type *CFPTy = CFP->getType();
2521 if (CFPTy->isFloatTy()) {
2522 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002523 } else if (CFPTy->isDoubleTy()) {
2524 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2525 LiteralNum.push_back(FPVal >> 32);
alan-baker089bf932020-01-07 16:35:45 -05002526 } else if (CFPTy->isHalfTy()) {
2527 LiteralNum.push_back(FPVal & 0xFFFF);
David Neto22f144c2017-06-12 14:26:21 -04002528 } else {
2529 CFPTy->print(errs());
2530 llvm_unreachable("Implement this ConstantFP Type");
2531 }
2532
2533 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002534
David Neto257c3892018-04-11 13:19:45 -04002535 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002536 } else if (isa<ConstantDataSequential>(Cst) &&
2537 cast<ConstantDataSequential>(Cst)->isString()) {
2538 Cst->print(errs());
2539 llvm_unreachable("Implement this Constant");
2540
2541 } else if (const ConstantDataSequential *CDS =
2542 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002543 // Let's convert <4 x i8> constant to int constant specially.
2544 // This case occurs when all the values are specified as constant
2545 // ints.
2546 Type *CstTy = Cst->getType();
2547 if (is4xi8vec(CstTy)) {
2548 LLVMContext &Context = CstTy->getContext();
2549
2550 //
2551 // Generate OpConstant with OpTypeInt 32 0.
2552 //
Neil Henning39672102017-09-29 14:33:13 +01002553 uint32_t IntValue = 0;
2554 for (unsigned k = 0; k < 4; k++) {
2555 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002556 IntValue = (IntValue << 8) | (Val & 0xffu);
2557 }
2558
2559 Type *i32 = Type::getInt32Ty(Context);
2560 Constant *CstInt = ConstantInt::get(i32, IntValue);
2561 // If this constant is already registered on VMap, use it.
2562 if (VMap.count(CstInt)) {
2563 uint32_t CstID = VMap[CstInt];
2564 VMap[Cst] = CstID;
2565 continue;
2566 }
2567
David Neto257c3892018-04-11 13:19:45 -04002568 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002569
David Neto87846742018-04-11 17:36:22 -04002570 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002571 SPIRVInstList.push_back(CstInst);
2572
2573 continue;
2574 }
2575
2576 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002577 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2578 Constant *EleCst = CDS->getElementAsConstant(k);
2579 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002580 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002581 }
2582
2583 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002584 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2585 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002586 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002587 Type *CstTy = Cst->getType();
2588 if (is4xi8vec(CstTy)) {
2589 LLVMContext &Context = CstTy->getContext();
2590
2591 //
2592 // Generate OpConstant with OpTypeInt 32 0.
2593 //
Neil Henning39672102017-09-29 14:33:13 +01002594 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002595 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2596 I != E; ++I) {
2597 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002598 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002599 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2600 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002601 }
David Neto49351ac2017-08-26 17:32:20 -04002602 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002603 }
2604
David Neto49351ac2017-08-26 17:32:20 -04002605 Type *i32 = Type::getInt32Ty(Context);
2606 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002607 // If this constant is already registered on VMap, use it.
2608 if (VMap.count(CstInt)) {
2609 uint32_t CstID = VMap[CstInt];
2610 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002611 continue;
David Neto22f144c2017-06-12 14:26:21 -04002612 }
2613
David Neto257c3892018-04-11 13:19:45 -04002614 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002615
David Neto87846742018-04-11 17:36:22 -04002616 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002617 SPIRVInstList.push_back(CstInst);
2618
David Neto19a1bad2017-08-25 15:01:41 -04002619 continue;
David Neto22f144c2017-06-12 14:26:21 -04002620 }
2621
2622 // We use a constant composite in SPIR-V for our constant aggregate in
2623 // LLVM.
2624 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002625
2626 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2627 // Look up the ID of the element of this aggregate (which we will
2628 // previously have created a constant for).
2629 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2630
2631 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002632 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002633 }
2634 } else if (Cst->isNullValue()) {
2635 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002636 } else {
2637 Cst->print(errs());
2638 llvm_unreachable("Unsupported Constant???");
2639 }
2640
alan-baker5b86ed72019-02-15 08:26:50 -05002641 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2642 // Null pointer requires variable pointers.
2643 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2644 }
2645
David Neto87846742018-04-11 17:36:22 -04002646 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002647 SPIRVInstList.push_back(CstInst);
2648 }
2649}
2650
SJW77b87ad2020-04-21 14:37:52 -05002651void SPIRVProducerPass::GenerateSamplers() {
SJW69939d52020-04-16 07:29:07 -05002652 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002653
alan-bakerb6b09dc2018-11-08 16:59:28 -05002654 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002655 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002656 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2657 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002658
David Neto862b7d82018-06-14 18:48:37 -04002659 // We might have samplers in the sampler map that are not used
2660 // in the translation unit. We need to allocate variables
2661 // for them and bindings too.
2662 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002663
SJW77b87ad2020-04-21 14:37:52 -05002664 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002665 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002666 if (!var_fn)
2667 return;
alan-baker09cb9802019-12-10 13:16:27 -05002668
David Neto862b7d82018-06-14 18:48:37 -04002669 for (auto user : var_fn->users()) {
2670 // Populate SamplerLiteralToDescriptorSetMap and
2671 // SamplerLiteralToBindingMap.
2672 //
2673 // Look for calls like
2674 // call %opencl.sampler_t addrspace(2)*
2675 // @clspv.sampler.var.literal(
2676 // i32 descriptor,
2677 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002678 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002679 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002680 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002681 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002682 auto sampler_value = third_param;
2683 if (clspv::Option::UseSamplerMap()) {
2684 if (third_param >= sampler_map.size()) {
2685 errs() << "Out of bounds index to sampler map: " << third_param;
2686 llvm_unreachable("bad sampler init: out of bounds");
2687 }
2688 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002689 }
2690
David Neto862b7d82018-06-14 18:48:37 -04002691 const auto descriptor_set = static_cast<unsigned>(
2692 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2693 const auto binding = static_cast<unsigned>(
2694 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2695
2696 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2697 SamplerLiteralToBindingMap[sampler_value] = binding;
2698 used_bindings.insert(binding);
2699 }
2700 }
2701
alan-baker09cb9802019-12-10 13:16:27 -05002702 DenseSet<size_t> seen;
2703 for (auto user : var_fn->users()) {
2704 if (!isa<CallInst>(user))
2705 continue;
2706
2707 auto call = cast<CallInst>(user);
2708 const unsigned third_param = static_cast<unsigned>(
2709 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2710
2711 // Already allocated a variable for this value.
2712 if (!seen.insert(third_param).second)
2713 continue;
2714
2715 auto sampler_value = third_param;
2716 if (clspv::Option::UseSamplerMap()) {
2717 sampler_value = sampler_map[third_param].first;
2718 }
2719
David Neto22f144c2017-06-12 14:26:21 -04002720 // Generate OpVariable.
2721 //
2722 // GIDOps[0] : Result Type ID
2723 // GIDOps[1] : Storage Class
2724 SPIRVOperandList Ops;
2725
David Neto257c3892018-04-11 13:19:45 -04002726 Ops << MkId(lookupType(SamplerTy))
2727 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002728
David Neto862b7d82018-06-14 18:48:37 -04002729 auto sampler_var_id = nextID++;
2730 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002731 SPIRVInstList.push_back(Inst);
2732
alan-baker09cb9802019-12-10 13:16:27 -05002733 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002734
David Neto862b7d82018-06-14 18:48:37 -04002735 unsigned descriptor_set;
2736 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002737 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002738 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002739 // This sampler is not actually used. Find the next one.
2740 for (binding = 0; used_bindings.count(binding); binding++)
2741 ;
2742 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2743 used_bindings.insert(binding);
2744 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002745 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2746 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002747
alan-baker09cb9802019-12-10 13:16:27 -05002748 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002749 descriptorMapEntries->emplace_back(std::move(sampler_data),
2750 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002751 }
2752
SJW69939d52020-04-16 07:29:07 -05002753 // Ops[0] = Target ID
2754 // Ops[1] = Decoration (DescriptorSet)
2755 // Ops[2] = LiteralNumber according to Decoration
2756 Ops.clear();
2757
David Neto862b7d82018-06-14 18:48:37 -04002758 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2759 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002760
David Neto87846742018-04-11 17:36:22 -04002761 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002762 getSPIRVInstList(kAnnotations).push_back(DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002763
2764 // Ops[0] = Target ID
2765 // Ops[1] = Decoration (Binding)
2766 // Ops[2] = LiteralNumber according to Decoration
2767 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002768 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2769 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002770
David Neto87846742018-04-11 17:36:22 -04002771 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002772 getSPIRVInstList(kAnnotations).push_back(BindDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002773 }
David Neto862b7d82018-06-14 18:48:37 -04002774}
David Neto22f144c2017-06-12 14:26:21 -04002775
SJW77b87ad2020-04-21 14:37:52 -05002776void SPIRVProducerPass::GenerateResourceVars() {
SJW69939d52020-04-16 07:29:07 -05002777 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto862b7d82018-06-14 18:48:37 -04002778 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002779
David Neto862b7d82018-06-14 18:48:37 -04002780 // Generate variables. Make one for each of resource var info object.
2781 for (auto *info : ModuleOrderedResourceVars) {
2782 Type *type = info->var_fn->getReturnType();
2783 // Remap the address space for opaque types.
2784 switch (info->arg_kind) {
2785 case clspv::ArgKind::Sampler:
2786 case clspv::ArgKind::ReadOnlyImage:
2787 case clspv::ArgKind::WriteOnlyImage:
2788 type = PointerType::get(type->getPointerElementType(),
2789 clspv::AddressSpace::UniformConstant);
2790 break;
2791 default:
2792 break;
2793 }
David Neto22f144c2017-06-12 14:26:21 -04002794
David Neto862b7d82018-06-14 18:48:37 -04002795 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002796
David Neto862b7d82018-06-14 18:48:37 -04002797 const auto type_id = lookupType(type);
2798 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2799 SPIRVOperandList Ops;
2800 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002801
David Neto862b7d82018-06-14 18:48:37 -04002802 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2803 SPIRVInstList.push_back(Inst);
2804
2805 // Map calls to the variable-builtin-function.
2806 for (auto &U : info->var_fn->uses()) {
2807 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2808 const auto set = unsigned(
2809 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2810 const auto binding = unsigned(
2811 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2812 if (set == info->descriptor_set && binding == info->binding) {
2813 switch (info->arg_kind) {
2814 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002815 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002816 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002817 case clspv::ArgKind::PodUBO:
2818 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002819 // The call maps to the variable directly.
2820 VMap[call] = info->var_id;
2821 break;
2822 case clspv::ArgKind::Sampler:
2823 case clspv::ArgKind::ReadOnlyImage:
2824 case clspv::ArgKind::WriteOnlyImage:
2825 // The call maps to a load we generate later.
2826 ResourceVarDeferredLoadCalls[call] = info->var_id;
2827 break;
2828 default:
2829 llvm_unreachable("Unhandled arg kind");
2830 }
2831 }
David Neto22f144c2017-06-12 14:26:21 -04002832 }
David Neto862b7d82018-06-14 18:48:37 -04002833 }
2834 }
David Neto22f144c2017-06-12 14:26:21 -04002835
David Neto862b7d82018-06-14 18:48:37 -04002836 // Generate associated decorations.
SJW69939d52020-04-16 07:29:07 -05002837 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto862b7d82018-06-14 18:48:37 -04002838
2839 SPIRVOperandList Ops;
2840 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002841 // Push constants don't need descriptor set or binding decorations.
2842 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2843 continue;
2844
David Neto862b7d82018-06-14 18:48:37 -04002845 // Decorate with DescriptorSet and Binding.
2846 Ops.clear();
2847 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2848 << MkNum(info->descriptor_set);
SJW69939d52020-04-16 07:29:07 -05002849 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002850
2851 Ops.clear();
2852 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2853 << MkNum(info->binding);
SJW69939d52020-04-16 07:29:07 -05002854 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002855
alan-bakere9308012019-03-15 10:25:13 -04002856 if (info->coherent) {
2857 // Decorate with Coherent if required for the variable.
2858 Ops.clear();
2859 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05002860 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
alan-bakere9308012019-03-15 10:25:13 -04002861 }
2862
David Neto862b7d82018-06-14 18:48:37 -04002863 // Generate NonWritable and NonReadable
2864 switch (info->arg_kind) {
2865 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002866 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002867 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2868 clspv::AddressSpace::Constant) {
2869 Ops.clear();
2870 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
SJW69939d52020-04-16 07:29:07 -05002871 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002872 }
David Neto862b7d82018-06-14 18:48:37 -04002873 break;
David Neto862b7d82018-06-14 18:48:37 -04002874 case clspv::ArgKind::WriteOnlyImage:
2875 Ops.clear();
2876 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
SJW69939d52020-04-16 07:29:07 -05002877 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002878 break;
2879 default:
2880 break;
David Neto22f144c2017-06-12 14:26:21 -04002881 }
2882 }
2883}
2884
SJW77b87ad2020-04-21 14:37:52 -05002885void SPIRVProducerPass::GeneratePushConstantDescriptorMapEntries() {
Kévin Petitbbbda972020-03-03 19:16:31 +00002886
SJW77b87ad2020-04-21 14:37:52 -05002887 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
2888 auto const &DL = module->getDataLayout();
Kévin Petitbbbda972020-03-03 19:16:31 +00002889 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
2890 auto STy = cast<StructType>(GV->getValueType());
2891
2892 for (unsigned i = 0; i < STy->getNumElements(); i++) {
2893 auto pc = static_cast<clspv::PushConstant>(
2894 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
2895 auto memberType = STy->getElementType(i);
2896 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
2897 unsigned previousOffset = 0;
2898 if (i > 0) {
2899 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
2900 }
2901 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
SJW77b87ad2020-04-21 14:37:52 -05002902 assert(isValidExplicitLayout(*module, STy, i,
2903 spv::StorageClassPushConstant, offset,
2904 previousOffset));
Kévin Petitbbbda972020-03-03 19:16:31 +00002905 version0::DescriptorMapEntry::PushConstantData data = {pc, offset, size};
2906 descriptorMapEntries->emplace_back(std::move(data));
2907 }
2908 }
2909}
2910
SJW77b87ad2020-04-21 14:37:52 -05002911void SPIRVProducerPass::GenerateSpecConstantDescriptorMapEntries() {
2912 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04002913 auto kind = pair.first;
2914 auto id = pair.second;
2915
2916 // Local memory size is only used for kernel arguments.
2917 if (kind == SpecConstant::kLocalMemorySize)
2918 continue;
2919
2920 version0::DescriptorMapEntry::SpecConstantData data = {kind, id};
2921 descriptorMapEntries->emplace_back(std::move(data));
2922 }
2923}
2924
David Neto22f144c2017-06-12 14:26:21 -04002925void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
SJW69939d52020-04-16 07:29:07 -05002926 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002927 ValueMapType &VMap = getValueMap();
2928 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002929 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002930
2931 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2932 Type *Ty = GV.getType();
2933 PointerType *PTy = cast<PointerType>(Ty);
2934
2935 uint32_t InitializerID = 0;
2936
2937 // Workgroup size is handled differently (it goes into a constant)
2938 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2939 std::vector<bool> HasMDVec;
2940 uint32_t PrevXDimCst = 0xFFFFFFFF;
2941 uint32_t PrevYDimCst = 0xFFFFFFFF;
2942 uint32_t PrevZDimCst = 0xFFFFFFFF;
2943 for (Function &Func : *GV.getParent()) {
2944 if (Func.isDeclaration()) {
2945 continue;
2946 }
2947
2948 // We only need to check kernels.
2949 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2950 continue;
2951 }
2952
2953 if (const MDNode *MD =
2954 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2955 uint32_t CurXDimCst = static_cast<uint32_t>(
2956 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2957 uint32_t CurYDimCst = static_cast<uint32_t>(
2958 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2959 uint32_t CurZDimCst = static_cast<uint32_t>(
2960 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2961
2962 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2963 PrevZDimCst == 0xFFFFFFFF) {
2964 PrevXDimCst = CurXDimCst;
2965 PrevYDimCst = CurYDimCst;
2966 PrevZDimCst = CurZDimCst;
2967 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2968 CurZDimCst != PrevZDimCst) {
2969 llvm_unreachable(
2970 "reqd_work_group_size must be the same across all kernels");
2971 } else {
2972 continue;
2973 }
2974
2975 //
2976 // Generate OpConstantComposite.
2977 //
2978 // Ops[0] : Result Type ID
2979 // Ops[1] : Constant size for x dimension.
2980 // Ops[2] : Constant size for y dimension.
2981 // Ops[3] : Constant size for z dimension.
2982 SPIRVOperandList Ops;
2983
2984 uint32_t XDimCstID =
2985 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2986 uint32_t YDimCstID =
2987 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2988 uint32_t ZDimCstID =
2989 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2990
2991 InitializerID = nextID;
2992
David Neto257c3892018-04-11 13:19:45 -04002993 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2994 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002995
David Neto87846742018-04-11 17:36:22 -04002996 auto *Inst =
2997 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04002998 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04002999
3000 HasMDVec.push_back(true);
3001 } else {
3002 HasMDVec.push_back(false);
3003 }
3004 }
3005
3006 // Check all kernels have same definitions for work_group_size.
3007 bool HasMD = false;
3008 if (!HasMDVec.empty()) {
3009 HasMD = HasMDVec[0];
3010 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
3011 if (HasMD != HasMDVec[i]) {
3012 llvm_unreachable(
3013 "Kernels should have consistent work group size definition");
3014 }
3015 }
3016 }
3017
3018 // If all kernels do not have metadata for reqd_work_group_size, generate
3019 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01003020 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04003021 //
3022 // Generate OpSpecConstants for x/y/z dimension.
3023 //
3024 // Ops[0] : Result Type ID
3025 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
3026 uint32_t XDimCstID = 0;
3027 uint32_t YDimCstID = 0;
3028 uint32_t ZDimCstID = 0;
3029
alan-bakera1be3322020-04-20 12:48:18 -04003030 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05003031 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04003032
David Neto22f144c2017-06-12 14:26:21 -04003033 SPIRVOperandList Ops;
James Pricecf53df42020-04-20 14:41:24 -04003034 uint32_t result_type_id = lookupType(
3035 cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04003036
David Neto257c3892018-04-11 13:19:45 -04003037 // X Dimension
3038 Ops << MkId(result_type_id) << MkNum(1);
3039 XDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003040 getSPIRVInstList(kConstants)
3041 .push_back(new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003042
3043 // Y Dimension
3044 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003045 Ops << MkId(result_type_id) << MkNum(1);
3046 YDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003047 getSPIRVInstList(kConstants)
3048 .push_back(new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003049
3050 // Z Dimension
3051 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003052 Ops << MkId(result_type_id) << MkNum(1);
3053 ZDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003054 getSPIRVInstList(kConstants)
3055 .push_back(new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003056
David Neto257c3892018-04-11 13:19:45 -04003057 BuiltinDimVec.push_back(XDimCstID);
3058 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003059 BuiltinDimVec.push_back(ZDimCstID);
3060
David Neto22f144c2017-06-12 14:26:21 -04003061 //
3062 // Generate OpSpecConstantComposite.
3063 //
3064 // Ops[0] : Result Type ID
3065 // Ops[1] : Constant size for x dimension.
3066 // Ops[2] : Constant size for y dimension.
3067 // Ops[3] : Constant size for z dimension.
3068 InitializerID = nextID;
3069
3070 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003071 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3072 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003073
David Neto87846742018-04-11 17:36:22 -04003074 auto *Inst =
3075 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003076 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003077 }
alan-bakerbed3a882020-04-21 14:42:41 -04003078 } else if (BuiltinType == spv::BuiltInWorkDim) {
3079 // 1. Generate a specialization constant with a default of 3.
3080 // 2. Allocate and annotate a SpecId for the constant.
3081 // 3. Use the spec constant as the initializer for the variable.
3082 SPIRVOperandList Ops;
3083
3084 //
3085 // Generate OpSpecConstant.
3086 //
3087 // Ops[0] : Result Type ID
3088 // Ops[1] : Default literal value
3089 InitializerID = nextID++;
3090
3091 Ops << MkId(lookupType(IntegerType::get(GV.getContext(), 32))) << MkNum(3);
3092
3093 auto *Inst = new SPIRVInstruction(spv::OpSpecConstant, InitializerID, Ops);
3094 getSPIRVInstList(kConstants).push_back(Inst);
3095
3096 //
3097 // Generate SpecId decoration.
3098 //
3099 // Ops[0] : target
3100 // Ops[1] : decoration
3101 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04003102 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04003103 Ops.clear();
3104 Ops << MkId(InitializerID) << MkNum(spv::DecorationSpecId)
3105 << MkNum(spec_id);
3106
3107 Inst = new SPIRVInstruction(spv::OpDecorate, Ops);
3108 getSPIRVInstList(kAnnotations).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003109 }
3110
David Neto22f144c2017-06-12 14:26:21 -04003111 VMap[&GV] = nextID;
3112
3113 //
3114 // Generate OpVariable.
3115 //
3116 // GIDOps[0] : Result Type ID
3117 // GIDOps[1] : Storage Class
3118 SPIRVOperandList Ops;
3119
David Neto85082642018-03-24 06:55:20 -07003120 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04003121 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04003122
David Neto85082642018-03-24 06:55:20 -07003123 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04003124 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07003125 clspv::Option::ModuleConstantsInStorageBuffer();
3126
Kévin Petit23d5f182019-08-13 16:21:29 +01003127 if (GV.hasInitializer()) {
3128 auto GVInit = GV.getInitializer();
3129 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
3130 assert(VMap.count(GVInit) == 1);
3131 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07003132 }
3133 }
Kévin Petit23d5f182019-08-13 16:21:29 +01003134
3135 if (0 != InitializerID) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003136 // Emit the ID of the initializer as part of the variable definition.
Kévin Petit23d5f182019-08-13 16:21:29 +01003137 Ops << MkId(InitializerID);
3138 }
David Neto85082642018-03-24 06:55:20 -07003139 const uint32_t var_id = nextID++;
3140
David Neto87846742018-04-11 17:36:22 -04003141 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003142 SPIRVInstList.push_back(Inst);
3143
SJW69939d52020-04-16 07:29:07 -05003144 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
alan-bakerbed3a882020-04-21 14:42:41 -04003145 // If we have a builtin (not WorkDim).
3146 if (spv::BuiltInMax != BuiltinType && BuiltinType != spv::BuiltInWorkDim) {
David Neto22f144c2017-06-12 14:26:21 -04003147 //
3148 // Generate OpDecorate.
3149 //
3150 // DOps[0] = Target ID
3151 // DOps[1] = Decoration (Builtin)
3152 // DOps[2] = BuiltIn ID
3153 uint32_t ResultID;
3154
3155 // WorkgroupSize is different, we decorate the constant composite that has
3156 // its value, rather than the variable that we use to access the value.
3157 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3158 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04003159 // Save both the value and variable IDs for later.
3160 WorkgroupSizeValueID = InitializerID;
3161 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04003162 } else {
3163 ResultID = VMap[&GV];
3164 }
3165
3166 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003167 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3168 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003169
David Neto87846742018-04-11 17:36:22 -04003170 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
SJW69939d52020-04-16 07:29:07 -05003171 Annotations.push_back(DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003172 } else if (module_scope_constant_external_init) {
3173 // This module scope constant is initialized from a storage buffer with data
3174 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05003175 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07003176
David Neto862b7d82018-06-14 18:48:37 -04003177 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003178 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3179 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003180 std::string hexbytes;
3181 llvm::raw_string_ostream str(hexbytes);
3182 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003183 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3184 str.str()};
3185 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3186 0);
David Neto85082642018-03-24 06:55:20 -07003187
David Neto85082642018-03-24 06:55:20 -07003188 SPIRVOperandList DOps;
David Neto85082642018-03-24 06:55:20 -07003189
3190 // OpDecorate %var DescriptorSet <descriptor_set>
David Neto257c3892018-04-11 13:19:45 -04003191 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3192 << MkNum(descriptor_set);
SJW69939d52020-04-16 07:29:07 -05003193 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
3194
3195 // OpDecorate %var Binding <binding>
3196 DOps.clear();
3197 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3198 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003199 }
3200}
3201
SJW77b87ad2020-04-21 14:37:52 -05003202void SPIRVProducerPass::GenerateWorkgroupVars() {
SJW69939d52020-04-16 07:29:07 -05003203 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
SJW77b87ad2020-04-21 14:37:52 -05003204 auto spec_constant_md =
3205 module->getNamedMetadata(clspv::SpecConstantMetadataName());
alan-bakera1be3322020-04-20 12:48:18 -04003206 if (!spec_constant_md)
3207 return;
3208
SJW77b87ad2020-04-21 14:37:52 -05003209 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04003210 auto kind = pair.first;
3211 auto spec_id = pair.second;
3212
3213 if (kind != SpecConstant::kLocalMemorySize)
3214 continue;
3215
alan-bakerb6b09dc2018-11-08 16:59:28 -05003216 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003217
3218 // Generate OpVariable.
3219 //
3220 // GIDOps[0] : Result Type ID
3221 // GIDOps[1] : Storage Class
3222 SPIRVOperandList Ops;
3223 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3224
3225 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003226 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003227 }
3228}
3229
SJW77b87ad2020-04-21 14:37:52 -05003230void SPIRVProducerPass::GenerateDescriptorMapInfo(Function &F) {
3231 const auto &DL = module->getDataLayout();
David Netoc5fb5242018-07-30 13:28:31 -04003232 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3233 return;
3234 }
Kévin Petit717f8572020-04-06 17:31:53 +01003235 // Add entries for each kernel
3236 version0::DescriptorMapEntry::KernelDeclData kernel_decl_data = {
3237 F.getName().str()};
3238 descriptorMapEntries->emplace_back(std::move(kernel_decl_data));
3239
David Neto862b7d82018-06-14 18:48:37 -04003240 // Gather the list of resources that are used by this function's arguments.
3241 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3242
David Neto862b7d82018-06-14 18:48:37 -04003243 auto *fty = F.getType()->getPointerElementType();
3244 auto *func_ty = dyn_cast<FunctionType>(fty);
3245
alan-baker038e9242019-04-19 22:14:41 -04003246 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003247 // If an argument maps to a resource variable, then get descriptor set and
3248 // binding from the resoure variable. Other info comes from the metadata.
alan-bakerff6c9292020-05-04 08:32:09 -04003249 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
3250 auto local_spec_id_md =
3251 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
David Neto862b7d82018-06-14 18:48:37 -04003252 if (arg_map) {
3253 for (const auto &arg : arg_map->operands()) {
3254 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
alan-bakerff6c9292020-05-04 08:32:09 -04003255 assert(arg_node->getNumOperands() == 6);
David Neto862b7d82018-06-14 18:48:37 -04003256 const auto name =
3257 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3258 const auto old_index =
3259 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3260 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003261 const size_t new_index = static_cast<size_t>(
3262 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003263 const auto offset =
3264 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003265 const auto arg_size =
3266 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
alan-bakerc4579bb2020-04-29 14:15:50 -04003267 const auto argKind = clspv::GetArgKindFromName(
3268 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
alan-bakerf5e5f692018-11-27 08:33:24 -05003269
alan-bakerff6c9292020-05-04 08:32:09 -04003270 // If this is a local memory argument, find the right spec id for this
3271 // argument.
3272 int64_t spec_id = -1;
3273 if (argKind == clspv::ArgKind::Local) {
3274 for (auto spec_id_arg : local_spec_id_md->operands()) {
3275 if ((&F == dyn_cast<Function>(
3276 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
3277 ->getValue())) &&
3278 (new_index ==
3279 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
3280 ->getZExtValue())) {
3281 spec_id = mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
3282 ->getSExtValue();
3283 break;
3284 }
3285 }
3286 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003287 uint32_t descriptor_set = 0;
3288 uint32_t binding = 0;
3289 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003290 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
3291 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05003292 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003293 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003294 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003295 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3296 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3297 DL));
David Neto862b7d82018-06-14 18:48:37 -04003298 } else {
3299 auto *info = resource_var_at_index[new_index];
3300 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003301 descriptor_set = info->descriptor_set;
3302 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003303 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003304 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3305 binding);
David Neto862b7d82018-06-14 18:48:37 -04003306 }
3307 } else {
3308 // There is no argument map.
3309 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003310 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003311
3312 SmallVector<Argument *, 4> arguments;
3313 for (auto &arg : F.args()) {
3314 arguments.push_back(&arg);
3315 }
3316
3317 unsigned arg_index = 0;
3318 for (auto *info : resource_var_at_index) {
3319 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003320 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003321 unsigned arg_size = 0;
alan-baker9b0ec3c2020-04-06 14:45:34 -04003322 if (info->arg_kind == clspv::ArgKind::Pod ||
3323 info->arg_kind == clspv::ArgKind::PodUBO ||
3324 info->arg_kind == clspv::ArgKind::PodPushConstant) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003325 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003326 }
3327
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003328 // Local pointer arguments are unused in this case. Offset is always
3329 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003330 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003331 F.getName().str(),
3332 arg->getName().str(),
3333 arg_index,
alan-bakerc4579bb2020-04-29 14:15:50 -04003334 info->arg_kind,
alan-baker21574d32020-01-29 16:00:31 -05003335 0,
3336 0,
3337 0,
3338 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05003339 descriptorMapEntries->emplace_back(std::move(kernel_data),
3340 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003341 }
3342 arg_index++;
3343 }
3344 // Generate mappings for pointer-to-local arguments.
3345 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3346 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003347 auto where = LocalArgSpecIds.find(arg);
3348 if (where != LocalArgSpecIds.end()) {
3349 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003350 // Pod arguments members are unused in this case.
3351 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003352 F.getName().str(),
3353 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05003354 arg_index,
3355 ArgKind::Local,
3356 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003357 static_cast<uint32_t>(
3358 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003359 0,
3360 0};
3361 // Pointer-to-local arguments do not utilize descriptor set and binding.
3362 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003363 }
3364 }
3365 }
3366}
3367
David Neto22f144c2017-06-12 14:26:21 -04003368void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003369 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003370 ValueMapType &VMap = getValueMap();
3371 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003372 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3373 auto &GlobalConstArgSet = getGlobalConstArgSet();
3374
3375 FunctionType *FTy = F.getFunctionType();
3376
3377 //
David Neto22f144c2017-06-12 14:26:21 -04003378 // Generate OPFunction.
3379 //
3380
3381 // FOps[0] : Result Type ID
3382 // FOps[1] : Function Control
3383 // FOps[2] : Function Type ID
3384 SPIRVOperandList FOps;
3385
3386 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003387 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003388
3389 // Check function attributes for SPIRV Function Control.
3390 uint32_t FuncControl = spv::FunctionControlMaskNone;
3391 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3392 FuncControl |= spv::FunctionControlInlineMask;
3393 }
3394 if (F.hasFnAttribute(Attribute::NoInline)) {
3395 FuncControl |= spv::FunctionControlDontInlineMask;
3396 }
3397 // TODO: Check llvm attribute for Function Control Pure.
3398 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3399 FuncControl |= spv::FunctionControlPureMask;
3400 }
3401 // TODO: Check llvm attribute for Function Control Const.
3402 if (F.hasFnAttribute(Attribute::ReadNone)) {
3403 FuncControl |= spv::FunctionControlConstMask;
3404 }
3405
David Neto257c3892018-04-11 13:19:45 -04003406 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003407
3408 uint32_t FTyID;
3409 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3410 SmallVector<Type *, 4> NewFuncParamTys;
3411 FunctionType *NewFTy =
3412 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3413 FTyID = lookupType(NewFTy);
3414 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003415 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003416 if (GlobalConstFuncTyMap.count(FTy)) {
3417 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3418 } else {
3419 FTyID = lookupType(FTy);
3420 }
3421 }
3422
David Neto257c3892018-04-11 13:19:45 -04003423 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003424
3425 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3426 EntryPoints.push_back(std::make_pair(&F, nextID));
3427 }
3428
3429 VMap[&F] = nextID;
3430
David Neto482550a2018-03-24 05:21:07 -07003431 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003432 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3433 }
David Neto22f144c2017-06-12 14:26:21 -04003434 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003435 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003436 SPIRVInstList.push_back(FuncInst);
3437
3438 //
3439 // Generate OpFunctionParameter for Normal function.
3440 //
3441
3442 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003443
David Neto22f144c2017-06-12 14:26:21 -04003444 // Iterate Argument for name instead of param type from function type.
3445 unsigned ArgIdx = 0;
3446 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003447 uint32_t param_id = nextID++;
3448 VMap[&Arg] = param_id;
3449
3450 if (CalledWithCoherentResource(Arg)) {
3451 // If the arg is passed a coherent resource ever, then decorate this
3452 // parameter with Coherent too.
3453 SPIRVOperandList decoration_ops;
3454 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05003455 getSPIRVInstList(kAnnotations)
3456 .push_back(new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003457 }
David Neto22f144c2017-06-12 14:26:21 -04003458
3459 // ParamOps[0] : Result Type ID
3460 SPIRVOperandList ParamOps;
3461
3462 // Find SPIRV instruction for parameter type.
3463 uint32_t ParamTyID = lookupType(Arg.getType());
3464 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3465 if (GlobalConstFuncTyMap.count(FTy)) {
3466 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3467 Type *EleTy = PTy->getPointerElementType();
3468 Type *ArgTy =
3469 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3470 ParamTyID = lookupType(ArgTy);
3471 GlobalConstArgSet.insert(&Arg);
3472 }
3473 }
3474 }
David Neto257c3892018-04-11 13:19:45 -04003475 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003476
3477 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003478 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003479 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003480 SPIRVInstList.push_back(ParamInst);
3481
3482 ArgIdx++;
3483 }
3484 }
3485}
3486
SJW77b87ad2020-04-21 14:37:52 -05003487void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04003488 EntryPointVecType &EntryPoints = getEntryPointVec();
3489 ValueMapType &VMap = getValueMap();
3490 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
David Neto22f144c2017-06-12 14:26:21 -04003491 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3492
SJW69939d52020-04-16 07:29:07 -05003493 SPIRVInstructionList &SPIRVCapabilities = getSPIRVInstList(kCapabilities);
David Neto22f144c2017-06-12 14:26:21 -04003494 //
3495 // Generate OpCapability
3496 //
3497 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3498
3499 // Ops[0] = Capability
3500 SPIRVOperandList Ops;
3501
David Neto87846742018-04-11 17:36:22 -04003502 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003503 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
SJW69939d52020-04-16 07:29:07 -05003504 SPIRVCapabilities.push_back(CapInst);
David Neto22f144c2017-06-12 14:26:21 -04003505
alan-bakerf906d2b2019-12-10 11:26:23 -05003506 bool write_without_format = false;
3507 bool sampled_1d = false;
3508 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003509 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003510 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3511 // Generate OpCapability for i8 type.
SJW69939d52020-04-16 07:29:07 -05003512 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003513 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003514 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003515 // Generate OpCapability for i16 type.
SJW69939d52020-04-16 07:29:07 -05003516 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003517 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003518 } else if (Ty->isIntegerTy(64)) {
3519 // Generate OpCapability for i64 type.
SJW69939d52020-04-16 07:29:07 -05003520 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003521 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003522 } else if (Ty->isHalfTy()) {
3523 // Generate OpCapability for half type.
SJW69939d52020-04-16 07:29:07 -05003524 SPIRVCapabilities.push_back(new SPIRVInstruction(
3525 spv::OpCapability, MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003526 } else if (Ty->isDoubleTy()) {
3527 // Generate OpCapability for double type.
SJW69939d52020-04-16 07:29:07 -05003528 SPIRVCapabilities.push_back(new SPIRVInstruction(
3529 spv::OpCapability, MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003530 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3531 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003532 if (STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003533 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05003534 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003535 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003536 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003537 write_without_format = true;
3538 }
3539 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003540 STy->getName().startswith("opencl.image1d_wo_t") ||
3541 STy->getName().startswith("opencl.image1d_array_ro_t") ||
3542 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003543 if (STy->getName().contains(".sampled"))
3544 sampled_1d = true;
3545 else
3546 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003547 }
3548 }
3549 }
3550 }
3551
alan-bakerf906d2b2019-12-10 11:26:23 -05003552 if (write_without_format) {
3553 // Generate OpCapability for write only image type.
SJW69939d52020-04-16 07:29:07 -05003554 SPIRVCapabilities.push_back(new SPIRVInstruction(
3555 spv::OpCapability,
3556 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003557 }
3558 if (image_1d) {
3559 // Generate OpCapability for unsampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003560 SPIRVCapabilities.push_back(new SPIRVInstruction(
3561 spv::OpCapability, {MkNum(spv::CapabilityImage1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003562 } else if (sampled_1d) {
3563 // Generate OpCapability for sampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003564 SPIRVCapabilities.push_back(new SPIRVInstruction(
3565 spv::OpCapability, {MkNum(spv::CapabilitySampled1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003566 }
3567
David Neto5c22a252018-03-15 16:07:41 -04003568 { // OpCapability ImageQuery
3569 bool hasImageQuery = false;
SJW77b87ad2020-04-21 14:37:52 -05003570 for (const auto &SymVal : module->getValueSymbolTable()) {
alan-bakerf67468c2019-11-25 15:51:49 -05003571 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
SJW173c7e92020-03-16 08:44:47 -05003572 if (IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003573 hasImageQuery = true;
3574 break;
3575 }
David Neto5c22a252018-03-15 16:07:41 -04003576 }
3577 }
alan-bakerf67468c2019-11-25 15:51:49 -05003578
David Neto5c22a252018-03-15 16:07:41 -04003579 if (hasImageQuery) {
SJW69939d52020-04-16 07:29:07 -05003580 SPIRVCapabilities.push_back(new SPIRVInstruction(
3581 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)}));
David Neto5c22a252018-03-15 16:07:41 -04003582 }
3583 }
3584
David Neto22f144c2017-06-12 14:26:21 -04003585 if (hasVariablePointers()) {
3586 //
David Neto22f144c2017-06-12 14:26:21 -04003587 // Generate OpCapability.
3588 //
3589 // Ops[0] = Capability
3590 //
3591 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003592 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003593
SJW69939d52020-04-16 07:29:07 -05003594 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003595 } else if (hasVariablePointersStorageBuffer()) {
3596 //
3597 // Generate OpCapability.
3598 //
3599 // Ops[0] = Capability
3600 //
3601 Ops.clear();
3602 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003603
SJW69939d52020-04-16 07:29:07 -05003604 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003605 }
3606
SJW69939d52020-04-16 07:29:07 -05003607 SPIRVInstructionList &SPIRVExtensions = getSPIRVInstList(kExtensions);
alan-baker5b86ed72019-02-15 08:26:50 -05003608 // Always add the storage buffer extension
3609 {
David Neto22f144c2017-06-12 14:26:21 -04003610 //
3611 // Generate OpExtension.
3612 //
3613 // Ops[0] = Name (Literal String)
3614 //
alan-baker5b86ed72019-02-15 08:26:50 -05003615 auto *ExtensionInst = new SPIRVInstruction(
3616 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
SJW69939d52020-04-16 07:29:07 -05003617 SPIRVExtensions.push_back(ExtensionInst);
alan-baker5b86ed72019-02-15 08:26:50 -05003618 }
David Neto22f144c2017-06-12 14:26:21 -04003619
alan-baker5b86ed72019-02-15 08:26:50 -05003620 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3621 //
3622 // Generate OpExtension.
3623 //
3624 // Ops[0] = Name (Literal String)
3625 //
3626 auto *ExtensionInst = new SPIRVInstruction(
3627 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
SJW69939d52020-04-16 07:29:07 -05003628 SPIRVExtensions.push_back(ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003629 }
3630
3631 //
3632 // Generate OpMemoryModel
3633 //
3634 // Memory model for Vulkan will always be GLSL450.
3635
3636 // Ops[0] = Addressing Model
3637 // Ops[1] = Memory Model
3638 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003639 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003640
David Neto87846742018-04-11 17:36:22 -04003641 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
SJW69939d52020-04-16 07:29:07 -05003642 getSPIRVInstList(kMemoryModel).push_back(MemModelInst);
David Neto22f144c2017-06-12 14:26:21 -04003643
SJW69939d52020-04-16 07:29:07 -05003644 SPIRVInstructionList &SPIRVEntryPoints = getSPIRVInstList(kEntryPoints);
David Neto22f144c2017-06-12 14:26:21 -04003645 //
3646 // Generate OpEntryPoint
3647 //
3648 for (auto EntryPoint : EntryPoints) {
3649 // Ops[0] = Execution Model
3650 // Ops[1] = EntryPoint ID
3651 // Ops[2] = Name (Literal String)
3652 // ...
3653 //
3654 // TODO: Do we need to consider Interface ID for forward references???
3655 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003656 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003657 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3658 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003659
David Neto22f144c2017-06-12 14:26:21 -04003660 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003661 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003662 }
3663
David Neto87846742018-04-11 17:36:22 -04003664 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
SJW69939d52020-04-16 07:29:07 -05003665 SPIRVEntryPoints.push_back(EntryPointInst);
David Neto22f144c2017-06-12 14:26:21 -04003666 }
3667
SJW69939d52020-04-16 07:29:07 -05003668 SPIRVInstructionList &SPIRVExecutionModes = getSPIRVInstList(kExecutionModes);
David Neto22f144c2017-06-12 14:26:21 -04003669 for (auto EntryPoint : EntryPoints) {
Kévin Petit21c23c62020-04-29 01:38:28 +01003670 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3671 ->getMetadata("reqd_work_group_size");
3672 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04003673
3674 if (!BuiltinDimVec.empty()) {
3675 llvm_unreachable(
3676 "Kernels should have consistent work group size definition");
3677 }
3678
3679 //
3680 // Generate OpExecutionMode
3681 //
3682
3683 // Ops[0] = Entry Point ID
3684 // Ops[1] = Execution Mode
3685 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3686 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003687 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003688
3689 uint32_t XDim = static_cast<uint32_t>(
3690 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3691 uint32_t YDim = static_cast<uint32_t>(
3692 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3693 uint32_t ZDim = static_cast<uint32_t>(
3694 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3695
David Neto257c3892018-04-11 13:19:45 -04003696 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003697
David Neto87846742018-04-11 17:36:22 -04003698 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
SJW69939d52020-04-16 07:29:07 -05003699 SPIRVExecutionModes.push_back(ExecModeInst);
David Neto22f144c2017-06-12 14:26:21 -04003700 }
3701 }
3702
3703 //
3704 // Generate OpSource.
3705 //
3706 // Ops[0] = SourceLanguage ID
3707 // Ops[1] = Version (LiteralNum)
3708 //
3709 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003710 switch (clspv::Option::Language()) {
3711 case clspv::Option::SourceLanguage::OpenCL_C_10:
3712 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3713 break;
3714 case clspv::Option::SourceLanguage::OpenCL_C_11:
3715 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3716 break;
3717 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003718 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003719 break;
3720 case clspv::Option::SourceLanguage::OpenCL_C_20:
3721 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3722 break;
3723 case clspv::Option::SourceLanguage::OpenCL_CPP:
3724 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3725 break;
3726 default:
3727 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3728 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003729 }
David Neto22f144c2017-06-12 14:26:21 -04003730
David Neto87846742018-04-11 17:36:22 -04003731 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
SJW69939d52020-04-16 07:29:07 -05003732 getSPIRVInstList(kDebug).push_back(OpenSourceInst);
David Neto22f144c2017-06-12 14:26:21 -04003733
3734 if (!BuiltinDimVec.empty()) {
SJW69939d52020-04-16 07:29:07 -05003735 SPIRVInstructionList &SPIRVAnnotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003736 //
3737 // Generate OpDecorates for x/y/z dimension.
3738 //
3739 // Ops[0] = Target ID
3740 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003741 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003742
3743 // X Dimension
3744 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003745 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
SJW69939d52020-04-16 07:29:07 -05003746 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003747
3748 // Y Dimension
3749 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003750 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
SJW69939d52020-04-16 07:29:07 -05003751 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003752
3753 // Z Dimension
3754 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003755 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
SJW69939d52020-04-16 07:29:07 -05003756 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003757 }
3758}
3759
David Netob6e2e062018-04-25 10:32:06 -04003760void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3761 // Work around a driver bug. Initializers on Private variables might not
3762 // work. So the start of the kernel should store the initializer value to the
3763 // variables. Yes, *every* entry point pays this cost if *any* entry point
3764 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3765 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003766 // TODO(dneto): Remove this at some point once fixed drivers are widely
3767 // available.
David Netob6e2e062018-04-25 10:32:06 -04003768 if (WorkgroupSizeVarID) {
3769 assert(WorkgroupSizeValueID);
3770
3771 SPIRVOperandList Ops;
3772 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3773
3774 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
SJW69939d52020-04-16 07:29:07 -05003775 getSPIRVInstList(kFunctions).push_back(Inst);
David Netob6e2e062018-04-25 10:32:06 -04003776 }
3777}
3778
David Neto22f144c2017-06-12 14:26:21 -04003779void SPIRVProducerPass::GenerateFuncBody(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003780 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003781 ValueMapType &VMap = getValueMap();
3782
David Netob6e2e062018-04-25 10:32:06 -04003783 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003784
3785 for (BasicBlock &BB : F) {
3786 // Register BasicBlock to ValueMap.
3787 VMap[&BB] = nextID;
3788
3789 //
3790 // Generate OpLabel for Basic Block.
3791 //
3792 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003793 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003794 SPIRVInstList.push_back(Inst);
3795
David Neto6dcd4712017-06-23 11:06:47 -04003796 // OpVariable instructions must come first.
3797 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003798 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3799 // Allocating a pointer requires variable pointers.
3800 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003801 setVariablePointersCapabilities(
3802 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003803 }
David Neto6dcd4712017-06-23 11:06:47 -04003804 GenerateInstruction(I);
3805 }
3806 }
3807
David Neto22f144c2017-06-12 14:26:21 -04003808 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003809 if (clspv::Option::HackInitializers()) {
3810 GenerateEntryPointInitialStores();
3811 }
David Neto22f144c2017-06-12 14:26:21 -04003812 }
3813
3814 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003815 if (!isa<AllocaInst>(I)) {
3816 GenerateInstruction(I);
3817 }
David Neto22f144c2017-06-12 14:26:21 -04003818 }
3819 }
3820}
3821
3822spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3823 const std::map<CmpInst::Predicate, spv::Op> Map = {
3824 {CmpInst::ICMP_EQ, spv::OpIEqual},
3825 {CmpInst::ICMP_NE, spv::OpINotEqual},
3826 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3827 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3828 {CmpInst::ICMP_ULT, spv::OpULessThan},
3829 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3830 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3831 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3832 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3833 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3834 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3835 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3836 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3837 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3838 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3839 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3840 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3841 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3842 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3843 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3844 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3845 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3846
3847 assert(0 != Map.count(I->getPredicate()));
3848
3849 return Map.at(I->getPredicate());
3850}
3851
3852spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3853 const std::map<unsigned, spv::Op> Map{
3854 {Instruction::Trunc, spv::OpUConvert},
3855 {Instruction::ZExt, spv::OpUConvert},
3856 {Instruction::SExt, spv::OpSConvert},
3857 {Instruction::FPToUI, spv::OpConvertFToU},
3858 {Instruction::FPToSI, spv::OpConvertFToS},
3859 {Instruction::UIToFP, spv::OpConvertUToF},
3860 {Instruction::SIToFP, spv::OpConvertSToF},
3861 {Instruction::FPTrunc, spv::OpFConvert},
3862 {Instruction::FPExt, spv::OpFConvert},
3863 {Instruction::BitCast, spv::OpBitcast}};
3864
3865 assert(0 != Map.count(I.getOpcode()));
3866
3867 return Map.at(I.getOpcode());
3868}
3869
3870spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003871 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003872 switch (I.getOpcode()) {
3873 default:
3874 break;
3875 case Instruction::Or:
3876 return spv::OpLogicalOr;
3877 case Instruction::And:
3878 return spv::OpLogicalAnd;
3879 case Instruction::Xor:
3880 return spv::OpLogicalNotEqual;
3881 }
3882 }
3883
alan-bakerb6b09dc2018-11-08 16:59:28 -05003884 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003885 {Instruction::Add, spv::OpIAdd},
3886 {Instruction::FAdd, spv::OpFAdd},
3887 {Instruction::Sub, spv::OpISub},
3888 {Instruction::FSub, spv::OpFSub},
3889 {Instruction::Mul, spv::OpIMul},
3890 {Instruction::FMul, spv::OpFMul},
3891 {Instruction::UDiv, spv::OpUDiv},
3892 {Instruction::SDiv, spv::OpSDiv},
3893 {Instruction::FDiv, spv::OpFDiv},
3894 {Instruction::URem, spv::OpUMod},
3895 {Instruction::SRem, spv::OpSRem},
3896 {Instruction::FRem, spv::OpFRem},
3897 {Instruction::Or, spv::OpBitwiseOr},
3898 {Instruction::Xor, spv::OpBitwiseXor},
3899 {Instruction::And, spv::OpBitwiseAnd},
3900 {Instruction::Shl, spv::OpShiftLeftLogical},
3901 {Instruction::LShr, spv::OpShiftRightLogical},
3902 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3903
3904 assert(0 != Map.count(I.getOpcode()));
3905
3906 return Map.at(I.getOpcode());
3907}
3908
3909void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
SJW69939d52020-04-16 07:29:07 -05003910 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003911 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003912 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3913 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3914
3915 // Register Instruction to ValueMap.
3916 if (0 == VMap[&I]) {
3917 VMap[&I] = nextID;
3918 }
3919
3920 switch (I.getOpcode()) {
3921 default: {
3922 if (Instruction::isCast(I.getOpcode())) {
3923 //
3924 // Generate SPIRV instructions for cast operators.
3925 //
3926
David Netod2de94a2017-08-28 17:27:47 -04003927 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003928 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003929 auto toI8 = Ty == Type::getInt8Ty(Context);
3930 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003931 // Handle zext, sext and uitofp with i1 type specially.
3932 if ((I.getOpcode() == Instruction::ZExt ||
3933 I.getOpcode() == Instruction::SExt ||
3934 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003935 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003936 //
3937 // Generate OpSelect.
3938 //
3939
3940 // Ops[0] = Result Type ID
3941 // Ops[1] = Condition ID
3942 // Ops[2] = True Constant ID
3943 // Ops[3] = False Constant ID
3944 SPIRVOperandList Ops;
3945
David Neto257c3892018-04-11 13:19:45 -04003946 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003947
David Neto22f144c2017-06-12 14:26:21 -04003948 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003949 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003950
3951 uint32_t TrueID = 0;
3952 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003953 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003954 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003955 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003956 } else {
3957 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3958 }
David Neto257c3892018-04-11 13:19:45 -04003959 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003960
3961 uint32_t FalseID = 0;
3962 if (I.getOpcode() == Instruction::ZExt) {
3963 FalseID = VMap[Constant::getNullValue(I.getType())];
3964 } else if (I.getOpcode() == Instruction::SExt) {
3965 FalseID = VMap[Constant::getNullValue(I.getType())];
3966 } else {
3967 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3968 }
David Neto257c3892018-04-11 13:19:45 -04003969 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003970
David Neto87846742018-04-11 17:36:22 -04003971 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003972 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003973 } else if (!clspv::Option::Int8Support() &&
3974 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003975 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3976 // 8 bits.
3977 // Before:
3978 // %result = trunc i32 %a to i8
3979 // After
3980 // %result = OpBitwiseAnd %uint %a %uint_255
3981
3982 SPIRVOperandList Ops;
3983
David Neto257c3892018-04-11 13:19:45 -04003984 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003985
3986 Type *UintTy = Type::getInt32Ty(Context);
3987 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003988 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003989
David Neto87846742018-04-11 17:36:22 -04003990 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003991 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003992 } else {
3993 // Ops[0] = Result Type ID
3994 // Ops[1] = Source Value ID
3995 SPIRVOperandList Ops;
3996
David Neto257c3892018-04-11 13:19:45 -04003997 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003998
David Neto87846742018-04-11 17:36:22 -04003999 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004000 SPIRVInstList.push_back(Inst);
4001 }
4002 } else if (isa<BinaryOperator>(I)) {
4003 //
4004 // Generate SPIRV instructions for binary operators.
4005 //
4006
4007 // Handle xor with i1 type specially.
4008 if (I.getOpcode() == Instruction::Xor &&
4009 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00004010 ((isa<ConstantInt>(I.getOperand(0)) &&
4011 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
4012 (isa<ConstantInt>(I.getOperand(1)) &&
4013 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04004014 //
4015 // Generate OpLogicalNot.
4016 //
4017 // Ops[0] = Result Type ID
4018 // Ops[1] = Operand
4019 SPIRVOperandList Ops;
4020
David Neto257c3892018-04-11 13:19:45 -04004021 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004022
4023 Value *CondV = I.getOperand(0);
4024 if (isa<Constant>(I.getOperand(0))) {
4025 CondV = I.getOperand(1);
4026 }
David Neto257c3892018-04-11 13:19:45 -04004027 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04004028
David Neto87846742018-04-11 17:36:22 -04004029 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004030 SPIRVInstList.push_back(Inst);
4031 } else {
4032 // Ops[0] = Result Type ID
4033 // Ops[1] = Operand 0
4034 // Ops[2] = Operand 1
4035 SPIRVOperandList Ops;
4036
David Neto257c3892018-04-11 13:19:45 -04004037 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4038 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004039
David Neto87846742018-04-11 17:36:22 -04004040 auto *Inst =
4041 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004042 SPIRVInstList.push_back(Inst);
4043 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004044 } else if (I.getOpcode() == Instruction::FNeg) {
4045 // The only unary operator.
4046 //
4047 // Ops[0] = Result Type ID
4048 // Ops[1] = Operand 0
4049 SPIRVOperandList ops;
4050
4051 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
4052 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
4053 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004054 } else {
4055 I.print(errs());
4056 llvm_unreachable("Unsupported instruction???");
4057 }
4058 break;
4059 }
4060 case Instruction::GetElementPtr: {
4061 auto &GlobalConstArgSet = getGlobalConstArgSet();
4062
4063 //
4064 // Generate OpAccessChain.
4065 //
4066 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4067
4068 //
4069 // Generate OpAccessChain.
4070 //
4071
4072 // Ops[0] = Result Type ID
4073 // Ops[1] = Base ID
4074 // Ops[2] ... Ops[n] = Indexes ID
4075 SPIRVOperandList Ops;
4076
alan-bakerb6b09dc2018-11-08 16:59:28 -05004077 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004078 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4079 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4080 // Use pointer type with private address space for global constant.
4081 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004082 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004083 }
David Neto257c3892018-04-11 13:19:45 -04004084
4085 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04004086
David Neto862b7d82018-06-14 18:48:37 -04004087 // Generate the base pointer.
4088 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004089
David Neto862b7d82018-06-14 18:48:37 -04004090 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004091
4092 //
4093 // Follows below rules for gep.
4094 //
David Neto862b7d82018-06-14 18:48:37 -04004095 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4096 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004097 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4098 // first index.
4099 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4100 // use gep's first index.
4101 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4102 // gep's first index.
4103 //
4104 spv::Op Opcode = spv::OpAccessChain;
4105 unsigned offset = 0;
4106 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004107 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004108 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004109 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004110 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004111 }
David Neto862b7d82018-06-14 18:48:37 -04004112 } else {
David Neto22f144c2017-06-12 14:26:21 -04004113 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004114 }
4115
4116 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004117 // Do we need to generate ArrayStride? Check against the GEP result type
4118 // rather than the pointer type of the base because when indexing into
4119 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4120 // for something else in the SPIR-V.
4121 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004122 auto address_space = ResultType->getAddressSpace();
4123 setVariablePointersCapabilities(address_space);
4124 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004125 case spv::StorageClassStorageBuffer:
4126 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004127 // Save the need to generate an ArrayStride decoration. But defer
4128 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004129 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004130 break;
4131 default:
4132 break;
David Neto1a1a0582017-07-07 12:01:44 -04004133 }
David Neto22f144c2017-06-12 14:26:21 -04004134 }
4135
4136 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04004137 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04004138 }
4139
David Neto87846742018-04-11 17:36:22 -04004140 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004141 SPIRVInstList.push_back(Inst);
4142 break;
4143 }
4144 case Instruction::ExtractValue: {
4145 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4146 // Ops[0] = Result Type ID
4147 // Ops[1] = Composite ID
4148 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4149 SPIRVOperandList Ops;
4150
David Neto257c3892018-04-11 13:19:45 -04004151 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004152
4153 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004154 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004155
4156 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004157 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004158 }
4159
David Neto87846742018-04-11 17:36:22 -04004160 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004161 SPIRVInstList.push_back(Inst);
4162 break;
4163 }
4164 case Instruction::InsertValue: {
4165 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4166 // Ops[0] = Result Type ID
4167 // Ops[1] = Object ID
4168 // Ops[2] = Composite ID
4169 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4170 SPIRVOperandList Ops;
4171
4172 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004173 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004174
4175 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004176 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004177
4178 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004179 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004180
4181 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004182 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004183 }
4184
David Neto87846742018-04-11 17:36:22 -04004185 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004186 SPIRVInstList.push_back(Inst);
4187 break;
4188 }
4189 case Instruction::Select: {
4190 //
4191 // Generate OpSelect.
4192 //
4193
4194 // Ops[0] = Result Type ID
4195 // Ops[1] = Condition ID
4196 // Ops[2] = True Constant ID
4197 // Ops[3] = False Constant ID
4198 SPIRVOperandList Ops;
4199
4200 // Find SPIRV instruction for parameter type.
4201 auto Ty = I.getType();
4202 if (Ty->isPointerTy()) {
4203 auto PointeeTy = Ty->getPointerElementType();
4204 if (PointeeTy->isStructTy() &&
4205 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4206 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004207 } else {
4208 // Selecting between pointers requires variable pointers.
4209 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4210 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4211 setVariablePointers(true);
4212 }
David Neto22f144c2017-06-12 14:26:21 -04004213 }
4214 }
4215
David Neto257c3892018-04-11 13:19:45 -04004216 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4217 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004218
David Neto87846742018-04-11 17:36:22 -04004219 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004220 SPIRVInstList.push_back(Inst);
4221 break;
4222 }
4223 case Instruction::ExtractElement: {
4224 // Handle <4 x i8> type manually.
4225 Type *CompositeTy = I.getOperand(0)->getType();
4226 if (is4xi8vec(CompositeTy)) {
4227 //
4228 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4229 // <4 x i8>.
4230 //
4231
4232 //
4233 // Generate OpShiftRightLogical
4234 //
4235 // Ops[0] = Result Type ID
4236 // Ops[1] = Operand 0
4237 // Ops[2] = Operand 1
4238 //
4239 SPIRVOperandList Ops;
4240
David Neto257c3892018-04-11 13:19:45 -04004241 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004242
4243 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004244 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004245
4246 uint32_t Op1ID = 0;
4247 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4248 // Handle constant index.
4249 uint64_t Idx = CI->getZExtValue();
4250 Value *ShiftAmount =
4251 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4252 Op1ID = VMap[ShiftAmount];
4253 } else {
4254 // Handle variable index.
4255 SPIRVOperandList TmpOps;
4256
David Neto257c3892018-04-11 13:19:45 -04004257 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4258 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004259
4260 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004261 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004262
4263 Op1ID = nextID;
4264
David Neto87846742018-04-11 17:36:22 -04004265 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004266 SPIRVInstList.push_back(TmpInst);
4267 }
David Neto257c3892018-04-11 13:19:45 -04004268 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004269
4270 uint32_t ShiftID = nextID;
4271
David Neto87846742018-04-11 17:36:22 -04004272 auto *Inst =
4273 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004274 SPIRVInstList.push_back(Inst);
4275
4276 //
4277 // Generate OpBitwiseAnd
4278 //
4279 // Ops[0] = Result Type ID
4280 // Ops[1] = Operand 0
4281 // Ops[2] = Operand 1
4282 //
4283 Ops.clear();
4284
David Neto257c3892018-04-11 13:19:45 -04004285 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004286
4287 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004288 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004289
David Neto9b2d6252017-09-06 15:47:37 -04004290 // Reset mapping for this value to the result of the bitwise and.
4291 VMap[&I] = nextID;
4292
David Neto87846742018-04-11 17:36:22 -04004293 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004294 SPIRVInstList.push_back(Inst);
4295 break;
4296 }
4297
4298 // Ops[0] = Result Type ID
4299 // Ops[1] = Composite ID
4300 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4301 SPIRVOperandList Ops;
4302
David Neto257c3892018-04-11 13:19:45 -04004303 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004304
4305 spv::Op Opcode = spv::OpCompositeExtract;
4306 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004307 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004308 } else {
David Neto257c3892018-04-11 13:19:45 -04004309 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004310 Opcode = spv::OpVectorExtractDynamic;
4311 }
4312
David Neto87846742018-04-11 17:36:22 -04004313 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004314 SPIRVInstList.push_back(Inst);
4315 break;
4316 }
4317 case Instruction::InsertElement: {
4318 // Handle <4 x i8> type manually.
4319 Type *CompositeTy = I.getOperand(0)->getType();
4320 if (is4xi8vec(CompositeTy)) {
4321 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4322 uint32_t CstFFID = VMap[CstFF];
4323
4324 uint32_t ShiftAmountID = 0;
4325 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4326 // Handle constant index.
4327 uint64_t Idx = CI->getZExtValue();
4328 Value *ShiftAmount =
4329 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4330 ShiftAmountID = VMap[ShiftAmount];
4331 } else {
4332 // Handle variable index.
4333 SPIRVOperandList TmpOps;
4334
David Neto257c3892018-04-11 13:19:45 -04004335 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4336 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004337
4338 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004339 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004340
4341 ShiftAmountID = nextID;
4342
David Neto87846742018-04-11 17:36:22 -04004343 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004344 SPIRVInstList.push_back(TmpInst);
4345 }
4346
4347 //
4348 // Generate mask operations.
4349 //
4350
4351 // ShiftLeft mask according to index of insertelement.
4352 SPIRVOperandList Ops;
4353
David Neto257c3892018-04-11 13:19:45 -04004354 const uint32_t ResTyID = lookupType(CompositeTy);
4355 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004356
4357 uint32_t MaskID = nextID;
4358
David Neto87846742018-04-11 17:36:22 -04004359 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004360 SPIRVInstList.push_back(Inst);
4361
4362 // Inverse mask.
4363 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004365
4366 uint32_t InvMaskID = nextID;
4367
David Neto87846742018-04-11 17:36:22 -04004368 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004369 SPIRVInstList.push_back(Inst);
4370
4371 // Apply mask.
4372 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004373 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004374
4375 uint32_t OrgValID = nextID;
4376
David Neto87846742018-04-11 17:36:22 -04004377 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004378 SPIRVInstList.push_back(Inst);
4379
4380 // Create correct value according to index of insertelement.
4381 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004382 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4383 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004384
4385 uint32_t InsertValID = nextID;
4386
David Neto87846742018-04-11 17:36:22 -04004387 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004388 SPIRVInstList.push_back(Inst);
4389
4390 // Insert value to original value.
4391 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004392 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004393
David Netoa394f392017-08-26 20:45:29 -04004394 VMap[&I] = nextID;
4395
David Neto87846742018-04-11 17:36:22 -04004396 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004397 SPIRVInstList.push_back(Inst);
4398
4399 break;
4400 }
4401
David Neto22f144c2017-06-12 14:26:21 -04004402 SPIRVOperandList Ops;
4403
James Priced26efea2018-06-09 23:28:32 +01004404 // Ops[0] = Result Type ID
4405 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004406
4407 spv::Op Opcode = spv::OpCompositeInsert;
4408 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004409 const auto value = CI->getZExtValue();
4410 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004411 // Ops[1] = Object ID
4412 // Ops[2] = Composite ID
4413 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004414 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004415 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004416 } else {
James Priced26efea2018-06-09 23:28:32 +01004417 // Ops[1] = Composite ID
4418 // Ops[2] = Object ID
4419 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004420 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004421 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004422 Opcode = spv::OpVectorInsertDynamic;
4423 }
4424
David Neto87846742018-04-11 17:36:22 -04004425 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004426 SPIRVInstList.push_back(Inst);
4427 break;
4428 }
4429 case Instruction::ShuffleVector: {
4430 // Ops[0] = Result Type ID
4431 // Ops[1] = Vector 1 ID
4432 // Ops[2] = Vector 2 ID
4433 // Ops[3] ... Ops[n] = Components (Literal Number)
4434 SPIRVOperandList Ops;
4435
David Neto257c3892018-04-11 13:19:45 -04004436 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4437 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004438
alan-bakerc9666712020-04-01 16:31:21 -04004439 auto shuffle = cast<ShuffleVectorInst>(&I);
4440 SmallVector<int, 4> mask;
4441 shuffle->getShuffleMask(mask);
4442 for (auto i : mask) {
4443 if (i == UndefMaskElem) {
4444 if (clspv::Option::HackUndef())
4445 // Use 0 instead of undef.
David Neto257c3892018-04-11 13:19:45 -04004446 Ops << MkNum(0);
alan-bakerc9666712020-04-01 16:31:21 -04004447 else
4448 // Undef for shuffle in SPIR-V.
4449 Ops << MkNum(0xffffffff);
David Neto22f144c2017-06-12 14:26:21 -04004450 } else {
alan-bakerc9666712020-04-01 16:31:21 -04004451 Ops << MkNum(i);
David Neto22f144c2017-06-12 14:26:21 -04004452 }
4453 }
4454
David Neto87846742018-04-11 17:36:22 -04004455 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004456 SPIRVInstList.push_back(Inst);
4457 break;
4458 }
4459 case Instruction::ICmp:
4460 case Instruction::FCmp: {
4461 CmpInst *CmpI = cast<CmpInst>(&I);
4462
David Netod4ca2e62017-07-06 18:47:35 -04004463 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004464 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004465 if (isa<PointerType>(ArgTy)) {
4466 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004467 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004468 errs()
4469 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4470 << "in function " << name << "\n";
4471 llvm_unreachable("Pointer equality check is invalid");
4472 break;
4473 }
4474
David Neto257c3892018-04-11 13:19:45 -04004475 // Ops[0] = Result Type ID
4476 // Ops[1] = Operand 1 ID
4477 // Ops[2] = Operand 2 ID
4478 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004479
David Neto257c3892018-04-11 13:19:45 -04004480 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4481 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004482
4483 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004484 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004485 SPIRVInstList.push_back(Inst);
4486 break;
4487 }
4488 case Instruction::Br: {
4489 // Branch instrucion is deferred because it needs label's ID. Record slot's
4490 // location on SPIRVInstructionList.
4491 DeferredInsts.push_back(
4492 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4493 break;
4494 }
4495 case Instruction::Switch: {
4496 I.print(errs());
4497 llvm_unreachable("Unsupported instruction???");
4498 break;
4499 }
4500 case Instruction::IndirectBr: {
4501 I.print(errs());
4502 llvm_unreachable("Unsupported instruction???");
4503 break;
4504 }
4505 case Instruction::PHI: {
4506 // Branch instrucion is deferred because it needs label's ID. Record slot's
4507 // location on SPIRVInstructionList.
4508 DeferredInsts.push_back(
4509 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4510 break;
4511 }
4512 case Instruction::Alloca: {
4513 //
4514 // Generate OpVariable.
4515 //
4516 // Ops[0] : Result Type ID
4517 // Ops[1] : Storage Class
4518 SPIRVOperandList Ops;
4519
David Neto257c3892018-04-11 13:19:45 -04004520 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004521
David Neto87846742018-04-11 17:36:22 -04004522 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004523 SPIRVInstList.push_back(Inst);
4524 break;
4525 }
4526 case Instruction::Load: {
4527 LoadInst *LD = cast<LoadInst>(&I);
4528 //
4529 // Generate OpLoad.
4530 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004531
alan-baker5b86ed72019-02-15 08:26:50 -05004532 if (LD->getType()->isPointerTy()) {
4533 // Loading a pointer requires variable pointers.
4534 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4535 }
David Neto22f144c2017-06-12 14:26:21 -04004536
David Neto0a2f98d2017-09-15 19:38:40 -04004537 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004538 uint32_t PointerID = VMap[LD->getPointerOperand()];
4539
4540 // This is a hack to work around what looks like a driver bug.
4541 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004542 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4543 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004544 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004545 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004546 // Generate a bitwise-and of the original value with itself.
4547 // We should have been able to get away with just an OpCopyObject,
4548 // but we need something more complex to get past certain driver bugs.
4549 // This is ridiculous, but necessary.
4550 // TODO(dneto): Revisit this once drivers fix their bugs.
4551
4552 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004553 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4554 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004555
David Neto87846742018-04-11 17:36:22 -04004556 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004557 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004558 break;
4559 }
4560
4561 // This is the normal path. Generate a load.
4562
David Neto22f144c2017-06-12 14:26:21 -04004563 // Ops[0] = Result Type ID
4564 // Ops[1] = Pointer ID
4565 // Ops[2] ... Ops[n] = Optional Memory Access
4566 //
4567 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004568
David Neto22f144c2017-06-12 14:26:21 -04004569 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004570 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004571
David Neto87846742018-04-11 17:36:22 -04004572 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004573 SPIRVInstList.push_back(Inst);
4574 break;
4575 }
4576 case Instruction::Store: {
4577 StoreInst *ST = cast<StoreInst>(&I);
4578 //
4579 // Generate OpStore.
4580 //
4581
alan-baker5b86ed72019-02-15 08:26:50 -05004582 if (ST->getValueOperand()->getType()->isPointerTy()) {
4583 // Storing a pointer requires variable pointers.
4584 setVariablePointersCapabilities(
4585 ST->getValueOperand()->getType()->getPointerAddressSpace());
4586 }
4587
David Neto22f144c2017-06-12 14:26:21 -04004588 // Ops[0] = Pointer ID
4589 // Ops[1] = Object ID
4590 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4591 //
4592 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004593 SPIRVOperandList Ops;
4594 Ops << MkId(VMap[ST->getPointerOperand()])
4595 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004596
David Neto87846742018-04-11 17:36:22 -04004597 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004598 SPIRVInstList.push_back(Inst);
4599 break;
4600 }
4601 case Instruction::AtomicCmpXchg: {
4602 I.print(errs());
4603 llvm_unreachable("Unsupported instruction???");
4604 break;
4605 }
4606 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004607 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4608
4609 spv::Op opcode;
4610
4611 switch (AtomicRMW->getOperation()) {
4612 default:
4613 I.print(errs());
4614 llvm_unreachable("Unsupported instruction???");
4615 case llvm::AtomicRMWInst::Add:
4616 opcode = spv::OpAtomicIAdd;
4617 break;
4618 case llvm::AtomicRMWInst::Sub:
4619 opcode = spv::OpAtomicISub;
4620 break;
4621 case llvm::AtomicRMWInst::Xchg:
4622 opcode = spv::OpAtomicExchange;
4623 break;
4624 case llvm::AtomicRMWInst::Min:
4625 opcode = spv::OpAtomicSMin;
4626 break;
4627 case llvm::AtomicRMWInst::Max:
4628 opcode = spv::OpAtomicSMax;
4629 break;
4630 case llvm::AtomicRMWInst::UMin:
4631 opcode = spv::OpAtomicUMin;
4632 break;
4633 case llvm::AtomicRMWInst::UMax:
4634 opcode = spv::OpAtomicUMax;
4635 break;
4636 case llvm::AtomicRMWInst::And:
4637 opcode = spv::OpAtomicAnd;
4638 break;
4639 case llvm::AtomicRMWInst::Or:
4640 opcode = spv::OpAtomicOr;
4641 break;
4642 case llvm::AtomicRMWInst::Xor:
4643 opcode = spv::OpAtomicXor;
4644 break;
4645 }
4646
4647 //
4648 // Generate OpAtomic*.
4649 //
4650 SPIRVOperandList Ops;
4651
David Neto257c3892018-04-11 13:19:45 -04004652 Ops << MkId(lookupType(I.getType()))
4653 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004654
4655 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004656 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004657 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004658
4659 const auto ConstantMemorySemantics = ConstantInt::get(
4660 IntTy, spv::MemorySemanticsUniformMemoryMask |
4661 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004662 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004663
David Neto257c3892018-04-11 13:19:45 -04004664 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004665
4666 VMap[&I] = nextID;
4667
David Neto87846742018-04-11 17:36:22 -04004668 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004669 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004670 break;
4671 }
4672 case Instruction::Fence: {
4673 I.print(errs());
4674 llvm_unreachable("Unsupported instruction???");
4675 break;
4676 }
4677 case Instruction::Call: {
4678 CallInst *Call = dyn_cast<CallInst>(&I);
4679 Function *Callee = Call->getCalledFunction();
4680
Alan Baker202c8c72018-08-13 13:47:44 -04004681 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004682 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4683 // Generate an OpLoad
4684 SPIRVOperandList Ops;
4685 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004686
David Neto862b7d82018-06-14 18:48:37 -04004687 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4688 << MkId(ResourceVarDeferredLoadCalls[Call]);
4689
4690 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4691 SPIRVInstList.push_back(Inst);
4692 VMap[Call] = load_id;
4693 break;
4694
4695 } else {
4696 // This maps to an OpVariable we've already generated.
4697 // No code is generated for the call.
4698 }
4699 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004700 } else if (Callee->getName().startswith(
4701 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004702 // Don't codegen an instruction here, but instead map this call directly
4703 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004704 int spec_id = static_cast<int>(
4705 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004706 const auto &info = LocalSpecIdInfoMap[spec_id];
4707 VMap[Call] = info.variable_id;
4708 break;
David Neto862b7d82018-06-14 18:48:37 -04004709 }
4710
4711 // Sampler initializers become a load of the corresponding sampler.
4712
Kévin Petitdf71de32019-04-09 14:09:50 +01004713 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004714 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004715 const auto third_param = static_cast<unsigned>(
4716 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4717 auto sampler_value = third_param;
4718 if (clspv::Option::UseSamplerMap()) {
4719 sampler_value = getSamplerMap()[third_param].first;
4720 }
David Neto862b7d82018-06-14 18:48:37 -04004721
4722 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004723 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004724 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004725
David Neto257c3892018-04-11 13:19:45 -04004726 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004727 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004728
David Neto862b7d82018-06-14 18:48:37 -04004729 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004730 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004731 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004732 break;
4733 }
4734
Kévin Petit349c9502019-03-28 17:24:14 +00004735 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004736 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4737 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4738 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004739
Kévin Petit617a76d2019-04-04 13:54:16 +01004740 // If the switch above didn't have an entry maybe the intrinsic
4741 // is using the name mangling logic.
4742 bool usesMangler = false;
4743 if (opcode == spv::OpNop) {
4744 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4745 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4746 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4747 usesMangler = true;
4748 }
4749 }
4750
Kévin Petit349c9502019-03-28 17:24:14 +00004751 if (opcode != spv::OpNop) {
4752
David Neto22f144c2017-06-12 14:26:21 -04004753 SPIRVOperandList Ops;
4754
Kévin Petit349c9502019-03-28 17:24:14 +00004755 if (!I.getType()->isVoidTy()) {
4756 Ops << MkId(lookupType(I.getType()));
4757 }
David Neto22f144c2017-06-12 14:26:21 -04004758
Kévin Petit617a76d2019-04-04 13:54:16 +01004759 unsigned firstOperand = usesMangler ? 1 : 0;
4760 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004761 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004762 }
4763
Kévin Petit349c9502019-03-28 17:24:14 +00004764 if (!I.getType()->isVoidTy()) {
4765 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004766 }
4767
Kévin Petit349c9502019-03-28 17:24:14 +00004768 SPIRVInstruction *Inst;
4769 if (!I.getType()->isVoidTy()) {
4770 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4771 } else {
4772 Inst = new SPIRVInstruction(opcode, Ops);
4773 }
Kévin Petit8a560882019-03-21 15:24:34 +00004774 SPIRVInstList.push_back(Inst);
4775 break;
4776 }
4777
David Neto22f144c2017-06-12 14:26:21 -04004778 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4779 if (Callee->getName().startswith("spirv.copy_memory")) {
4780 //
4781 // Generate OpCopyMemory.
4782 //
4783
4784 // Ops[0] = Dst ID
4785 // Ops[1] = Src ID
4786 // Ops[2] = Memory Access
4787 // Ops[3] = Alignment
4788
4789 auto IsVolatile =
4790 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4791
4792 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4793 : spv::MemoryAccessMaskNone;
4794
4795 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4796
4797 auto Alignment =
4798 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4799
David Neto257c3892018-04-11 13:19:45 -04004800 SPIRVOperandList Ops;
4801 Ops << MkId(VMap[Call->getArgOperand(0)])
4802 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4803 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004804
David Neto87846742018-04-11 17:36:22 -04004805 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004806
4807 SPIRVInstList.push_back(Inst);
4808
4809 break;
4810 }
4811
SJW2c317da2020-03-23 07:39:13 -05004812 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4813 // Additionally, OpTypeSampledImage is generated.
SJW173c7e92020-03-16 08:44:47 -05004814 if (IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004815 //
4816 // Generate OpSampledImage.
4817 //
4818 // Ops[0] = Result Type ID
4819 // Ops[1] = Image ID
4820 // Ops[2] = Sampler ID
4821 //
4822 SPIRVOperandList Ops;
4823
4824 Value *Image = Call->getArgOperand(0);
4825 Value *Sampler = Call->getArgOperand(1);
4826 Value *Coordinate = Call->getArgOperand(2);
4827
4828 TypeMapType &OpImageTypeMap = getImageTypeMap();
4829 Type *ImageTy = Image->getType()->getPointerElementType();
4830 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004831 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004832 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004833
4834 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004835
4836 uint32_t SampledImageID = nextID;
4837
David Neto87846742018-04-11 17:36:22 -04004838 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004839 SPIRVInstList.push_back(Inst);
4840
4841 //
4842 // Generate OpImageSampleExplicitLod.
4843 //
4844 // Ops[0] = Result Type ID
4845 // Ops[1] = Sampled Image ID
4846 // Ops[2] = Coordinate ID
4847 // Ops[3] = Image Operands Type ID
4848 // Ops[4] ... Ops[n] = Operands ID
4849 //
4850 Ops.clear();
4851
alan-bakerf67468c2019-11-25 15:51:49 -05004852 const bool is_int_image = IsIntImageType(Image->getType());
4853 uint32_t result_type = 0;
4854 if (is_int_image) {
4855 result_type = v4int32ID;
4856 } else {
4857 result_type = lookupType(Call->getType());
4858 }
4859
4860 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
4861 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004862
4863 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004864 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004865
alan-bakerf67468c2019-11-25 15:51:49 -05004866 uint32_t final_id = nextID++;
4867 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04004868
alan-bakerf67468c2019-11-25 15:51:49 -05004869 uint32_t image_id = final_id;
4870 if (is_int_image) {
4871 // Int image requires a bitcast from v4int to v4uint.
4872 image_id = nextID++;
4873 }
4874
4875 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004876 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05004877
4878 if (is_int_image) {
4879 // Generate the bitcast.
4880 Ops.clear();
4881 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4882 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4883 SPIRVInstList.push_back(Inst);
4884 }
David Neto22f144c2017-06-12 14:26:21 -04004885 break;
4886 }
4887
alan-baker75090e42020-02-20 11:21:04 -05004888 // read_image (without a sampler) is mapped to OpImageFetch.
SJW173c7e92020-03-16 08:44:47 -05004889 if (IsUnsampledImageRead(Callee)) {
alan-baker75090e42020-02-20 11:21:04 -05004890 Value *Image = Call->getArgOperand(0);
4891 Value *Coordinate = Call->getArgOperand(1);
4892
4893 //
4894 // Generate OpImageFetch
4895 //
4896 // Ops[0] = Result Type ID
4897 // Ops[1] = Image ID
4898 // Ops[2] = Coordinate ID
4899 // Ops[3] = Lod
4900 // Ops[4] = 0
4901 //
4902 SPIRVOperandList Ops;
4903
4904 const bool is_int_image = IsIntImageType(Image->getType());
4905 uint32_t result_type = 0;
4906 if (is_int_image) {
4907 result_type = v4int32ID;
4908 } else {
4909 result_type = lookupType(Call->getType());
4910 }
4911
4912 Ops << MkId(result_type) << MkId(VMap[Image]) << MkId(VMap[Coordinate])
4913 << MkNum(spv::ImageOperandsLodMask);
4914
4915 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4916 Ops << MkId(VMap[CstInt0]);
4917
4918 uint32_t final_id = nextID++;
4919 VMap[&I] = final_id;
4920
4921 uint32_t image_id = final_id;
4922 if (is_int_image) {
4923 // Int image requires a bitcast from v4int to v4uint.
4924 image_id = nextID++;
4925 }
4926
4927 auto *Inst = new SPIRVInstruction(spv::OpImageFetch, image_id, Ops);
4928 SPIRVInstList.push_back(Inst);
4929
4930 if (is_int_image) {
4931 // Generate the bitcast.
4932 Ops.clear();
4933 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4934 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4935 SPIRVInstList.push_back(Inst);
4936 }
4937 break;
4938 }
4939
alan-bakerf67468c2019-11-25 15:51:49 -05004940 // write_image is mapped to OpImageWrite.
SJW173c7e92020-03-16 08:44:47 -05004941 if (IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004942 //
4943 // Generate OpImageWrite.
4944 //
4945 // Ops[0] = Image ID
4946 // Ops[1] = Coordinate ID
4947 // Ops[2] = Texel ID
4948 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4949 // Ops[4] ... Ops[n] = (Optional) Operands ID
4950 //
4951 SPIRVOperandList Ops;
4952
4953 Value *Image = Call->getArgOperand(0);
4954 Value *Coordinate = Call->getArgOperand(1);
4955 Value *Texel = Call->getArgOperand(2);
4956
4957 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004958 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004959 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05004960
4961 const bool is_int_image = IsIntImageType(Image->getType());
4962 if (is_int_image) {
4963 // Generate a bitcast to v4int and use it as the texel value.
4964 uint32_t castID = nextID++;
4965 Ops << MkId(v4int32ID) << MkId(TexelID);
4966 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
4967 SPIRVInstList.push_back(cast);
4968 Ops.clear();
4969 TexelID = castID;
4970 }
David Neto257c3892018-04-11 13:19:45 -04004971 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004972
David Neto87846742018-04-11 17:36:22 -04004973 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004974 SPIRVInstList.push_back(Inst);
4975 break;
4976 }
4977
alan-bakerce179f12019-12-06 19:02:22 -05004978 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
SJW173c7e92020-03-16 08:44:47 -05004979 if (IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04004980 //
alan-bakerce179f12019-12-06 19:02:22 -05004981 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04004982 //
4983 // Ops[0] = Image ID
4984 //
alan-bakerce179f12019-12-06 19:02:22 -05004985 // Result type has components equal to the dimensionality of the image,
4986 // plus 1 if the image is arrayed.
4987 //
alan-bakerf906d2b2019-12-10 11:26:23 -05004988 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04004989 SPIRVOperandList Ops;
4990
4991 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05004992 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
4993 uint32_t SizesTypeID = 0;
4994
David Neto5c22a252018-03-15 16:07:41 -04004995 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05004996 const uint32_t dim = ImageDimensionality(Image->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05004997 const uint32_t components =
4998 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -05004999 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05005000 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
5001 } else {
alan-baker7150a1d2020-02-25 08:31:06 -05005002 SizesTypeID =
5003 TypeMap[VectorType::get(Type::getInt32Ty(Context), components)];
alan-bakerce179f12019-12-06 19:02:22 -05005004 }
David Neto5c22a252018-03-15 16:07:41 -04005005 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04005006 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05005007 spv::Op query_opcode = spv::OpImageQuerySize;
SJW173c7e92020-03-16 08:44:47 -05005008 if (IsSampledImageType(Image->getType())) {
alan-bakerce179f12019-12-06 19:02:22 -05005009 query_opcode = spv::OpImageQuerySizeLod;
5010 // Need explicit 0 for Lod operand.
5011 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5012 Ops << MkId(VMap[CstInt0]);
5013 }
David Neto5c22a252018-03-15 16:07:41 -04005014
5015 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05005016 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04005017 SPIRVInstList.push_back(QueryInst);
5018
alan-bakerce179f12019-12-06 19:02:22 -05005019 // May require an extra instruction to create the appropriate result of
5020 // the builtin function.
SJW173c7e92020-03-16 08:44:47 -05005021 if (IsGetImageDim(Callee)) {
alan-bakerce179f12019-12-06 19:02:22 -05005022 if (dim == 3) {
5023 // get_image_dim returns an int4 for 3D images.
5024 //
5025 // Reset value map entry since we generated an intermediate
5026 // instruction.
5027 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04005028
alan-bakerce179f12019-12-06 19:02:22 -05005029 // Implement:
5030 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
5031 Ops.clear();
5032 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
5033 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04005034
alan-bakerce179f12019-12-06 19:02:22 -05005035 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5036 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04005037
alan-bakerce179f12019-12-06 19:02:22 -05005038 auto *Inst =
5039 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
5040 SPIRVInstList.push_back(Inst);
5041 } else if (dim != components) {
5042 // get_image_dim return an int2 regardless of the arrayedness of the
5043 // image. If the image is arrayed an element must be dropped from the
5044 // query result.
5045 //
5046 // Reset value map entry since we generated an intermediate
5047 // instruction.
5048 VMap[&I] = nextID;
5049
5050 // Implement:
5051 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
5052 Ops.clear();
5053 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
5054 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
5055
5056 auto *Inst =
5057 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
5058 SPIRVInstList.push_back(Inst);
5059 }
5060 } else if (components > 1) {
5061 // Reset value map entry since we generated an intermediate instruction.
5062 VMap[&I] = nextID;
5063
5064 // Implement:
5065 // %result = OpCompositeExtract %uint %sizes <component number>
5066 Ops.clear();
5067 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
5068
5069 uint32_t component = 0;
5070 if (IsGetImageHeight(Callee))
5071 component = 1;
5072 else if (IsGetImageDepth(Callee))
5073 component = 2;
5074 Ops << MkNum(component);
5075
5076 auto *Inst =
5077 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
5078 SPIRVInstList.push_back(Inst);
5079 }
David Neto5c22a252018-03-15 16:07:41 -04005080 break;
5081 }
5082
David Neto22f144c2017-06-12 14:26:21 -04005083 // Call instrucion is deferred because it needs function's ID. Record
5084 // slot's location on SPIRVInstructionList.
5085 DeferredInsts.push_back(
5086 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5087
David Neto3fbb4072017-10-16 11:28:14 -04005088 // Check whether the implementation of this call uses an extended
5089 // instruction plus one more value-producing instruction. If so, then
5090 // reserve the id for the extra value-producing slot.
5091 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5092 if (EInst != kGlslExtInstBad) {
5093 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005094 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005095 VMap[&I] = nextID;
5096 nextID++;
5097 }
5098 break;
5099 }
5100 case Instruction::Ret: {
5101 unsigned NumOps = I.getNumOperands();
5102 if (NumOps == 0) {
5103 //
5104 // Generate OpReturn.
5105 //
David Netoef5ba2b2019-12-20 08:35:54 -05005106 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04005107 } else {
5108 //
5109 // Generate OpReturnValue.
5110 //
5111
5112 // Ops[0] = Return Value ID
5113 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04005114
5115 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005116
David Neto87846742018-04-11 17:36:22 -04005117 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005118 SPIRVInstList.push_back(Inst);
5119 break;
5120 }
5121 break;
5122 }
5123 }
5124}
5125
5126void SPIRVProducerPass::GenerateFuncEpilogue() {
SJW69939d52020-04-16 07:29:07 -05005127 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005128
5129 //
5130 // Generate OpFunctionEnd
5131 //
5132
David Netoef5ba2b2019-12-20 08:35:54 -05005133 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04005134 SPIRVInstList.push_back(Inst);
5135}
5136
5137bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05005138 // Don't specialize <4 x i8> if i8 is generally supported.
5139 if (clspv::Option::Int8Support())
5140 return false;
5141
David Neto22f144c2017-06-12 14:26:21 -04005142 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04005143 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
5144 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
5145 VecTy->getNumElements() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04005146 return true;
5147 }
5148 }
5149
5150 return false;
5151}
5152
5153void SPIRVProducerPass::HandleDeferredInstruction() {
SJW69939d52020-04-16 07:29:07 -05005154 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005155 ValueMapType &VMap = getValueMap();
5156 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5157
5158 for (auto DeferredInst = DeferredInsts.rbegin();
5159 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5160 Value *Inst = std::get<0>(*DeferredInst);
5161 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5162 if (InsertPoint != SPIRVInstList.end()) {
5163 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5164 ++InsertPoint;
5165 }
5166 }
5167
5168 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05005169 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04005170 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05005171 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04005172 //
5173 // Generate OpLoopMerge.
5174 //
5175 // Ops[0] = Merge Block ID
5176 // Ops[1] = Continue Target ID
5177 // Ops[2] = Selection Control
5178 SPIRVOperandList Ops;
5179
alan-baker06cad652019-12-03 17:56:47 -05005180 auto MergeBB = MergeBlocks[BrBB];
5181 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04005182 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005183 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005184 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05005185 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005186
David Neto87846742018-04-11 17:36:22 -04005187 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005188 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005189 } else if (MergeBlocks.count(BrBB)) {
5190 //
5191 // Generate OpSelectionMerge.
5192 //
5193 // Ops[0] = Merge Block ID
5194 // Ops[1] = Selection Control
5195 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005196
alan-baker06cad652019-12-03 17:56:47 -05005197 auto MergeBB = MergeBlocks[BrBB];
5198 uint32_t MergeBBID = VMap[MergeBB];
5199 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005200
alan-baker06cad652019-12-03 17:56:47 -05005201 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5202 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005203 }
5204
5205 if (Br->isConditional()) {
5206 //
5207 // Generate OpBranchConditional.
5208 //
5209 // Ops[0] = Condition ID
5210 // Ops[1] = True Label ID
5211 // Ops[2] = False Label ID
5212 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5213 SPIRVOperandList Ops;
5214
5215 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005216 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005217 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005218
5219 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005220
David Neto87846742018-04-11 17:36:22 -04005221 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005222 SPIRVInstList.insert(InsertPoint, BrInst);
5223 } else {
5224 //
5225 // Generate OpBranch.
5226 //
5227 // Ops[0] = Target Label ID
5228 SPIRVOperandList Ops;
5229
5230 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005231 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005232
David Neto87846742018-04-11 17:36:22 -04005233 SPIRVInstList.insert(InsertPoint,
5234 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005235 }
5236 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04005237 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
5238 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05005239 // OpPhi on pointers requires variable pointers.
5240 setVariablePointersCapabilities(
5241 PHI->getType()->getPointerAddressSpace());
5242 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5243 setVariablePointers(true);
5244 }
5245 }
5246
David Neto22f144c2017-06-12 14:26:21 -04005247 //
5248 // Generate OpPhi.
5249 //
5250 // Ops[0] = Result Type ID
5251 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5252 SPIRVOperandList Ops;
5253
David Neto257c3892018-04-11 13:19:45 -04005254 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005255
David Neto22f144c2017-06-12 14:26:21 -04005256 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5257 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005258 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005259 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005260 }
5261
5262 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005263 InsertPoint,
5264 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005265 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5266 Function *Callee = Call->getCalledFunction();
SJW2c317da2020-03-23 07:39:13 -05005267 LLVMContext &Context = Callee->getContext();
5268 auto IntTy = Type::getInt32Ty(Context);
5269 auto callee_code = Builtins::Lookup(Callee);
David Neto3fbb4072017-10-16 11:28:14 -04005270 auto callee_name = Callee->getName();
5271 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005272
5273 if (EInst) {
5274 uint32_t &ExtInstImportID = getOpExtInstImportID();
5275
5276 //
5277 // Generate OpExtInst.
5278 //
5279
5280 // Ops[0] = Result Type ID
5281 // Ops[1] = Set ID (OpExtInstImport ID)
5282 // Ops[2] = Instruction Number (Literal Number)
5283 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5284 SPIRVOperandList Ops;
5285
David Neto862b7d82018-06-14 18:48:37 -04005286 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5287 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005288
David Neto22f144c2017-06-12 14:26:21 -04005289 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5290 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005291 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005292 }
5293
David Neto87846742018-04-11 17:36:22 -04005294 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5295 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005296 SPIRVInstList.insert(InsertPoint, ExtInst);
5297
David Neto3fbb4072017-10-16 11:28:14 -04005298 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5299 if (IndirectExtInst != kGlslExtInstBad) {
5300 // Generate one more instruction that uses the result of the extended
5301 // instruction. Its result id is one more than the id of the
5302 // extended instruction.
David Neto3fbb4072017-10-16 11:28:14 -04005303 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5304 &VMap, &SPIRVInstList, &InsertPoint](
5305 spv::Op opcode, Constant *constant) {
5306 //
5307 // Generate instruction like:
5308 // result = opcode constant <extinst-result>
5309 //
5310 // Ops[0] = Result Type ID
5311 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5312 // Ops[2] = Operand 1 ;; the result of the extended instruction
5313 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005314
David Neto3fbb4072017-10-16 11:28:14 -04005315 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005316 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005317
5318 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5319 constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04005320 {static_cast<unsigned>(vectorTy->getNumElements()), false},
5321 constant);
David Neto3fbb4072017-10-16 11:28:14 -04005322 }
David Neto257c3892018-04-11 13:19:45 -04005323 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005324
5325 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005326 InsertPoint, new SPIRVInstruction(
5327 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005328 };
5329
5330 switch (IndirectExtInst) {
5331 case glsl::ExtInstFindUMsb: // Implementing clz
SJW2c317da2020-03-23 07:39:13 -05005332 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
David Neto3fbb4072017-10-16 11:28:14 -04005333 break;
5334 case glsl::ExtInstAcos: // Implementing acospi
5335 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005336 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005337 case glsl::ExtInstAtan2: // Implementing atan2pi
5338 generate_extra_inst(
5339 spv::OpFMul,
5340 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5341 break;
5342
5343 default:
5344 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005345 }
David Neto22f144c2017-06-12 14:26:21 -04005346 }
David Neto3fbb4072017-10-16 11:28:14 -04005347
SJW2c317da2020-03-23 07:39:13 -05005348 } else if (callee_code == Builtins::kPopcount) {
David Neto22f144c2017-06-12 14:26:21 -04005349 //
5350 // Generate OpBitCount
5351 //
5352 // Ops[0] = Result Type ID
5353 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005354 SPIRVOperandList Ops;
5355 Ops << MkId(lookupType(Call->getType()))
5356 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005357
5358 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005359 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005360 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005361
David Neto862b7d82018-06-14 18:48:37 -04005362 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005363
5364 // Generate an OpCompositeConstruct
5365 SPIRVOperandList Ops;
5366
5367 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005368 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005369
5370 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005371 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005372 }
5373
5374 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005375 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5376 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005377
Alan Baker202c8c72018-08-13 13:47:44 -04005378 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5379
5380 // We have already mapped the call's result value to an ID.
5381 // Don't generate any code now.
5382
5383 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005384
5385 // We have already mapped the call's result value to an ID.
5386 // Don't generate any code now.
5387
David Neto22f144c2017-06-12 14:26:21 -04005388 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005389 if (Call->getType()->isPointerTy()) {
5390 // Functions returning pointers require variable pointers.
5391 setVariablePointersCapabilities(
5392 Call->getType()->getPointerAddressSpace());
5393 }
5394
David Neto22f144c2017-06-12 14:26:21 -04005395 //
5396 // Generate OpFunctionCall.
5397 //
5398
5399 // Ops[0] = Result Type ID
5400 // Ops[1] = Callee Function ID
5401 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5402 SPIRVOperandList Ops;
5403
David Neto862b7d82018-06-14 18:48:37 -04005404 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005405
5406 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005407 if (CalleeID == 0) {
5408 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005409 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005410 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5411 // causes an infinite loop. Instead, go ahead and generate
5412 // the bad function call. A validator will catch the 0-Id.
5413 // llvm_unreachable("Can't translate function call");
5414 }
David Neto22f144c2017-06-12 14:26:21 -04005415
David Neto257c3892018-04-11 13:19:45 -04005416 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005417
David Neto22f144c2017-06-12 14:26:21 -04005418 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5419 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005420 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005421 auto *operand_type = operand->getType();
5422 // Images and samplers can be passed as function parameters without
5423 // variable pointers.
5424 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5425 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005426 auto sc =
5427 GetStorageClass(operand->getType()->getPointerAddressSpace());
5428 if (sc == spv::StorageClassStorageBuffer) {
5429 // Passing SSBO by reference requires variable pointers storage
5430 // buffer.
5431 setVariablePointersStorageBuffer(true);
5432 } else if (sc == spv::StorageClassWorkgroup) {
5433 // Workgroup references require variable pointers if they are not
5434 // memory object declarations.
5435 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5436 // Workgroup accessor represents a variable reference.
5437 if (!operand_call->getCalledFunction()->getName().startswith(
5438 clspv::WorkgroupAccessorFunction()))
5439 setVariablePointers(true);
5440 } else {
5441 // Arguments are function parameters.
5442 if (!isa<Argument>(operand))
5443 setVariablePointers(true);
5444 }
5445 }
5446 }
5447 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005448 }
5449
David Neto87846742018-04-11 17:36:22 -04005450 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5451 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005452 SPIRVInstList.insert(InsertPoint, CallInst);
5453 }
5454 }
5455 }
5456}
5457
SJW77b87ad2020-04-21 14:37:52 -05005458void SPIRVProducerPass::HandleDeferredDecorations() {
5459 const auto &DL = module->getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04005460 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005461 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005462 }
David Neto1a1a0582017-07-07 12:01:44 -04005463
SJW69939d52020-04-16 07:29:07 -05005464 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kAnnotations);
David Neto1a1a0582017-07-07 12:01:44 -04005465
David Netoc6f3ab22018-04-06 18:02:31 -04005466 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5467 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005468 for (auto *type : getTypesNeedingArrayStride()) {
5469 Type *elemTy = nullptr;
5470 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5471 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005472 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04005473 elemTy = arrayTy->getElementType();
5474 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
5475 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07005476 } else {
5477 errs() << "Unhandled strided type " << *type << "\n";
5478 llvm_unreachable("Unhandled strided type");
5479 }
David Neto1a1a0582017-07-07 12:01:44 -04005480
5481 // Ops[0] = Target ID
5482 // Ops[1] = Decoration (ArrayStride)
5483 // Ops[2] = Stride number (Literal Number)
5484 SPIRVOperandList Ops;
5485
David Neto85082642018-03-24 06:55:20 -07005486 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005487 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005488
5489 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5490 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005491
David Neto87846742018-04-11 17:36:22 -04005492 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05005493 SPIRVInstList.push_back(DecoInst);
David Neto1a1a0582017-07-07 12:01:44 -04005494 }
David Netoc6f3ab22018-04-06 18:02:31 -04005495
5496 // Emit SpecId decorations targeting the array size value.
SJW77b87ad2020-04-21 14:37:52 -05005497 for (auto pair : clspv::GetSpecConstants(module)) {
alan-bakera1be3322020-04-20 12:48:18 -04005498 auto kind = pair.first;
5499 auto spec_id = pair.second;
5500
5501 if (kind != SpecConstant::kLocalMemorySize)
5502 continue;
5503
alan-bakerb6b09dc2018-11-08 16:59:28 -05005504 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005505 SPIRVOperandList Ops;
5506 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5507 << MkNum(arg_info.spec_id);
SJW69939d52020-04-16 07:29:07 -05005508 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005509 }
David Neto1a1a0582017-07-07 12:01:44 -04005510}
5511
David Neto22f144c2017-06-12 14:26:21 -04005512glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005513
5514 const auto &fi = Builtins::Lookup(Name);
5515 switch (fi) {
5516 case Builtins::kClamp: {
5517 auto param_type = fi.getParameter(0);
5518 if (param_type.type_id == Type::FloatTyID) {
5519 return glsl::ExtInst::ExtInstFClamp;
5520 }
5521 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
5522 : glsl::ExtInst::ExtInstUClamp;
5523 }
5524 case Builtins::kMax: {
5525 auto param_type = fi.getParameter(0);
5526 if (param_type.type_id == Type::FloatTyID) {
5527 return glsl::ExtInst::ExtInstFMax;
5528 }
5529 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
5530 : glsl::ExtInst::ExtInstUMax;
5531 }
5532 case Builtins::kMin: {
5533 auto param_type = fi.getParameter(0);
5534 if (param_type.type_id == Type::FloatTyID) {
5535 return glsl::ExtInst::ExtInstFMin;
5536 }
5537 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
5538 : glsl::ExtInst::ExtInstUMin;
5539 }
5540 case Builtins::kAbs:
5541 return glsl::ExtInst::ExtInstSAbs;
5542 case Builtins::kFmax:
5543 return glsl::ExtInst::ExtInstFMax;
5544 case Builtins::kFmin:
5545 return glsl::ExtInst::ExtInstFMin;
5546 case Builtins::kDegrees:
5547 return glsl::ExtInst::ExtInstDegrees;
5548 case Builtins::kRadians:
5549 return glsl::ExtInst::ExtInstRadians;
5550 case Builtins::kMix:
5551 return glsl::ExtInst::ExtInstFMix;
5552 case Builtins::kAcos:
5553 case Builtins::kAcospi:
5554 return glsl::ExtInst::ExtInstAcos;
5555 case Builtins::kAcosh:
5556 return glsl::ExtInst::ExtInstAcosh;
5557 case Builtins::kAsin:
5558 case Builtins::kAsinpi:
5559 return glsl::ExtInst::ExtInstAsin;
5560 case Builtins::kAsinh:
5561 return glsl::ExtInst::ExtInstAsinh;
5562 case Builtins::kAtan:
5563 case Builtins::kAtanpi:
5564 return glsl::ExtInst::ExtInstAtan;
5565 case Builtins::kAtanh:
5566 return glsl::ExtInst::ExtInstAtanh;
5567 case Builtins::kAtan2:
5568 case Builtins::kAtan2pi:
5569 return glsl::ExtInst::ExtInstAtan2;
5570 case Builtins::kCeil:
5571 return glsl::ExtInst::ExtInstCeil;
5572 case Builtins::kSin:
5573 case Builtins::kHalfSin:
5574 case Builtins::kNativeSin:
5575 return glsl::ExtInst::ExtInstSin;
5576 case Builtins::kSinh:
5577 return glsl::ExtInst::ExtInstSinh;
5578 case Builtins::kCos:
5579 case Builtins::kHalfCos:
5580 case Builtins::kNativeCos:
5581 return glsl::ExtInst::ExtInstCos;
5582 case Builtins::kCosh:
5583 return glsl::ExtInst::ExtInstCosh;
5584 case Builtins::kTan:
5585 case Builtins::kHalfTan:
5586 case Builtins::kNativeTan:
5587 return glsl::ExtInst::ExtInstTan;
5588 case Builtins::kTanh:
5589 return glsl::ExtInst::ExtInstTanh;
5590 case Builtins::kExp:
5591 case Builtins::kHalfExp:
5592 case Builtins::kNativeExp:
5593 return glsl::ExtInst::ExtInstExp;
5594 case Builtins::kExp2:
5595 case Builtins::kHalfExp2:
5596 case Builtins::kNativeExp2:
5597 return glsl::ExtInst::ExtInstExp2;
5598 case Builtins::kLog:
5599 case Builtins::kHalfLog:
5600 case Builtins::kNativeLog:
5601 return glsl::ExtInst::ExtInstLog;
5602 case Builtins::kLog2:
5603 case Builtins::kHalfLog2:
5604 case Builtins::kNativeLog2:
5605 return glsl::ExtInst::ExtInstLog2;
5606 case Builtins::kFabs:
5607 return glsl::ExtInst::ExtInstFAbs;
5608 case Builtins::kFma:
5609 return glsl::ExtInst::ExtInstFma;
5610 case Builtins::kFloor:
5611 return glsl::ExtInst::ExtInstFloor;
5612 case Builtins::kLdexp:
5613 return glsl::ExtInst::ExtInstLdexp;
5614 case Builtins::kPow:
5615 case Builtins::kPowr:
5616 case Builtins::kHalfPowr:
5617 case Builtins::kNativePowr:
5618 return glsl::ExtInst::ExtInstPow;
5619 case Builtins::kRound:
5620 return glsl::ExtInst::ExtInstRound;
5621 case Builtins::kSqrt:
5622 case Builtins::kHalfSqrt:
5623 case Builtins::kNativeSqrt:
5624 return glsl::ExtInst::ExtInstSqrt;
5625 case Builtins::kRsqrt:
5626 case Builtins::kHalfRsqrt:
5627 case Builtins::kNativeRsqrt:
5628 return glsl::ExtInst::ExtInstInverseSqrt;
5629 case Builtins::kTrunc:
5630 return glsl::ExtInst::ExtInstTrunc;
5631 case Builtins::kFrexp:
5632 return glsl::ExtInst::ExtInstFrexp;
5633 case Builtins::kFract:
5634 return glsl::ExtInst::ExtInstFract;
5635 case Builtins::kSign:
5636 return glsl::ExtInst::ExtInstFSign;
5637 case Builtins::kLength:
5638 case Builtins::kFastLength:
5639 return glsl::ExtInst::ExtInstLength;
5640 case Builtins::kDistance:
5641 case Builtins::kFastDistance:
5642 return glsl::ExtInst::ExtInstDistance;
5643 case Builtins::kStep:
5644 return glsl::ExtInst::ExtInstStep;
5645 case Builtins::kSmoothstep:
5646 return glsl::ExtInst::ExtInstSmoothStep;
5647 case Builtins::kCross:
5648 return glsl::ExtInst::ExtInstCross;
5649 case Builtins::kNormalize:
5650 case Builtins::kFastNormalize:
5651 return glsl::ExtInst::ExtInstNormalize;
5652 default:
5653 break;
5654 }
5655
David Neto22f144c2017-06-12 14:26:21 -04005656 return StringSwitch<glsl::ExtInst>(Name)
David Neto22f144c2017-06-12 14:26:21 -04005657 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5658 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5659 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto3fbb4072017-10-16 11:28:14 -04005660 .Default(kGlslExtInstBad);
5661}
5662
5663glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005664 switch (Builtins::Lookup(Name)) {
5665 case Builtins::kClz:
5666 return glsl::ExtInst::ExtInstFindUMsb;
5667 case Builtins::kAcospi:
5668 return glsl::ExtInst::ExtInstAcos;
5669 case Builtins::kAsinpi:
5670 return glsl::ExtInst::ExtInstAsin;
5671 case Builtins::kAtanpi:
5672 return glsl::ExtInst::ExtInstAtan;
5673 case Builtins::kAtan2pi:
5674 return glsl::ExtInst::ExtInstAtan2;
5675 default:
5676 break;
5677 }
5678 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005679}
5680
alan-bakerb6b09dc2018-11-08 16:59:28 -05005681glsl::ExtInst
5682SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005683 auto direct = getExtInstEnum(Name);
5684 if (direct != kGlslExtInstBad)
5685 return direct;
5686 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005687}
5688
David Neto22f144c2017-06-12 14:26:21 -04005689void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005690 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005691}
5692
5693void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5694 WriteOneWord(Inst->getResultID());
5695}
5696
5697void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5698 // High 16 bit : Word Count
5699 // Low 16 bit : Opcode
5700 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005701 const uint32_t count = Inst->getWordCount();
5702 if (count > 65535) {
5703 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5704 llvm_unreachable("Word count too high");
5705 }
David Neto22f144c2017-06-12 14:26:21 -04005706 Word |= Inst->getWordCount() << 16;
5707 WriteOneWord(Word);
5708}
5709
David Netoef5ba2b2019-12-20 08:35:54 -05005710void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005711 SPIRVOperandType OpTy = Op->getType();
5712 switch (OpTy) {
5713 default: {
5714 llvm_unreachable("Unsupported SPIRV Operand Type???");
5715 break;
5716 }
5717 case SPIRVOperandType::NUMBERID: {
5718 WriteOneWord(Op->getNumID());
5719 break;
5720 }
5721 case SPIRVOperandType::LITERAL_STRING: {
5722 std::string Str = Op->getLiteralStr();
5723 const char *Data = Str.c_str();
5724 size_t WordSize = Str.size() / 4;
5725 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5726 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5727 }
5728
5729 uint32_t Remainder = Str.size() % 4;
5730 uint32_t LastWord = 0;
5731 if (Remainder) {
5732 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5733 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5734 }
5735 }
5736
5737 WriteOneWord(LastWord);
5738 break;
5739 }
5740 case SPIRVOperandType::LITERAL_INTEGER:
5741 case SPIRVOperandType::LITERAL_FLOAT: {
5742 auto LiteralNum = Op->getLiteralNum();
5743 // TODO: Handle LiteranNum carefully.
5744 for (auto Word : LiteralNum) {
5745 WriteOneWord(Word);
5746 }
5747 break;
5748 }
5749 }
5750}
5751
5752void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005753 for (int i = 0; i < kSectionCount; ++i) {
5754 WriteSPIRVBinary(SPIRVSections[i]);
5755 }
5756}
5757
5758void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04005759
5760 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005761 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005762 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5763
5764 switch (Opcode) {
5765 default: {
David Neto5c22a252018-03-15 16:07:41 -04005766 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005767 llvm_unreachable("Unsupported SPIRV instruction");
5768 break;
5769 }
5770 case spv::OpCapability:
5771 case spv::OpExtension:
5772 case spv::OpMemoryModel:
5773 case spv::OpEntryPoint:
5774 case spv::OpExecutionMode:
5775 case spv::OpSource:
5776 case spv::OpDecorate:
5777 case spv::OpMemberDecorate:
5778 case spv::OpBranch:
5779 case spv::OpBranchConditional:
5780 case spv::OpSelectionMerge:
5781 case spv::OpLoopMerge:
5782 case spv::OpStore:
5783 case spv::OpImageWrite:
5784 case spv::OpReturnValue:
5785 case spv::OpControlBarrier:
5786 case spv::OpMemoryBarrier:
5787 case spv::OpReturn:
5788 case spv::OpFunctionEnd:
5789 case spv::OpCopyMemory: {
5790 WriteWordCountAndOpcode(Inst);
5791 for (uint32_t i = 0; i < Ops.size(); i++) {
5792 WriteOperand(Ops[i]);
5793 }
5794 break;
5795 }
5796 case spv::OpTypeBool:
5797 case spv::OpTypeVoid:
5798 case spv::OpTypeSampler:
5799 case spv::OpLabel:
5800 case spv::OpExtInstImport:
5801 case spv::OpTypePointer:
5802 case spv::OpTypeRuntimeArray:
5803 case spv::OpTypeStruct:
5804 case spv::OpTypeImage:
5805 case spv::OpTypeSampledImage:
5806 case spv::OpTypeInt:
5807 case spv::OpTypeFloat:
5808 case spv::OpTypeArray:
5809 case spv::OpTypeVector:
5810 case spv::OpTypeFunction: {
5811 WriteWordCountAndOpcode(Inst);
5812 WriteResultID(Inst);
5813 for (uint32_t i = 0; i < Ops.size(); i++) {
5814 WriteOperand(Ops[i]);
5815 }
5816 break;
5817 }
5818 case spv::OpFunction:
5819 case spv::OpFunctionParameter:
5820 case spv::OpAccessChain:
5821 case spv::OpPtrAccessChain:
5822 case spv::OpInBoundsAccessChain:
5823 case spv::OpUConvert:
5824 case spv::OpSConvert:
5825 case spv::OpConvertFToU:
5826 case spv::OpConvertFToS:
5827 case spv::OpConvertUToF:
5828 case spv::OpConvertSToF:
5829 case spv::OpFConvert:
5830 case spv::OpConvertPtrToU:
5831 case spv::OpConvertUToPtr:
5832 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005833 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005834 case spv::OpIAdd:
5835 case spv::OpFAdd:
5836 case spv::OpISub:
5837 case spv::OpFSub:
5838 case spv::OpIMul:
5839 case spv::OpFMul:
5840 case spv::OpUDiv:
5841 case spv::OpSDiv:
5842 case spv::OpFDiv:
5843 case spv::OpUMod:
5844 case spv::OpSRem:
5845 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005846 case spv::OpUMulExtended:
5847 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005848 case spv::OpBitwiseOr:
5849 case spv::OpBitwiseXor:
5850 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005851 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005852 case spv::OpShiftLeftLogical:
5853 case spv::OpShiftRightLogical:
5854 case spv::OpShiftRightArithmetic:
5855 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005856 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005857 case spv::OpCompositeExtract:
5858 case spv::OpVectorExtractDynamic:
5859 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005860 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005861 case spv::OpVectorInsertDynamic:
5862 case spv::OpVectorShuffle:
5863 case spv::OpIEqual:
5864 case spv::OpINotEqual:
5865 case spv::OpUGreaterThan:
5866 case spv::OpUGreaterThanEqual:
5867 case spv::OpULessThan:
5868 case spv::OpULessThanEqual:
5869 case spv::OpSGreaterThan:
5870 case spv::OpSGreaterThanEqual:
5871 case spv::OpSLessThan:
5872 case spv::OpSLessThanEqual:
5873 case spv::OpFOrdEqual:
5874 case spv::OpFOrdGreaterThan:
5875 case spv::OpFOrdGreaterThanEqual:
5876 case spv::OpFOrdLessThan:
5877 case spv::OpFOrdLessThanEqual:
5878 case spv::OpFOrdNotEqual:
5879 case spv::OpFUnordEqual:
5880 case spv::OpFUnordGreaterThan:
5881 case spv::OpFUnordGreaterThanEqual:
5882 case spv::OpFUnordLessThan:
5883 case spv::OpFUnordLessThanEqual:
5884 case spv::OpFUnordNotEqual:
5885 case spv::OpExtInst:
5886 case spv::OpIsInf:
5887 case spv::OpIsNan:
5888 case spv::OpAny:
5889 case spv::OpAll:
5890 case spv::OpUndef:
5891 case spv::OpConstantNull:
5892 case spv::OpLogicalOr:
5893 case spv::OpLogicalAnd:
5894 case spv::OpLogicalNot:
5895 case spv::OpLogicalNotEqual:
5896 case spv::OpConstantComposite:
5897 case spv::OpSpecConstantComposite:
5898 case spv::OpConstantTrue:
5899 case spv::OpConstantFalse:
5900 case spv::OpConstant:
5901 case spv::OpSpecConstant:
5902 case spv::OpVariable:
5903 case spv::OpFunctionCall:
5904 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005905 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04005906 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005907 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005908 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005909 case spv::OpSelect:
5910 case spv::OpPhi:
5911 case spv::OpLoad:
5912 case spv::OpAtomicIAdd:
5913 case spv::OpAtomicISub:
5914 case spv::OpAtomicExchange:
5915 case spv::OpAtomicIIncrement:
5916 case spv::OpAtomicIDecrement:
5917 case spv::OpAtomicCompareExchange:
5918 case spv::OpAtomicUMin:
5919 case spv::OpAtomicSMin:
5920 case spv::OpAtomicUMax:
5921 case spv::OpAtomicSMax:
5922 case spv::OpAtomicAnd:
5923 case spv::OpAtomicOr:
5924 case spv::OpAtomicXor:
5925 case spv::OpDot: {
5926 WriteWordCountAndOpcode(Inst);
5927 WriteOperand(Ops[0]);
5928 WriteResultID(Inst);
5929 for (uint32_t i = 1; i < Ops.size(); i++) {
5930 WriteOperand(Ops[i]);
5931 }
5932 break;
5933 }
5934 }
5935 }
5936}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005937
alan-bakerb6b09dc2018-11-08 16:59:28 -05005938bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005939 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005940 case Type::HalfTyID:
5941 case Type::FloatTyID:
5942 case Type::DoubleTyID:
5943 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005944 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005945 return true;
5946 case Type::PointerTyID: {
5947 const PointerType *pointer_type = cast<PointerType>(type);
5948 if (pointer_type->getPointerAddressSpace() !=
5949 AddressSpace::UniformConstant) {
5950 auto pointee_type = pointer_type->getPointerElementType();
5951 if (pointee_type->isStructTy() &&
5952 cast<StructType>(pointee_type)->isOpaque()) {
5953 // Images and samplers are not nullable.
5954 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005955 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005956 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005957 return true;
5958 }
5959 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005960 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005961 case Type::StructTyID: {
5962 const StructType *struct_type = cast<StructType>(type);
5963 // Images and samplers are not nullable.
5964 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005965 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005966 for (const auto element : struct_type->elements()) {
5967 if (!IsTypeNullable(element))
5968 return false;
5969 }
5970 return true;
5971 }
5972 default:
5973 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005974 }
5975}
Alan Bakerfcda9482018-10-02 17:09:59 -04005976
SJW77b87ad2020-04-21 14:37:52 -05005977void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005978 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005979 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005980 // Metdata is stored as key-value pair operands. The first element of each
5981 // operand is the type and the second is a vector of offsets.
5982 for (const auto *operand : offsets_md->operands()) {
5983 const auto *pair = cast<MDTuple>(operand);
5984 auto *type =
5985 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5986 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5987 std::vector<uint32_t> offsets;
5988 for (const Metadata *offset_md : offset_vector->operands()) {
5989 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005990 offsets.push_back(static_cast<uint32_t>(
5991 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005992 }
5993 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5994 }
5995 }
5996
5997 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005998 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005999 // Metadata is stored as key-value pair operands. The first element of each
6000 // operand is the type and the second is a triple of sizes: type size in
6001 // bits, store size and alloc size.
6002 for (const auto *operand : sizes_md->operands()) {
6003 const auto *pair = cast<MDTuple>(operand);
6004 auto *type =
6005 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6006 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6007 uint64_t type_size_in_bits =
6008 cast<ConstantInt>(
6009 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6010 ->getZExtValue();
6011 uint64_t type_store_size =
6012 cast<ConstantInt>(
6013 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6014 ->getZExtValue();
6015 uint64_t type_alloc_size =
6016 cast<ConstantInt>(
6017 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6018 ->getZExtValue();
6019 RemappedUBOTypeSizes.insert(std::make_pair(
6020 type, std::make_tuple(type_size_in_bits, type_store_size,
6021 type_alloc_size)));
6022 }
6023 }
6024}
6025
6026uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6027 const DataLayout &DL) {
6028 auto iter = RemappedUBOTypeSizes.find(type);
6029 if (iter != RemappedUBOTypeSizes.end()) {
6030 return std::get<0>(iter->second);
6031 }
6032
6033 return DL.getTypeSizeInBits(type);
6034}
6035
6036uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6037 auto iter = RemappedUBOTypeSizes.find(type);
6038 if (iter != RemappedUBOTypeSizes.end()) {
6039 return std::get<1>(iter->second);
6040 }
6041
6042 return DL.getTypeStoreSize(type);
6043}
6044
6045uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6046 auto iter = RemappedUBOTypeSizes.find(type);
6047 if (iter != RemappedUBOTypeSizes.end()) {
6048 return std::get<2>(iter->second);
6049 }
6050
6051 return DL.getTypeAllocSize(type);
6052}
alan-baker5b86ed72019-02-15 08:26:50 -05006053
Kévin Petitbbbda972020-03-03 19:16:31 +00006054uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
6055 StructType *type, unsigned member, const DataLayout &DL) {
6056 const auto StructLayout = DL.getStructLayout(type);
6057 // Search for the correct offsets if this type was remapped.
6058 std::vector<uint32_t> *offsets = nullptr;
6059 auto iter = RemappedUBOTypeOffsets.find(type);
6060 if (iter != RemappedUBOTypeOffsets.end()) {
6061 offsets = &iter->second;
6062 }
6063 auto ByteOffset =
6064 static_cast<uint32_t>(StructLayout->getElementOffset(member));
6065 if (offsets) {
6066 ByteOffset = (*offsets)[member];
6067 }
6068
6069 return ByteOffset;
6070}
6071
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006072void SPIRVProducerPass::setVariablePointersCapabilities(
6073 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006074 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6075 setVariablePointersStorageBuffer(true);
6076 } else {
6077 setVariablePointers(true);
6078 }
6079}
6080
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006081Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006082 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6083 return GetBasePointer(gep->getPointerOperand());
6084 }
6085
6086 // Conservatively return |v|.
6087 return v;
6088}
6089
6090bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6091 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6092 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6093 if (lhs_call->getCalledFunction()->getName().startswith(
6094 clspv::ResourceAccessorFunction()) &&
6095 rhs_call->getCalledFunction()->getName().startswith(
6096 clspv::ResourceAccessorFunction())) {
6097 // For resource accessors, match descriptor set and binding.
6098 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6099 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6100 return true;
6101 } else if (lhs_call->getCalledFunction()->getName().startswith(
6102 clspv::WorkgroupAccessorFunction()) &&
6103 rhs_call->getCalledFunction()->getName().startswith(
6104 clspv::WorkgroupAccessorFunction())) {
6105 // For workgroup resources, match spec id.
6106 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6107 return true;
6108 }
6109 }
6110 }
6111
6112 return false;
6113}
6114
6115bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6116 assert(inst->getType()->isPointerTy());
6117 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6118 spv::StorageClassStorageBuffer);
6119 const bool hack_undef = clspv::Option::HackUndef();
6120 if (auto *select = dyn_cast<SelectInst>(inst)) {
6121 auto *true_base = GetBasePointer(select->getTrueValue());
6122 auto *false_base = GetBasePointer(select->getFalseValue());
6123
6124 if (true_base == false_base)
6125 return true;
6126
6127 // If either the true or false operand is a null, then we satisfy the same
6128 // object constraint.
6129 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6130 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6131 return true;
6132 }
6133
6134 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6135 if (false_cst->isNullValue() ||
6136 (hack_undef && isa<UndefValue>(false_base)))
6137 return true;
6138 }
6139
6140 if (sameResource(true_base, false_base))
6141 return true;
6142 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6143 Value *value = nullptr;
6144 bool ok = true;
6145 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6146 auto *base = GetBasePointer(phi->getIncomingValue(i));
6147 // Null values satisfy the constraint of selecting of selecting from the
6148 // same object.
6149 if (!value) {
6150 if (auto *cst = dyn_cast<Constant>(base)) {
6151 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6152 value = base;
6153 } else {
6154 value = base;
6155 }
6156 } else if (base != value) {
6157 if (auto *base_cst = dyn_cast<Constant>(base)) {
6158 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6159 continue;
6160 }
6161
6162 if (sameResource(value, base))
6163 continue;
6164
6165 // Values don't represent the same base.
6166 ok = false;
6167 }
6168 }
6169
6170 return ok;
6171 }
6172
6173 // Conservatively return false.
6174 return false;
6175}
alan-bakere9308012019-03-15 10:25:13 -04006176
6177bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6178 if (!Arg.getType()->isPointerTy() ||
6179 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6180 // Only SSBOs need to be annotated as coherent.
6181 return false;
6182 }
6183
6184 DenseSet<Value *> visited;
6185 std::vector<Value *> stack;
6186 for (auto *U : Arg.getParent()->users()) {
6187 if (auto *call = dyn_cast<CallInst>(U)) {
6188 stack.push_back(call->getOperand(Arg.getArgNo()));
6189 }
6190 }
6191
6192 while (!stack.empty()) {
6193 Value *v = stack.back();
6194 stack.pop_back();
6195
6196 if (!visited.insert(v).second)
6197 continue;
6198
6199 auto *resource_call = dyn_cast<CallInst>(v);
6200 if (resource_call &&
6201 resource_call->getCalledFunction()->getName().startswith(
6202 clspv::ResourceAccessorFunction())) {
6203 // If this is a resource accessor function, check if the coherent operand
6204 // is set.
6205 const auto coherent =
6206 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6207 ->getZExtValue());
6208 if (coherent == 1)
6209 return true;
6210 } else if (auto *arg = dyn_cast<Argument>(v)) {
6211 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006212 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006213 if (auto *call = dyn_cast<CallInst>(U)) {
6214 stack.push_back(call->getOperand(arg->getArgNo()));
6215 }
6216 }
6217 } else if (auto *user = dyn_cast<User>(v)) {
6218 // If this is a user, traverse all operands that could lead to resource
6219 // variables.
6220 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6221 Value *operand = user->getOperand(i);
6222 if (operand->getType()->isPointerTy() &&
6223 operand->getType()->getPointerAddressSpace() ==
6224 clspv::AddressSpace::Global) {
6225 stack.push_back(operand);
6226 }
6227 }
6228 }
6229 }
6230
6231 // No coherent resource variables encountered.
6232 return false;
6233}
alan-baker06cad652019-12-03 17:56:47 -05006234
SJW77b87ad2020-04-21 14:37:52 -05006235void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05006236 // First, track loop merges and continues.
6237 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05006238 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05006239 if (F.isDeclaration())
6240 continue;
6241
6242 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6243 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6244 std::deque<BasicBlock *> order;
6245 DenseSet<BasicBlock *> visited;
6246 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6247
6248 for (auto BB : order) {
6249 auto terminator = BB->getTerminator();
6250 auto branch = dyn_cast<BranchInst>(terminator);
6251 if (LI.isLoopHeader(BB)) {
6252 auto L = LI.getLoopFor(BB);
6253 BasicBlock *ContinueBB = nullptr;
6254 BasicBlock *MergeBB = nullptr;
6255
6256 MergeBB = L->getExitBlock();
6257 if (!MergeBB) {
6258 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6259 // has regions with single entry/exit. As a result, loop should not
6260 // have multiple exits.
6261 llvm_unreachable("Loop has multiple exits???");
6262 }
6263
6264 if (L->isLoopLatch(BB)) {
6265 ContinueBB = BB;
6266 } else {
6267 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6268 // block.
6269 BasicBlock *Header = L->getHeader();
6270 BasicBlock *Latch = L->getLoopLatch();
6271 for (auto *loop_block : L->blocks()) {
6272 if (loop_block == Header) {
6273 continue;
6274 }
6275
6276 // Check whether block dominates block with back-edge.
6277 // The loop latch is the single block with a back-edge. If it was
6278 // possible, StructurizeCFG made the loop conform to this
6279 // requirement, otherwise |Latch| is a nullptr.
6280 if (DT.dominates(loop_block, Latch)) {
6281 ContinueBB = loop_block;
6282 }
6283 }
6284
6285 if (!ContinueBB) {
6286 llvm_unreachable("Wrong continue block from loop");
6287 }
6288 }
6289
6290 // Record the continue and merge blocks.
6291 MergeBlocks[BB] = MergeBB;
6292 ContinueBlocks[BB] = ContinueBB;
6293 LoopMergesAndContinues.insert(MergeBB);
6294 LoopMergesAndContinues.insert(ContinueBB);
6295 } else if (branch && branch->isConditional()) {
6296 auto L = LI.getLoopFor(BB);
6297 bool HasBackedge = false;
6298 while (L && !HasBackedge) {
6299 if (L->isLoopLatch(BB)) {
6300 HasBackedge = true;
6301 }
6302 L = L->getParentLoop();
6303 }
6304
6305 if (!HasBackedge) {
6306 // Only need a merge if the branch doesn't include a loop break or
6307 // continue.
6308 auto true_bb = branch->getSuccessor(0);
6309 auto false_bb = branch->getSuccessor(1);
6310 if (!LoopMergesAndContinues.count(true_bb) &&
6311 !LoopMergesAndContinues.count(false_bb)) {
6312 // StructurizeCFG pass already manipulated CFG. Just use false block
6313 // of branch instruction as merge block.
6314 MergeBlocks[BB] = false_bb;
6315 }
6316 }
6317 }
6318 }
6319 }
6320}