blob: 9d60fb07190981ac16ad511b942efe03e0c5e388 [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-baker56f7aff2019-05-22 08:06:42 -040060#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040061#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040062#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050063#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040064
David Neto22f144c2017-06-12 14:26:21 -040065#if defined(_MSC_VER)
66#pragma warning(pop)
67#endif
68
69using namespace llvm;
70using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050071using namespace clspv::Builtins;
David Neto156783e2017-07-05 15:39:41 -040072using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040073
74namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040075
David Neto862b7d82018-06-14 18:48:37 -040076cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
77 cl::desc("Show resource variable creation"));
78
alan-baker5ed87542020-03-23 11:05:22 -040079cl::opt<bool>
80 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
81 cl::desc("Dump the IR at the start of SPIRVProducer"));
82
David Neto862b7d82018-06-14 18:48:37 -040083// These hacks exist to help transition code generation algorithms
84// without making huge noise in detailed test output.
85const bool Hack_generate_runtime_array_stride_early = true;
86
David Neto3fbb4072017-10-16 11:28:14 -040087// The value of 1/pi. This value is from MSDN
88// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
89const double kOneOverPi = 0.318309886183790671538;
90const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
91
alan-bakerb6b09dc2018-11-08 16:59:28 -050092const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040093
SJW69939d52020-04-16 07:29:07 -050094// SPIRV Module Sections (per 2.4 of the SPIRV spec)
95// These are used to collect SPIRVInstructions by type on-the-fly.
96enum SPIRVSection {
97 kCapabilities,
98 kExtensions,
99 kImports,
100 kMemoryModel,
101 kEntryPoints,
102 kExecutionModes,
103
104 kDebug,
105 kAnnotations,
106
107 kTypes,
108 kConstants = kTypes,
109 kGlobalVariables,
110
111 kFunctions,
112
113 kSectionCount
114};
115
David Neto22f144c2017-06-12 14:26:21 -0400116enum SPIRVOperandType {
117 NUMBERID,
118 LITERAL_INTEGER,
119 LITERAL_STRING,
120 LITERAL_FLOAT
121};
122
123struct SPIRVOperand {
124 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
125 : Type(Ty), LiteralNum(1, Num) {}
126 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
127 : Type(Ty), LiteralStr(Str) {}
128 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
129 : Type(Ty), LiteralStr(Str) {}
130 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
131 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
132
James Price11010dc2019-12-19 13:53:09 -0500133 SPIRVOperandType getType() const { return Type; };
134 uint32_t getNumID() const { return LiteralNum[0]; };
135 std::string getLiteralStr() const { return LiteralStr; };
136 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400137
David Neto87846742018-04-11 17:36:22 -0400138 uint32_t GetNumWords() const {
139 switch (Type) {
140 case NUMBERID:
141 return 1;
142 case LITERAL_INTEGER:
143 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400144 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400145 case LITERAL_STRING:
146 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400147 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400148 }
149 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
150 }
151
David Neto22f144c2017-06-12 14:26:21 -0400152private:
153 SPIRVOperandType Type;
154 std::string LiteralStr;
155 SmallVector<uint32_t, 4> LiteralNum;
156};
157
David Netoc6f3ab22018-04-06 18:02:31 -0400158class SPIRVOperandList {
159public:
David Netoef5ba2b2019-12-20 08:35:54 -0500160 typedef std::unique_ptr<SPIRVOperand> element_type;
161 typedef SmallVector<element_type, 8> container_type;
162 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400163 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500164 SPIRVOperandList(const SPIRVOperandList &other) = delete;
165 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400166 contents_ = std::move(other.contents_);
167 other.contents_.clear();
168 }
David Netoef5ba2b2019-12-20 08:35:54 -0500169 iterator begin() { return contents_.begin(); }
170 iterator end() { return contents_.end(); }
171 operator ArrayRef<element_type>() { return contents_; }
172 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500173 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400174 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500175 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400176
David Netoef5ba2b2019-12-20 08:35:54 -0500177 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400178
David Netoc6f3ab22018-04-06 18:02:31 -0400179private:
David Netoef5ba2b2019-12-20 08:35:54 -0500180 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400181};
182
James Price11010dc2019-12-19 13:53:09 -0500183SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500184 std::unique_ptr<SPIRVOperand> elem) {
185 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400186 return list;
187}
188
David Netoef5ba2b2019-12-20 08:35:54 -0500189std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
190 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400191}
David Netoef5ba2b2019-12-20 08:35:54 -0500192std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
193 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400194}
David Netoef5ba2b2019-12-20 08:35:54 -0500195std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
196 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400197}
David Netoef5ba2b2019-12-20 08:35:54 -0500198std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
199 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500200}
David Netoef5ba2b2019-12-20 08:35:54 -0500201std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
202 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400203}
David Netoc6f3ab22018-04-06 18:02:31 -0400204
David Neto22f144c2017-06-12 14:26:21 -0400205struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500206 // Creates an instruction with an opcode and no result ID, and with the given
207 // operands. This computes its own word count. Takes ownership of the
208 // operands and clears |Ops|.
209 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
210 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500211 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400212 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400213 }
David Netoef5ba2b2019-12-20 08:35:54 -0500214 Operands.reserve(Ops.size());
215 for (auto &ptr : Ops) {
216 Operands.emplace_back(std::move(ptr));
217 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400218 }
David Netoef5ba2b2019-12-20 08:35:54 -0500219 Ops.clear();
220 }
221 // Creates an instruction with an opcode and a no-zero result ID, and
222 // with the given operands. This computes its own word count. Takes ownership
223 // of the operands and clears |Ops|.
224 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
225 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500226 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400227 WordCount += operand->GetNumWords();
228 }
David Netoef5ba2b2019-12-20 08:35:54 -0500229 Operands.reserve(Ops.size());
230 for (auto &ptr : Ops) {
231 Operands.emplace_back(std::move(ptr));
232 ptr.reset(nullptr);
233 }
234 if (ResID == 0) {
235 llvm_unreachable("Result ID of 0 was provided");
236 }
237 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400238 }
David Neto22f144c2017-06-12 14:26:21 -0400239
David Netoef5ba2b2019-12-20 08:35:54 -0500240 // Creates an instruction with an opcode and no result ID, and with the single
241 // operand. This computes its own word count.
242 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
243 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
244 WordCount += operand->GetNumWords();
245 Operands.emplace_back(std::move(operand));
246 operand.reset(nullptr);
247 }
248 // Creates an instruction with an opcode and a non-zero result ID, and
249 // with the single operand. This computes its own word count.
250 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
251 SPIRVOperandList::element_type operand)
252 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
253 WordCount += operand->GetNumWords();
254 if (ResID == 0) {
255 llvm_unreachable("Result ID of 0 was provided");
256 }
257 Operands.emplace_back(std::move(operand));
258 operand.reset(nullptr);
259 }
260 // Creates an instruction with an opcode and a no-zero result ID, and no
261 // operands.
262 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
263 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
264 if (ResID == 0) {
265 llvm_unreachable("Result ID of 0 was provided");
266 }
267 }
268 // Creates an instruction with an opcode, no result ID, no type ID, and no
269 // operands.
270 SPIRVInstruction(spv::Op Opc)
271 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
272
David Netoee2660d2018-06-28 16:31:29 -0400273 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400274 uint16_t getOpcode() const { return Opcode; }
275 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500276 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500277 return Operands;
278 }
David Neto22f144c2017-06-12 14:26:21 -0400279
280private:
David Netoee2660d2018-06-28 16:31:29 -0400281 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400282 uint16_t Opcode;
283 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500284 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400285};
286
287struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400288 typedef DenseMap<Type *, uint32_t> TypeMapType;
289 typedef UniqueVector<Type *> TypeList;
290 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400291 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400292 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
293 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400294 // A vector of tuples, each of which is:
295 // - the LLVM instruction that we will later generate SPIR-V code for
296 // - where the SPIR-V instruction should be inserted
297 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400298 typedef std::vector<
299 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
300 DeferredInstVecType;
301 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
302 GlobalConstFuncMapType;
303
David Neto44795152017-07-13 15:45:28 -0400304 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500305 raw_pwrite_stream &out,
306 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400307 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400308 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400309 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400310 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400311 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400312 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500313 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
314 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
alan-bakera1be3322020-04-20 12:48:18 -0400315 WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400316
James Price11010dc2019-12-19 13:53:09 -0500317 virtual ~SPIRVProducerPass() {
SJW69939d52020-04-16 07:29:07 -0500318 for (int i = 0; i < kSectionCount; ++i) {
319 for (auto *Inst : SPIRVSections[i]) {
320 delete Inst;
321 }
James Price11010dc2019-12-19 13:53:09 -0500322 }
323 }
324
David Neto22f144c2017-06-12 14:26:21 -0400325 void getAnalysisUsage(AnalysisUsage &AU) const override {
326 AU.addRequired<DominatorTreeWrapperPass>();
327 AU.addRequired<LoopInfoWrapperPass>();
328 }
329
330 virtual bool runOnModule(Module &module) override;
331
332 // output the SPIR-V header block
333 void outputHeader();
334
335 // patch the SPIR-V header block
336 void patchHeader();
337
338 uint32_t lookupType(Type *Ty) {
339 if (Ty->isPointerTy() &&
340 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
341 auto PointeeTy = Ty->getPointerElementType();
342 if (PointeeTy->isStructTy() &&
343 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
344 Ty = PointeeTy;
345 }
346 }
347
David Neto862b7d82018-06-14 18:48:37 -0400348 auto where = TypeMap.find(Ty);
349 if (where == TypeMap.end()) {
350 if (Ty) {
351 errs() << "Unhandled type " << *Ty << "\n";
352 } else {
353 errs() << "Unhandled type (null)\n";
354 }
David Netoe439d702018-03-23 13:14:08 -0700355 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400356 }
357
David Neto862b7d82018-06-14 18:48:37 -0400358 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400359 }
360 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500361 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400362 TypeList &getTypeList() { return Types; };
363 ValueList &getConstantList() { return Constants; };
364 ValueMapType &getValueMap() { return ValueMap; }
365 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
SJW69939d52020-04-16 07:29:07 -0500366 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
367 return SPIRVSections[Section];
368 };
David Neto22f144c2017-06-12 14:26:21 -0400369 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
370 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
371 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
372 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
373 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
SJW2c317da2020-03-23 07:39:13 -0500374
alan-baker5b86ed72019-02-15 08:26:50 -0500375 bool hasVariablePointersStorageBuffer() {
376 return HasVariablePointersStorageBuffer;
377 }
378 void setVariablePointersStorageBuffer(bool Val) {
379 HasVariablePointersStorageBuffer = Val;
380 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400381 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400382 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500383 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
384 return samplerMap;
385 }
David Neto22f144c2017-06-12 14:26:21 -0400386 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
387 return GlobalConstFuncTypeMap;
388 }
389 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
390 return GlobalConstArgumentSet;
391 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500392 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400393
David Netoc6f3ab22018-04-06 18:02:31 -0400394 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500395 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
396 // *not* be converted to a storage buffer, replace each such global variable
397 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400398 void FindGlobalConstVars(Module &M, const DataLayout &DL);
399 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
400 // ModuleOrderedResourceVars.
401 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400402 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400403 bool FindExtInst(Module &M);
404 void FindTypePerGlobalVar(GlobalVariable &GV);
405 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400406 void FindTypesForSamplerMap(Module &M);
407 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500408 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
409 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400410 void FindType(Type *Ty);
411 void FindConstantPerGlobalVar(GlobalVariable &GV);
412 void FindConstantPerFunc(Function &F);
413 void FindConstant(Value *V);
414 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400415 // Generates instructions for SPIR-V types corresponding to the LLVM types
416 // saved in the |Types| member. A type follows its subtypes. IDs are
417 // allocated sequentially starting with the current value of nextID, and
418 // with a type following its subtypes. Also updates nextID to just beyond
419 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500420 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400421 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400422 void GenerateModuleInfo(Module &M);
alan-bakera1be3322020-04-20 12:48:18 -0400423 void GeneratePushConstantDescriptorMapEntries(Module &M);
424 void GenerateSpecConstantDescriptorMapEntries(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400425 void GenerateGlobalVar(GlobalVariable &GV);
alan-bakera1be3322020-04-20 12:48:18 -0400426 void GenerateWorkgroupVars(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400427 // Generate descriptor map entries for resource variables associated with
428 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500429 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400430 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400431 // Generate OpVariables for %clspv.resource.var.* calls.
432 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400433 void GenerateFuncPrologue(Function &F);
434 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400435 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400436 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
437 spv::Op GetSPIRVCastOpcode(Instruction &I);
438 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
439 void GenerateInstruction(Instruction &I);
440 void GenerateFuncEpilogue();
441 void HandleDeferredInstruction();
alan-bakera1be3322020-04-20 12:48:18 -0400442 void HandleDeferredDecorations(Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400443 bool is4xi8vec(Type *Ty) const;
444 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400445 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400446 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400447 // Returns the GLSL extended instruction enum that the given function
448 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400449 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400450 // Returns the GLSL extended instruction enum indirectly used by the given
451 // function. That is, to implement the given function, we use an extended
452 // instruction plus one more instruction. If none, then returns the 0 value,
453 // i.e. GLSLstd4580Bad.
454 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
455 // Returns the single GLSL extended instruction used directly or
456 // indirectly by the given function call.
457 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400458 void WriteOneWord(uint32_t Word);
459 void WriteResultID(SPIRVInstruction *Inst);
460 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500461 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400462 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500463 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400464
Alan Baker9bf93fb2018-08-28 16:59:26 -0400465 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500466 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400467
Alan Bakerfcda9482018-10-02 17:09:59 -0400468 // Populate UBO remapped type maps.
469 void PopulateUBOTypeMaps(Module &module);
470
alan-baker06cad652019-12-03 17:56:47 -0500471 // Populate the merge and continue block maps.
472 void PopulateStructuredCFGMaps(Module &module);
473
Alan Bakerfcda9482018-10-02 17:09:59 -0400474 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
475 // uses the internal map, otherwise it falls back on the data layout.
476 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
477 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
478 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000479 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
480 unsigned member,
481 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400482
alan-baker5b86ed72019-02-15 08:26:50 -0500483 // Returns the base pointer of |v|.
484 Value *GetBasePointer(Value *v);
485
486 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
487 // |address_space|.
488 void setVariablePointersCapabilities(unsigned address_space);
489
490 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
491 // variable.
492 bool sameResource(Value *lhs, Value *rhs) const;
493
494 // Returns true if |inst| is phi or select that selects from the same
495 // structure (or null).
496 bool selectFromSameObject(Instruction *inst);
497
alan-bakere9308012019-03-15 10:25:13 -0400498 // Returns true if |Arg| is called with a coherent resource.
499 bool CalledWithCoherentResource(Argument &Arg);
500
David Neto22f144c2017-06-12 14:26:21 -0400501private:
502 static char ID;
David Neto44795152017-07-13 15:45:28 -0400503 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400504 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400505
506 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
507 // convert to other formats on demand?
508
509 // When emitting a C initialization list, the WriteSPIRVBinary method
510 // will actually write its words to this vector via binaryTempOut.
511 SmallVector<char, 100> binaryTempUnderlyingVector;
512 raw_svector_ostream binaryTempOut;
513
514 // Binary output writes to this stream, which might be |out| or
515 // |binaryTempOut|. It's the latter when we really want to write a C
516 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400517 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500518 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400519 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400520 uint64_t patchBoundOffset;
521 uint32_t nextID;
522
alan-bakerf67468c2019-11-25 15:51:49 -0500523 // ID for OpTypeInt 32 1.
524 uint32_t int32ID = 0;
525 // ID for OpTypeVector %int 4.
526 uint32_t v4int32ID = 0;
527
David Neto19a1bad2017-08-25 15:01:41 -0400528 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400529 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400530 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400531 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500532 // A unique-vector of LLVM image types. This list is used to provide
533 // deterministic traversal of image types.
534 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400535 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400536 TypeList Types;
537 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400538 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400539 ValueMapType ValueMap;
540 ValueMapType AllocatedValueMap;
SJW69939d52020-04-16 07:29:07 -0500541 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400542
David Neto22f144c2017-06-12 14:26:21 -0400543 EntryPointVecType EntryPointVec;
544 DeferredInstVecType DeferredInstVec;
545 ValueList EntryPointInterfacesVec;
546 uint32_t OpExtInstImportID;
547 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500548 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400549 bool HasVariablePointers;
550 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500551 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700552
553 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700554 // will map F's type to (G, index of the parameter), where in a first phase
555 // G is F's type. During FindTypePerFunc, G will be changed to F's type
556 // but replacing the pointer-to-constant parameter with
557 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700558 // TODO(dneto): This doesn't seem general enough? A function might have
559 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400560 GlobalConstFuncMapType GlobalConstFuncTypeMap;
561 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400562 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700563 // or array types, and which point into transparent memory (StorageBuffer
564 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400565 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700566 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400567
568 // This is truly ugly, but works around what look like driver bugs.
569 // For get_local_size, an earlier part of the flow has created a module-scope
570 // variable in Private address space to hold the value for the workgroup
571 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
572 // When this is present, save the IDs of the initializer value and variable
573 // in these two variables. We only ever do a vector load from it, and
574 // when we see one of those, substitute just the value of the intializer.
575 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700576 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400577 uint32_t WorkgroupSizeValueID;
578 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400579
David Neto862b7d82018-06-14 18:48:37 -0400580 // Bookkeeping for mapping kernel arguments to resource variables.
581 struct ResourceVarInfo {
582 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400583 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400584 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400585 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400586 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
587 const int index; // Index into ResourceVarInfoList
588 const unsigned descriptor_set;
589 const unsigned binding;
590 Function *const var_fn; // The @clspv.resource.var.* function.
591 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400592 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400593 const unsigned addr_space; // The LLVM address space
594 // The SPIR-V ID of the OpVariable. Not populated at construction time.
595 uint32_t var_id = 0;
596 };
597 // A list of resource var info. Each one correponds to a module-scope
598 // resource variable we will have to create. Resource var indices are
599 // indices into this vector.
600 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
601 // This is a vector of pointers of all the resource vars, but ordered by
602 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500603 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400604 // Map a function to the ordered list of resource variables it uses, one for
605 // each argument. If an argument does not use a resource variable, it
606 // will have a null pointer entry.
607 using FunctionToResourceVarsMapType =
608 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
609 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
610
611 // What LLVM types map to SPIR-V types needing layout? These are the
612 // arrays and structures supporting storage buffers and uniform buffers.
613 TypeList TypesNeedingLayout;
614 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
615 UniqueVector<StructType *> StructTypesNeedingBlock;
616 // For a call that represents a load from an opaque type (samplers, images),
617 // map it to the variable id it should load from.
618 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700619
David Netoc6f3ab22018-04-06 18:02:31 -0400620 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500621 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400622 LocalArgList LocalArgs;
623 // Information about a pointer-to-local argument.
624 struct LocalArgInfo {
625 // The SPIR-V ID of the array variable.
626 uint32_t variable_id;
627 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500628 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400629 // The ID of the array type.
630 uint32_t array_size_id;
631 // The ID of the array type.
632 uint32_t array_type_id;
633 // The ID of the pointer to the array type.
634 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 // The specialization constant ID of the array size.
636 int spec_id;
637 };
Alan Baker202c8c72018-08-13 13:47:44 -0400638 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500639 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400640 // A mapping from SpecId to its LocalArgInfo.
641 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400642 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500643 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400644 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500645 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
646 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500647
648 // Maps basic block to its merge block.
649 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
650 // Maps basic block to its continue block.
651 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400652};
653
654char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400655
alan-bakerb6b09dc2018-11-08 16:59:28 -0500656} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400657
658namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500659ModulePass *createSPIRVProducerPass(
660 raw_pwrite_stream &out,
661 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400662 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500663 bool outputCInitList) {
664 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400665 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400666}
David Netoc2c368d2017-06-30 16:50:17 -0400667} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400668
669bool SPIRVProducerPass::runOnModule(Module &module) {
alan-baker5ed87542020-03-23 11:05:22 -0400670 if (ShowProducerIR) {
671 llvm::outs() << module << "\n";
672 }
David Neto0676e6f2017-07-11 18:47:44 -0400673 binaryOut = outputCInitList ? &binaryTempOut : &out;
674
Alan Bakerfcda9482018-10-02 17:09:59 -0400675 PopulateUBOTypeMaps(module);
alan-baker06cad652019-12-03 17:56:47 -0500676 PopulateStructuredCFGMaps(module);
Alan Bakerfcda9482018-10-02 17:09:59 -0400677
David Neto22f144c2017-06-12 14:26:21 -0400678 // SPIR-V always begins with its header information
679 outputHeader();
680
David Netoc6f3ab22018-04-06 18:02:31 -0400681 const DataLayout &DL = module.getDataLayout();
682
David Neto22f144c2017-06-12 14:26:21 -0400683 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400684 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400685
David Neto22f144c2017-06-12 14:26:21 -0400686 // Collect information on global variables too.
687 for (GlobalVariable &GV : module.globals()) {
688 // If the GV is one of our special __spirv_* variables, remove the
689 // initializer as it was only placed there to force LLVM to not throw the
690 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000691 if (GV.getName().startswith("__spirv_") ||
692 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400693 GV.setInitializer(nullptr);
694 }
695
696 // Collect types' information from global variable.
697 FindTypePerGlobalVar(GV);
698
699 // Collect constant information from global variable.
700 FindConstantPerGlobalVar(GV);
701
702 // If the variable is an input, entry points need to know about it.
703 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400704 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400705 }
706 }
707
708 // If there are extended instructions, generate OpExtInstImport.
709 if (FindExtInst(module)) {
710 GenerateExtInstImport();
711 }
712
713 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400714 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400715
716 // Generate SPIRV constants.
717 GenerateSPIRVConstants();
718
alan-baker09cb9802019-12-10 13:16:27 -0500719 // Generate literal samplers if necessary.
720 GenerateSamplers(module);
David Neto22f144c2017-06-12 14:26:21 -0400721
Kévin Petitbbbda972020-03-03 19:16:31 +0000722 // Generate descriptor map entries for all push constants
alan-bakera1be3322020-04-20 12:48:18 -0400723 GeneratePushConstantDescriptorMapEntries(module);
Kévin Petitbbbda972020-03-03 19:16:31 +0000724
David Neto22f144c2017-06-12 14:26:21 -0400725 // Generate SPIRV variables.
726 for (GlobalVariable &GV : module.globals()) {
727 GenerateGlobalVar(GV);
728 }
David Neto862b7d82018-06-14 18:48:37 -0400729 GenerateResourceVars(module);
alan-bakera1be3322020-04-20 12:48:18 -0400730 GenerateWorkgroupVars(module);
David Neto22f144c2017-06-12 14:26:21 -0400731
732 // Generate SPIRV instructions for each function.
733 for (Function &F : module) {
734 if (F.isDeclaration()) {
735 continue;
736 }
737
David Neto862b7d82018-06-14 18:48:37 -0400738 GenerateDescriptorMapInfo(DL, F);
739
David Neto22f144c2017-06-12 14:26:21 -0400740 // Generate Function Prologue.
741 GenerateFuncPrologue(F);
742
743 // Generate SPIRV instructions for function body.
744 GenerateFuncBody(F);
745
746 // Generate Function Epilogue.
747 GenerateFuncEpilogue();
748 }
749
750 HandleDeferredInstruction();
alan-bakera1be3322020-04-20 12:48:18 -0400751 HandleDeferredDecorations(module);
752
753 // Generate descriptor map entries for module scope specialization constants.
754 GenerateSpecConstantDescriptorMapEntries(module);
David Neto22f144c2017-06-12 14:26:21 -0400755
756 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400757 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400758
alan-baker00e7a582019-06-07 12:54:21 -0400759 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400760
761 // We need to patch the SPIR-V header to set bound correctly.
762 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400763
764 if (outputCInitList) {
765 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400766 std::ostringstream os;
767
David Neto57fb0b92017-08-04 15:35:09 -0400768 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400769 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400770 os << ",\n";
771 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400772 first = false;
773 };
774
775 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400776 const std::string str(binaryTempOut.str());
777 for (unsigned i = 0; i < str.size(); i += 4) {
778 const uint32_t a = static_cast<unsigned char>(str[i]);
779 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
780 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
781 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
782 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400783 }
784 os << "}\n";
785 out << os.str();
786 }
787
David Neto22f144c2017-06-12 14:26:21 -0400788 return false;
789}
790
791void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400792 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
793 sizeof(spv::MagicNumber));
alan-bakere0902602020-03-23 08:43:40 -0400794 const uint32_t spv_version = 0x10000; // SPIR-V 1.0
795 binaryOut->write(reinterpret_cast<const char *>(&spv_version),
796 sizeof(spv_version));
David Neto22f144c2017-06-12 14:26:21 -0400797
alan-baker0c18ab02019-06-12 10:23:21 -0400798 // use Google's vendor ID
799 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400800 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400801
alan-baker00e7a582019-06-07 12:54:21 -0400802 // we record where we need to come back to and patch in the bound value
803 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400804
alan-baker00e7a582019-06-07 12:54:21 -0400805 // output a bad bound for now
806 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400807
alan-baker00e7a582019-06-07 12:54:21 -0400808 // output the schema (reserved for use and must be 0)
809 const uint32_t schema = 0;
810 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400811}
812
813void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400814 // for a binary we just write the value of nextID over bound
815 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
816 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400817}
818
David Netoc6f3ab22018-04-06 18:02:31 -0400819void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400820 // This function generates LLVM IR for function such as global variable for
821 // argument, constant and pointer type for argument access. These information
822 // is artificial one because we need Vulkan SPIR-V output. This function is
823 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400824 LLVMContext &Context = M.getContext();
825
David Neto862b7d82018-06-14 18:48:37 -0400826 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400827
David Neto862b7d82018-06-14 18:48:37 -0400828 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400829
830 bool HasWorkGroupBuiltin = false;
831 for (GlobalVariable &GV : M.globals()) {
832 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
833 if (spv::BuiltInWorkgroupSize == BuiltinType) {
834 HasWorkGroupBuiltin = true;
835 }
836 }
837
David Neto862b7d82018-06-14 18:48:37 -0400838 FindTypesForSamplerMap(M);
839 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400840 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400841
842 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000843 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400844 continue;
845 }
846
847 for (BasicBlock &BB : F) {
848 for (Instruction &I : BB) {
849 if (I.getOpcode() == Instruction::ZExt ||
850 I.getOpcode() == Instruction::SExt ||
851 I.getOpcode() == Instruction::UIToFP) {
852 // If there is zext with i1 type, it will be changed to OpSelect. The
853 // OpSelect needs constant 0 and 1 so the constants are added here.
854
855 auto OpTy = I.getOperand(0)->getType();
856
Kévin Petit24272b62018-10-18 19:16:12 +0000857 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400858 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400859 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000860 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400861 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400862 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000863 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400864 } else {
865 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
866 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
867 }
868 }
869 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400870 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400871
872 // Handle image type specially.
SJW173c7e92020-03-16 08:44:47 -0500873 if (IsImageBuiltin(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400874 TypeMapType &OpImageTypeMap = getImageTypeMap();
875 Type *ImageTy =
876 Call->getArgOperand(0)->getType()->getPointerElementType();
877 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500878 getImageTypeList().insert(ImageTy);
alan-baker75090e42020-02-20 11:21:04 -0500879 }
David Neto22f144c2017-06-12 14:26:21 -0400880
SJW173c7e92020-03-16 08:44:47 -0500881 if (IsSampledImageRead(callee_name)) {
alan-bakerf67468c2019-11-25 15:51:49 -0500882 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400883 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
SJW2c317da2020-03-23 07:39:13 -0500884 } else if (IsUnsampledImageRead(callee_name)) {
alan-baker75090e42020-02-20 11:21:04 -0500885 // All unsampled reads need an integer 0 for the Lod operand.
886 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
SJW2c317da2020-03-23 07:39:13 -0500887 } else if (IsImageQuery(callee_name)) {
alan-bakerce179f12019-12-06 19:02:22 -0500888 Type *ImageTy = Call->getOperand(0)->getType();
889 const uint32_t dim = ImageDimensionality(ImageTy);
alan-baker7150a1d2020-02-25 08:31:06 -0500890 uint32_t components =
891 dim + (clspv::IsArrayImageType(ImageTy) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -0500892 if (components > 1) {
893 // OpImageQuerySize* return |components| components.
894 FindType(VectorType::get(Type::getInt32Ty(Context), components));
895 if (dim == 3 && IsGetImageDim(callee_name)) {
896 // get_image_dim for 3D images returns an int4.
897 FindType(
898 VectorType::get(Type::getInt32Ty(Context), components + 1));
899 }
900 }
901
SJW173c7e92020-03-16 08:44:47 -0500902 if (IsSampledImageType(ImageTy)) {
alan-bakerce179f12019-12-06 19:02:22 -0500903 // All sampled image queries need a integer 0 for the Lod
904 // operand.
905 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
906 }
David Neto5c22a252018-03-15 16:07:41 -0400907 }
David Neto22f144c2017-06-12 14:26:21 -0400908 }
909 }
910 }
911
Kévin Petitabef4522019-03-27 13:08:01 +0000912 // More things to do on kernel functions
913 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
914 if (const MDNode *MD =
915 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
916 // We generate constants if the WorkgroupSize builtin is being used.
917 if (HasWorkGroupBuiltin) {
918 // Collect constant information for work group size.
919 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
920 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
921 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400922 }
923 }
924 }
925
alan-bakerf67468c2019-11-25 15:51:49 -0500926 // TODO(alan-baker): make this better.
alan-bakerf906d2b2019-12-10 11:26:23 -0500927 if (M.getTypeByName("opencl.image1d_ro_t.float") ||
928 M.getTypeByName("opencl.image1d_ro_t.float.sampled") ||
929 M.getTypeByName("opencl.image1d_wo_t.float") ||
930 M.getTypeByName("opencl.image2d_ro_t.float") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500931 M.getTypeByName("opencl.image2d_ro_t.float.sampled") ||
932 M.getTypeByName("opencl.image2d_wo_t.float") ||
933 M.getTypeByName("opencl.image3d_ro_t.float") ||
934 M.getTypeByName("opencl.image3d_ro_t.float.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500935 M.getTypeByName("opencl.image3d_wo_t.float") ||
936 M.getTypeByName("opencl.image1d_array_ro_t.float") ||
937 M.getTypeByName("opencl.image1d_array_ro_t.float.sampled") ||
938 M.getTypeByName("opencl.image1d_array_wo_t.float") ||
939 M.getTypeByName("opencl.image2d_array_ro_t.float") ||
940 M.getTypeByName("opencl.image2d_array_ro_t.float.sampled") ||
941 M.getTypeByName("opencl.image2d_array_wo_t.float")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500942 FindType(Type::getFloatTy(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500943 } else if (M.getTypeByName("opencl.image1d_ro_t.uint") ||
944 M.getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
945 M.getTypeByName("opencl.image1d_wo_t.uint") ||
946 M.getTypeByName("opencl.image2d_ro_t.uint") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500947 M.getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
948 M.getTypeByName("opencl.image2d_wo_t.uint") ||
949 M.getTypeByName("opencl.image3d_ro_t.uint") ||
950 M.getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500951 M.getTypeByName("opencl.image3d_wo_t.uint") ||
952 M.getTypeByName("opencl.image1d_array_ro_t.uint") ||
953 M.getTypeByName("opencl.image1d_array_ro_t.uint.sampled") ||
954 M.getTypeByName("opencl.image1d_array_wo_t.uint") ||
955 M.getTypeByName("opencl.image2d_array_ro_t.uint") ||
956 M.getTypeByName("opencl.image2d_array_ro_t.uint.sampled") ||
957 M.getTypeByName("opencl.image2d_array_wo_t.uint")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500958 FindType(Type::getInt32Ty(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500959 } else if (M.getTypeByName("opencl.image1d_ro_t.int") ||
960 M.getTypeByName("opencl.image1d_ro_t.int.sampled") ||
961 M.getTypeByName("opencl.image1d_wo_t.int") ||
962 M.getTypeByName("opencl.image2d_ro_t.int") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500963 M.getTypeByName("opencl.image2d_ro_t.int.sampled") ||
964 M.getTypeByName("opencl.image2d_wo_t.int") ||
965 M.getTypeByName("opencl.image3d_ro_t.int") ||
966 M.getTypeByName("opencl.image3d_ro_t.int.sampled") ||
alan-baker7150a1d2020-02-25 08:31:06 -0500967 M.getTypeByName("opencl.image3d_wo_t.int") ||
968 M.getTypeByName("opencl.image1d_array_ro_t.int") ||
969 M.getTypeByName("opencl.image1d_array_ro_t.int.sampled") ||
970 M.getTypeByName("opencl.image1d_array_wo_t.int") ||
971 M.getTypeByName("opencl.image2d_array_ro_t.int") ||
972 M.getTypeByName("opencl.image2d_array_ro_t.int.sampled") ||
973 M.getTypeByName("opencl.image2d_array_wo_t.int")) {
alan-bakerf67468c2019-11-25 15:51:49 -0500974 // Nothing for now...
975 } else {
976 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400977 FindType(Type::getFloatTy(Context));
978 }
979
980 // Collect types' information from function.
981 FindTypePerFunc(F);
982
983 // Collect constant information from function.
984 FindConstantPerFunc(F);
985 }
986}
987
David Neto862b7d82018-06-14 18:48:37 -0400988void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400989 clspv::NormalizeGlobalVariables(M);
990
David Neto862b7d82018-06-14 18:48:37 -0400991 SmallVector<GlobalVariable *, 8> GVList;
992 SmallVector<GlobalVariable *, 8> DeadGVList;
993 for (GlobalVariable &GV : M.globals()) {
994 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
995 if (GV.use_empty()) {
996 DeadGVList.push_back(&GV);
997 } else {
998 GVList.push_back(&GV);
999 }
1000 }
1001 }
1002
1003 // Remove dead global __constant variables.
1004 for (auto GV : DeadGVList) {
1005 GV->eraseFromParent();
1006 }
1007 DeadGVList.clear();
1008
1009 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1010 // For now, we only support a single storage buffer.
1011 if (GVList.size() > 0) {
1012 assert(GVList.size() == 1);
1013 const auto *GV = GVList[0];
1014 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -04001015 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -04001016 const size_t kConstantMaxSize = 65536;
1017 if (constants_byte_size > kConstantMaxSize) {
1018 outs() << "Max __constant capacity of " << kConstantMaxSize
1019 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
1020 llvm_unreachable("Max __constant capacity exceeded");
1021 }
1022 }
1023 } else {
1024 // Change global constant variable's address space to ModuleScopePrivate.
1025 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1026 for (auto GV : GVList) {
1027 // Create new gv with ModuleScopePrivate address space.
1028 Type *NewGVTy = GV->getType()->getPointerElementType();
1029 GlobalVariable *NewGV = new GlobalVariable(
1030 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
1031 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1032 NewGV->takeName(GV);
1033
1034 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1035 SmallVector<User *, 8> CandidateUsers;
1036
1037 auto record_called_function_type_as_user =
1038 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1039 // Find argument index.
1040 unsigned index = 0;
1041 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1042 if (gv == call->getOperand(i)) {
1043 // TODO(dneto): Should we break here?
1044 index = i;
1045 }
1046 }
1047
1048 // Record function type with global constant.
1049 GlobalConstFuncTyMap[call->getFunctionType()] =
1050 std::make_pair(call->getFunctionType(), index);
1051 };
1052
1053 for (User *GVU : GVUsers) {
1054 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1055 record_called_function_type_as_user(GV, Call);
1056 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1057 // Check GEP users.
1058 for (User *GEPU : GEP->users()) {
1059 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1060 record_called_function_type_as_user(GEP, GEPCall);
1061 }
1062 }
1063 }
1064
1065 CandidateUsers.push_back(GVU);
1066 }
1067
1068 for (User *U : CandidateUsers) {
1069 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001070 if (!isa<Constant>(U)) {
1071 // #254: Can't change operands of a constant, but this shouldn't be
1072 // something that sticks around in the module.
1073 U->replaceUsesOfWith(GV, NewGV);
1074 }
David Neto862b7d82018-06-14 18:48:37 -04001075 }
1076
1077 // Delete original gv.
1078 GV->eraseFromParent();
1079 }
1080 }
1081}
1082
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001083void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001084 ResourceVarInfoList.clear();
1085 FunctionToResourceVarsMap.clear();
1086 ModuleOrderedResourceVars.reset();
1087 // Normally, there is one resource variable per clspv.resource.var.*
1088 // function, since that is unique'd by arg type and index. By design,
1089 // we can share these resource variables across kernels because all
1090 // kernels use the same descriptor set.
1091 //
1092 // But if the user requested distinct descriptor sets per kernel, then
1093 // the descriptor allocator has made different (set,binding) pairs for
1094 // the same (type,arg_index) pair. Since we can decorate a resource
1095 // variable with only exactly one DescriptorSet and Binding, we are
1096 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +00001097 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -04001098 // (set,binding) values.
1099 const bool always_distinct_sets =
1100 clspv::Option::DistinctKernelDescriptorSets();
1101 for (Function &F : M) {
1102 // Rely on the fact the resource var functions have a stable ordering
1103 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001104 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001105 // Find all calls to this function with distinct set and binding pairs.
1106 // Save them in ResourceVarInfoList.
1107
1108 // Determine uniqueness of the (set,binding) pairs only withing this
1109 // one resource-var builtin function.
1110 using SetAndBinding = std::pair<unsigned, unsigned>;
1111 // Maps set and binding to the resource var info.
1112 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1113 bool first_use = true;
1114 for (auto &U : F.uses()) {
1115 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1116 const auto set = unsigned(
1117 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1118 const auto binding = unsigned(
1119 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1120 const auto arg_kind = clspv::ArgKind(
1121 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1122 const auto arg_index = unsigned(
1123 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001124 const auto coherent = unsigned(
1125 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001126
1127 // Find or make the resource var info for this combination.
1128 ResourceVarInfo *rv = nullptr;
1129 if (always_distinct_sets) {
1130 // Make a new resource var any time we see a different
1131 // (set,binding) pair.
1132 SetAndBinding key{set, binding};
1133 auto where = set_and_binding_map.find(key);
1134 if (where == set_and_binding_map.end()) {
1135 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001136 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001137 ResourceVarInfoList.emplace_back(rv);
1138 set_and_binding_map[key] = rv;
1139 } else {
1140 rv = where->second;
1141 }
1142 } else {
1143 // The default is to make exactly one resource for each
1144 // clspv.resource.var.* function.
1145 if (first_use) {
1146 first_use = false;
1147 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001148 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001149 ResourceVarInfoList.emplace_back(rv);
1150 } else {
1151 rv = ResourceVarInfoList.back().get();
1152 }
1153 }
1154
1155 // Now populate FunctionToResourceVarsMap.
1156 auto &mapping =
1157 FunctionToResourceVarsMap[call->getParent()->getParent()];
1158 while (mapping.size() <= arg_index) {
1159 mapping.push_back(nullptr);
1160 }
1161 mapping[arg_index] = rv;
1162 }
1163 }
1164 }
1165 }
1166
1167 // Populate ModuleOrderedResourceVars.
1168 for (Function &F : M) {
1169 auto where = FunctionToResourceVarsMap.find(&F);
1170 if (where != FunctionToResourceVarsMap.end()) {
1171 for (auto &rv : where->second) {
1172 if (rv != nullptr) {
1173 ModuleOrderedResourceVars.insert(rv);
1174 }
1175 }
1176 }
1177 }
1178 if (ShowResourceVars) {
1179 for (auto *info : ModuleOrderedResourceVars) {
1180 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1181 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1182 << "\n";
1183 }
1184 }
1185}
1186
David Neto22f144c2017-06-12 14:26:21 -04001187bool SPIRVProducerPass::FindExtInst(Module &M) {
1188 LLVMContext &Context = M.getContext();
1189 bool HasExtInst = false;
1190
1191 for (Function &F : M) {
1192 for (BasicBlock &BB : F) {
1193 for (Instruction &I : BB) {
1194 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1195 Function *Callee = Call->getCalledFunction();
1196 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001197 auto callee_name = Callee->getName();
1198 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1199 const glsl::ExtInst IndirectEInst =
1200 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001201
David Neto3fbb4072017-10-16 11:28:14 -04001202 HasExtInst |=
1203 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1204
1205 if (IndirectEInst) {
1206 // Register extra constants if needed.
1207
1208 // Registers a type and constant for computing the result of the
1209 // given instruction. If the result of the instruction is a vector,
1210 // then make a splat vector constant with the same number of
1211 // elements.
1212 auto register_constant = [this, &I](Constant *constant) {
1213 FindType(constant->getType());
1214 FindConstant(constant);
1215 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1216 // Register the splat vector of the value with the same
1217 // width as the result of the instruction.
1218 auto *vec_constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04001219 {static_cast<unsigned>(vectorTy->getNumElements()), false},
David Neto3fbb4072017-10-16 11:28:14 -04001220 constant);
1221 FindConstant(vec_constant);
1222 FindType(vec_constant->getType());
1223 }
1224 };
1225 switch (IndirectEInst) {
1226 case glsl::ExtInstFindUMsb:
1227 // clz needs OpExtInst and OpISub with constant 31, or splat
1228 // vector of 31. Add it to the constant list here.
1229 register_constant(
1230 ConstantInt::get(Type::getInt32Ty(Context), 31));
1231 break;
1232 case glsl::ExtInstAcos:
1233 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001234 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001235 case glsl::ExtInstAtan2:
1236 // We need 1/pi for acospi, asinpi, atan2pi.
1237 register_constant(
1238 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1239 break;
1240 default:
1241 assert(false && "internally inconsistent");
1242 }
David Neto22f144c2017-06-12 14:26:21 -04001243 }
1244 }
1245 }
1246 }
1247 }
1248
1249 return HasExtInst;
1250}
1251
1252void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1253 // Investigate global variable's type.
1254 FindType(GV.getType());
1255}
1256
1257void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1258 // Investigate function's type.
1259 FunctionType *FTy = F.getFunctionType();
1260
1261 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1262 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001263 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001264 if (GlobalConstFuncTyMap.count(FTy)) {
1265 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1266 SmallVector<Type *, 4> NewFuncParamTys;
1267 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1268 Type *ParamTy = FTy->getParamType(i);
1269 if (i == GVCstArgIdx) {
1270 Type *EleTy = ParamTy->getPointerElementType();
1271 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1272 }
1273
1274 NewFuncParamTys.push_back(ParamTy);
1275 }
1276
1277 FunctionType *NewFTy =
1278 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1279 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1280 FTy = NewFTy;
1281 }
1282
1283 FindType(FTy);
1284 } else {
1285 // As kernel functions do not have parameters, create new function type and
1286 // add it to type map.
1287 SmallVector<Type *, 4> NewFuncParamTys;
1288 FunctionType *NewFTy =
1289 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1290 FindType(NewFTy);
1291 }
1292
1293 // Investigate instructions' type in function body.
1294 for (BasicBlock &BB : F) {
1295 for (Instruction &I : BB) {
1296 if (isa<ShuffleVectorInst>(I)) {
1297 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1298 // Ignore type for mask of shuffle vector instruction.
1299 if (i == 2) {
1300 continue;
1301 }
1302
1303 Value *Op = I.getOperand(i);
1304 if (!isa<MetadataAsValue>(Op)) {
1305 FindType(Op->getType());
1306 }
1307 }
1308
1309 FindType(I.getType());
1310 continue;
1311 }
1312
David Neto862b7d82018-06-14 18:48:37 -04001313 CallInst *Call = dyn_cast<CallInst>(&I);
1314
1315 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001316 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001317 // This is a fake call representing access to a resource variable.
1318 // We handle that elsewhere.
1319 continue;
1320 }
1321
Alan Baker202c8c72018-08-13 13:47:44 -04001322 if (Call && Call->getCalledFunction()->getName().startswith(
1323 clspv::WorkgroupAccessorFunction())) {
1324 // This is a fake call representing access to a workgroup variable.
1325 // We handle that elsewhere.
1326 continue;
1327 }
1328
alan-bakerf083bed2020-01-29 08:15:42 -05001329 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1330 // OpCompositeExtract which takes literal values for indices. As a result
1331 // don't map the type of indices.
1332 if (I.getOpcode() == Instruction::ExtractValue) {
1333 FindType(I.getOperand(0)->getType());
1334 continue;
1335 }
1336 if (I.getOpcode() == Instruction::InsertValue) {
1337 FindType(I.getOperand(0)->getType());
1338 FindType(I.getOperand(1)->getType());
1339 continue;
1340 }
1341
1342 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1343 // the index is a constant. In such a case don't map the index type.
1344 if (I.getOpcode() == Instruction::ExtractElement) {
1345 FindType(I.getOperand(0)->getType());
1346 Value *op1 = I.getOperand(1);
1347 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1348 FindType(op1->getType());
1349 }
1350 continue;
1351 }
1352 if (I.getOpcode() == Instruction::InsertElement) {
1353 FindType(I.getOperand(0)->getType());
1354 FindType(I.getOperand(1)->getType());
1355 Value *op2 = I.getOperand(2);
1356 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1357 FindType(op2->getType());
1358 }
1359 continue;
1360 }
1361
David Neto22f144c2017-06-12 14:26:21 -04001362 // Work through the operands of the instruction.
1363 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1364 Value *const Op = I.getOperand(i);
1365 // If any of the operands is a constant, find the type!
1366 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1367 FindType(Op->getType());
1368 }
1369 }
1370
1371 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001372 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001373 // Avoid to check call instruction's type.
1374 break;
1375 }
Alan Baker202c8c72018-08-13 13:47:44 -04001376 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1377 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1378 clspv::WorkgroupAccessorFunction())) {
1379 // This is a fake call representing access to a workgroup variable.
1380 // We handle that elsewhere.
1381 continue;
1382 }
1383 }
David Neto22f144c2017-06-12 14:26:21 -04001384 if (!isa<MetadataAsValue>(&Op)) {
1385 FindType(Op->getType());
1386 continue;
1387 }
1388 }
1389
David Neto22f144c2017-06-12 14:26:21 -04001390 // We don't want to track the type of this call as we are going to replace
1391 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001392 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001393 Call->getCalledFunction()->getName())) {
1394 continue;
1395 }
1396
1397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1398 // If gep's base operand has ModuleScopePrivate address space, make gep
1399 // return ModuleScopePrivate address space.
1400 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1401 // Add pointer type with private address space for global constant to
1402 // type list.
1403 Type *EleTy = I.getType()->getPointerElementType();
1404 Type *NewPTy =
1405 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1406
1407 FindType(NewPTy);
1408 continue;
1409 }
1410 }
1411
1412 FindType(I.getType());
1413 }
1414 }
1415}
1416
David Neto862b7d82018-06-14 18:48:37 -04001417void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1418 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001419 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001420 0 < getSamplerMap().size()) {
1421 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1422 if (!SamplerStructTy) {
1423 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1424 }
1425
1426 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1427
1428 FindType(SamplerTy);
1429 }
1430}
1431
1432void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1433 // Record types so they are generated.
1434 TypesNeedingLayout.reset();
1435 StructTypesNeedingBlock.reset();
1436
1437 // To match older clspv codegen, generate the float type first if required
1438 // for images.
1439 for (const auto *info : ModuleOrderedResourceVars) {
1440 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1441 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001442 if (IsIntImageType(info->var_fn->getReturnType())) {
1443 // Nothing for now...
1444 } else if (IsUintImageType(info->var_fn->getReturnType())) {
1445 FindType(Type::getInt32Ty(M.getContext()));
1446 }
1447
1448 // We need "float" either for the sampled type or for the Lod operand.
David Neto862b7d82018-06-14 18:48:37 -04001449 FindType(Type::getFloatTy(M.getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001450 }
1451 }
1452
1453 for (const auto *info : ModuleOrderedResourceVars) {
1454 Type *type = info->var_fn->getReturnType();
1455
1456 switch (info->arg_kind) {
1457 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001458 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001459 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1460 StructTypesNeedingBlock.insert(sty);
1461 } else {
1462 errs() << *type << "\n";
1463 llvm_unreachable("Buffer arguments must map to structures!");
1464 }
1465 break;
1466 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001467 case clspv::ArgKind::PodUBO:
1468 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001469 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1470 StructTypesNeedingBlock.insert(sty);
1471 } else {
1472 errs() << *type << "\n";
1473 llvm_unreachable("POD arguments must map to structures!");
1474 }
1475 break;
1476 case clspv::ArgKind::ReadOnlyImage:
1477 case clspv::ArgKind::WriteOnlyImage:
1478 case clspv::ArgKind::Sampler:
1479 // Sampler and image types map to the pointee type but
1480 // in the uniform constant address space.
1481 type = PointerType::get(type->getPointerElementType(),
1482 clspv::AddressSpace::UniformConstant);
1483 break;
1484 default:
1485 break;
1486 }
1487
1488 // The converted type is the type of the OpVariable we will generate.
1489 // If the pointee type is an array of size zero, FindType will convert it
1490 // to a runtime array.
1491 FindType(type);
1492 }
1493
alan-bakerdcd97412019-09-16 15:32:30 -04001494 // If module constants are clustered in a storage buffer then that struct
1495 // needs layout decorations.
1496 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1497 for (GlobalVariable &GV : M.globals()) {
1498 PointerType *PTy = cast<PointerType>(GV.getType());
1499 const auto AS = PTy->getAddressSpace();
1500 const bool module_scope_constant_external_init =
1501 (AS == AddressSpace::Constant) && GV.hasInitializer();
1502 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1503 if (module_scope_constant_external_init &&
1504 spv::BuiltInMax == BuiltinType) {
1505 StructTypesNeedingBlock.insert(
1506 cast<StructType>(PTy->getPointerElementType()));
1507 }
1508 }
1509 }
1510
Kévin Petitbbbda972020-03-03 19:16:31 +00001511 for (const GlobalVariable &GV : M.globals()) {
1512 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1513 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1514 assert(Ty->isStructTy() && "Push constants have to be structures.");
1515 auto STy = cast<StructType>(Ty);
1516 StructTypesNeedingBlock.insert(STy);
1517 }
1518 }
1519
David Neto862b7d82018-06-14 18:48:37 -04001520 // Traverse the arrays and structures underneath each Block, and
1521 // mark them as needing layout.
1522 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1523 StructTypesNeedingBlock.end());
1524 while (!work_list.empty()) {
1525 Type *type = work_list.back();
1526 work_list.pop_back();
1527 TypesNeedingLayout.insert(type);
1528 switch (type->getTypeID()) {
1529 case Type::ArrayTyID:
1530 work_list.push_back(type->getArrayElementType());
1531 if (!Hack_generate_runtime_array_stride_early) {
1532 // Remember this array type for deferred decoration.
1533 TypesNeedingArrayStride.insert(type);
1534 }
1535 break;
1536 case Type::StructTyID:
1537 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1538 work_list.push_back(elem_ty);
1539 }
1540 default:
1541 // This type and its contained types don't get layout.
1542 break;
1543 }
1544 }
1545}
1546
Alan Baker202c8c72018-08-13 13:47:44 -04001547void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1548 // The SpecId assignment for pointer-to-local arguments is recorded in
1549 // module-level metadata. Translate that information into local argument
1550 // information.
1551 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001552 if (!nmd)
1553 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001554 for (auto operand : nmd->operands()) {
1555 MDTuple *tuple = cast<MDTuple>(operand);
1556 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1557 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001558 ConstantAsMetadata *arg_index_md =
1559 cast<ConstantAsMetadata>(tuple->getOperand(1));
1560 int arg_index = static_cast<int>(
1561 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1562 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001563
1564 ConstantAsMetadata *spec_id_md =
1565 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001566 int spec_id = static_cast<int>(
1567 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001568
Alan Baker202c8c72018-08-13 13:47:44 -04001569 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001570 if (LocalSpecIdInfoMap.count(spec_id))
1571 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001572
1573 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1574 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1575 nextID + 1, nextID + 2,
1576 nextID + 3, spec_id};
1577 LocalSpecIdInfoMap[spec_id] = info;
1578 nextID += 4;
1579
1580 // Ensure the types necessary for this argument get generated.
1581 Type *IdxTy = Type::getInt32Ty(M.getContext());
1582 FindConstant(ConstantInt::get(IdxTy, 0));
1583 FindType(IdxTy);
1584 FindType(arg->getType());
1585 }
1586}
1587
David Neto22f144c2017-06-12 14:26:21 -04001588void SPIRVProducerPass::FindType(Type *Ty) {
1589 TypeList &TyList = getTypeList();
1590
1591 if (0 != TyList.idFor(Ty)) {
1592 return;
1593 }
1594
1595 if (Ty->isPointerTy()) {
1596 auto AddrSpace = Ty->getPointerAddressSpace();
1597 if ((AddressSpace::Constant == AddrSpace) ||
1598 (AddressSpace::Global == AddrSpace)) {
1599 auto PointeeTy = Ty->getPointerElementType();
1600
1601 if (PointeeTy->isStructTy() &&
1602 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1603 FindType(PointeeTy);
1604 auto ActualPointerTy =
1605 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1606 FindType(ActualPointerTy);
1607 return;
1608 }
1609 }
1610 }
1611
David Neto862b7d82018-06-14 18:48:37 -04001612 // By convention, LLVM array type with 0 elements will map to
1613 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1614 // has a constant number of elements. We need to support type of the
1615 // constant.
1616 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1617 if (arrayTy->getNumElements() > 0) {
1618 LLVMContext &Context = Ty->getContext();
1619 FindType(Type::getInt32Ty(Context));
1620 }
David Neto22f144c2017-06-12 14:26:21 -04001621 }
1622
1623 for (Type *SubTy : Ty->subtypes()) {
1624 FindType(SubTy);
1625 }
1626
1627 TyList.insert(Ty);
1628}
1629
1630void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1631 // If the global variable has a (non undef) initializer.
1632 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001633 // Generate the constant if it's not the initializer to a module scope
1634 // constant that we will expect in a storage buffer.
1635 const bool module_scope_constant_external_init =
1636 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1637 clspv::Option::ModuleConstantsInStorageBuffer();
1638 if (!module_scope_constant_external_init) {
1639 FindConstant(GV.getInitializer());
1640 }
David Neto22f144c2017-06-12 14:26:21 -04001641 }
1642}
1643
1644void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1645 // Investigate constants in function body.
1646 for (BasicBlock &BB : F) {
1647 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001648 if (auto *call = dyn_cast<CallInst>(&I)) {
1649 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001650 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001651 // We've handled these constants elsewhere, so skip it.
1652 continue;
1653 }
Alan Baker202c8c72018-08-13 13:47:44 -04001654 if (name.startswith(clspv::ResourceAccessorFunction())) {
1655 continue;
1656 }
1657 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001658 continue;
1659 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001660 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1661 // Skip the first operand that has the SPIR-V Opcode
1662 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1663 if (isa<Constant>(I.getOperand(i)) &&
1664 !isa<GlobalValue>(I.getOperand(i))) {
1665 FindConstant(I.getOperand(i));
1666 }
1667 }
1668 continue;
1669 }
David Neto22f144c2017-06-12 14:26:21 -04001670 }
1671
1672 if (isa<AllocaInst>(I)) {
1673 // Alloca instruction has constant for the number of element. Ignore it.
1674 continue;
1675 } else if (isa<ShuffleVectorInst>(I)) {
1676 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1677 // Ignore constant for mask of shuffle vector instruction.
1678 if (i == 2) {
1679 continue;
1680 }
1681
1682 if (isa<Constant>(I.getOperand(i)) &&
1683 !isa<GlobalValue>(I.getOperand(i))) {
1684 FindConstant(I.getOperand(i));
1685 }
1686 }
1687
1688 continue;
1689 } else if (isa<InsertElementInst>(I)) {
1690 // Handle InsertElement with <4 x i8> specially.
1691 Type *CompositeTy = I.getOperand(0)->getType();
1692 if (is4xi8vec(CompositeTy)) {
1693 LLVMContext &Context = CompositeTy->getContext();
1694 if (isa<Constant>(I.getOperand(0))) {
1695 FindConstant(I.getOperand(0));
1696 }
1697
1698 if (isa<Constant>(I.getOperand(1))) {
1699 FindConstant(I.getOperand(1));
1700 }
1701
1702 // Add mask constant 0xFF.
1703 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1704 FindConstant(CstFF);
1705
1706 // Add shift amount constant.
1707 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1708 uint64_t Idx = CI->getZExtValue();
1709 Constant *CstShiftAmount =
1710 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1711 FindConstant(CstShiftAmount);
1712 }
1713
1714 continue;
1715 }
1716
1717 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1718 // Ignore constant for index of InsertElement instruction.
1719 if (i == 2) {
1720 continue;
1721 }
1722
1723 if (isa<Constant>(I.getOperand(i)) &&
1724 !isa<GlobalValue>(I.getOperand(i))) {
1725 FindConstant(I.getOperand(i));
1726 }
1727 }
1728
1729 continue;
1730 } else if (isa<ExtractElementInst>(I)) {
1731 // Handle ExtractElement with <4 x i8> specially.
1732 Type *CompositeTy = I.getOperand(0)->getType();
1733 if (is4xi8vec(CompositeTy)) {
1734 LLVMContext &Context = CompositeTy->getContext();
1735 if (isa<Constant>(I.getOperand(0))) {
1736 FindConstant(I.getOperand(0));
1737 }
1738
1739 // Add mask constant 0xFF.
1740 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1741 FindConstant(CstFF);
1742
1743 // Add shift amount constant.
1744 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1745 uint64_t Idx = CI->getZExtValue();
1746 Constant *CstShiftAmount =
1747 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1748 FindConstant(CstShiftAmount);
1749 } else {
1750 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1751 FindConstant(Cst8);
1752 }
1753
1754 continue;
1755 }
1756
1757 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1758 // Ignore constant for index of ExtractElement instruction.
1759 if (i == 1) {
1760 continue;
1761 }
1762
1763 if (isa<Constant>(I.getOperand(i)) &&
1764 !isa<GlobalValue>(I.getOperand(i))) {
1765 FindConstant(I.getOperand(i));
1766 }
1767 }
1768
1769 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001770 } else if ((Instruction::Xor == I.getOpcode()) &&
1771 I.getType()->isIntegerTy(1)) {
1772 // We special case for Xor where the type is i1 and one of the arguments
1773 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1774 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001775 bool foundConstantTrue = false;
1776 for (Use &Op : I.operands()) {
1777 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1778 auto CI = cast<ConstantInt>(Op);
1779
1780 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001781 // If we already found the true constant, we might (probably only
1782 // on -O0) have an OpLogicalNot which is taking a constant
1783 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001784 FindConstant(Op);
1785 } else {
1786 foundConstantTrue = true;
1787 }
1788 }
1789 }
1790
1791 continue;
David Netod2de94a2017-08-28 17:27:47 -04001792 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001793 // Special case if i8 is not generally handled.
1794 if (!clspv::Option::Int8Support()) {
1795 // For truncation to i8 we mask against 255.
1796 Type *ToTy = I.getType();
1797 if (8u == ToTy->getPrimitiveSizeInBits()) {
1798 LLVMContext &Context = ToTy->getContext();
1799 Constant *Cst255 =
1800 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1801 FindConstant(Cst255);
1802 }
David Netod2de94a2017-08-28 17:27:47 -04001803 }
Neil Henning39672102017-09-29 14:33:13 +01001804 } else if (isa<AtomicRMWInst>(I)) {
1805 LLVMContext &Context = I.getContext();
1806
1807 FindConstant(
1808 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1809 FindConstant(ConstantInt::get(
1810 Type::getInt32Ty(Context),
1811 spv::MemorySemanticsUniformMemoryMask |
1812 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001813 }
1814
1815 for (Use &Op : I.operands()) {
1816 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1817 FindConstant(Op);
1818 }
1819 }
1820 }
1821 }
1822}
1823
1824void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001825 ValueList &CstList = getConstantList();
1826
David Netofb9a7972017-08-25 17:08:24 -04001827 // If V is already tracked, ignore it.
1828 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001829 return;
1830 }
1831
David Neto862b7d82018-06-14 18:48:37 -04001832 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1833 return;
1834 }
1835
David Neto22f144c2017-06-12 14:26:21 -04001836 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001837 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001838
1839 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001840 if (is4xi8vec(CstTy)) {
1841 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001842 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001843 }
1844 }
1845
1846 if (Cst->getNumOperands()) {
1847 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1848 ++I) {
1849 FindConstant(*I);
1850 }
1851
David Netofb9a7972017-08-25 17:08:24 -04001852 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001853 return;
1854 } else if (const ConstantDataSequential *CDS =
1855 dyn_cast<ConstantDataSequential>(Cst)) {
1856 // Add constants for each element to constant list.
1857 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1858 Constant *EleCst = CDS->getElementAsConstant(i);
1859 FindConstant(EleCst);
1860 }
1861 }
1862
1863 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001864 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001865 }
1866}
1867
1868spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1869 switch (AddrSpace) {
1870 default:
1871 llvm_unreachable("Unsupported OpenCL address space");
1872 case AddressSpace::Private:
1873 return spv::StorageClassFunction;
1874 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001875 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001876 case AddressSpace::Constant:
1877 return clspv::Option::ConstantArgsInUniformBuffer()
1878 ? spv::StorageClassUniform
1879 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001880 case AddressSpace::Input:
1881 return spv::StorageClassInput;
1882 case AddressSpace::Local:
1883 return spv::StorageClassWorkgroup;
1884 case AddressSpace::UniformConstant:
1885 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001886 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001887 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001888 case AddressSpace::ModuleScopePrivate:
1889 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001890 case AddressSpace::PushConstant:
1891 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001892 }
1893}
1894
David Neto862b7d82018-06-14 18:48:37 -04001895spv::StorageClass
1896SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1897 switch (arg_kind) {
1898 case clspv::ArgKind::Buffer:
1899 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001900 case clspv::ArgKind::BufferUBO:
1901 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001902 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001903 return spv::StorageClassStorageBuffer;
1904 case clspv::ArgKind::PodUBO:
1905 return spv::StorageClassUniform;
1906 case clspv::ArgKind::PodPushConstant:
1907 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001908 case clspv::ArgKind::Local:
1909 return spv::StorageClassWorkgroup;
1910 case clspv::ArgKind::ReadOnlyImage:
1911 case clspv::ArgKind::WriteOnlyImage:
1912 case clspv::ArgKind::Sampler:
1913 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001914 default:
1915 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001916 }
1917}
1918
David Neto22f144c2017-06-12 14:26:21 -04001919spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1920 return StringSwitch<spv::BuiltIn>(Name)
1921 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1922 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1923 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1924 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1925 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1926 .Default(spv::BuiltInMax);
1927}
1928
1929void SPIRVProducerPass::GenerateExtInstImport() {
SJW69939d52020-04-16 07:29:07 -05001930 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kImports);
David Neto22f144c2017-06-12 14:26:21 -04001931 uint32_t &ExtInstImportID = getOpExtInstImportID();
1932
1933 //
1934 // Generate OpExtInstImport.
1935 //
1936 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001937 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001938 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1939 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001940}
1941
alan-bakerb6b09dc2018-11-08 16:59:28 -05001942void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1943 Module &module) {
SJW69939d52020-04-16 07:29:07 -05001944 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kTypes);
David Neto22f144c2017-06-12 14:26:21 -04001945 ValueMapType &VMap = getValueMap();
1946 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001947 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001948
1949 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1950 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1951 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1952
1953 for (Type *Ty : getTypeList()) {
1954 // Update TypeMap with nextID for reference later.
1955 TypeMap[Ty] = nextID;
1956
1957 switch (Ty->getTypeID()) {
1958 default: {
1959 Ty->print(errs());
1960 llvm_unreachable("Unsupported type???");
1961 break;
1962 }
1963 case Type::MetadataTyID:
1964 case Type::LabelTyID: {
1965 // Ignore these types.
1966 break;
1967 }
1968 case Type::PointerTyID: {
1969 PointerType *PTy = cast<PointerType>(Ty);
1970 unsigned AddrSpace = PTy->getAddressSpace();
1971
1972 // For the purposes of our Vulkan SPIR-V type system, constant and global
1973 // are conflated.
1974 bool UseExistingOpTypePointer = false;
1975 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001976 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1977 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001978 // Check to see if we already created this type (for instance, if we
1979 // had a constant <type>* and a global <type>*, the type would be
1980 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001981 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1982 if (0 < TypeMap.count(GlobalTy)) {
1983 TypeMap[PTy] = TypeMap[GlobalTy];
1984 UseExistingOpTypePointer = true;
1985 break;
1986 }
David Neto22f144c2017-06-12 14:26:21 -04001987 }
1988 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001989 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1990 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001991
alan-bakerb6b09dc2018-11-08 16:59:28 -05001992 // Check to see if we already created this type (for instance, if we
1993 // had a constant <type>* and a global <type>*, the type would be
1994 // created by one of these types, and shared by both).
1995 auto ConstantTy =
1996 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001997 if (0 < TypeMap.count(ConstantTy)) {
1998 TypeMap[PTy] = TypeMap[ConstantTy];
1999 UseExistingOpTypePointer = true;
2000 }
David Neto22f144c2017-06-12 14:26:21 -04002001 }
2002 }
2003
David Neto862b7d82018-06-14 18:48:37 -04002004 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04002005
David Neto862b7d82018-06-14 18:48:37 -04002006 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04002007 //
2008 // Generate OpTypePointer.
2009 //
2010
2011 // OpTypePointer
2012 // Ops[0] = Storage Class
2013 // Ops[1] = Element Type ID
2014 SPIRVOperandList Ops;
2015
David Neto257c3892018-04-11 13:19:45 -04002016 Ops << MkNum(GetStorageClass(AddrSpace))
2017 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04002018
David Neto87846742018-04-11 17:36:22 -04002019 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002020 SPIRVInstList.push_back(Inst);
2021 }
David Neto22f144c2017-06-12 14:26:21 -04002022 break;
2023 }
2024 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002025 StructType *STy = cast<StructType>(Ty);
2026
2027 // Handle sampler type.
2028 if (STy->isOpaque()) {
2029 if (STy->getName().equals("opencl.sampler_t")) {
2030 //
2031 // Generate OpTypeSampler
2032 //
2033 // Empty Ops.
2034 SPIRVOperandList Ops;
2035
David Neto87846742018-04-11 17:36:22 -04002036 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002037 SPIRVInstList.push_back(Inst);
2038 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05002039 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
2040 STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002041 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2042 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05002043 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002044 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002045 STy->getName().startswith("opencl.image2d_array_ro_t") ||
2046 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05002047 STy->getName().startswith("opencl.image3d_ro_t") ||
2048 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002049 //
2050 // Generate OpTypeImage
2051 //
2052 // Ops[0] = Sampled Type ID
2053 // Ops[1] = Dim ID
2054 // Ops[2] = Depth (Literal Number)
2055 // Ops[3] = Arrayed (Literal Number)
2056 // Ops[4] = MS (Literal Number)
2057 // Ops[5] = Sampled (Literal Number)
2058 // Ops[6] = Image Format ID
2059 //
2060 SPIRVOperandList Ops;
2061
alan-bakerf67468c2019-11-25 15:51:49 -05002062 uint32_t ImageTyID = nextID++;
2063 uint32_t SampledTyID = 0;
2064 if (STy->getName().contains(".float")) {
2065 SampledTyID = lookupType(Type::getFloatTy(Context));
2066 } else if (STy->getName().contains(".uint")) {
2067 SampledTyID = lookupType(Type::getInt32Ty(Context));
2068 } else if (STy->getName().contains(".int")) {
2069 // Generate a signed 32-bit integer if necessary.
2070 if (int32ID == 0) {
2071 int32ID = nextID++;
2072 SPIRVOperandList intOps;
2073 intOps << MkNum(32);
2074 intOps << MkNum(1);
2075 auto signed_int =
2076 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
2077 SPIRVInstList.push_back(signed_int);
2078 }
2079 SampledTyID = int32ID;
2080
2081 // Generate a vec4 of the signed int if necessary.
2082 if (v4int32ID == 0) {
2083 v4int32ID = nextID++;
2084 SPIRVOperandList vecOps;
2085 vecOps << MkId(int32ID);
2086 vecOps << MkNum(4);
2087 auto int_vec =
2088 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
2089 SPIRVInstList.push_back(int_vec);
2090 }
2091 } else {
2092 // This was likely an UndefValue.
2093 SampledTyID = lookupType(Type::getFloatTy(Context));
2094 }
David Neto257c3892018-04-11 13:19:45 -04002095 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04002096
2097 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05002098 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05002099 STy->getName().startswith("opencl.image1d_wo_t") ||
2100 STy->getName().startswith("opencl.image1d_array_ro_t") ||
2101 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05002102 DimID = spv::Dim1D;
2103 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
2104 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002105 DimID = spv::Dim3D;
2106 }
David Neto257c3892018-04-11 13:19:45 -04002107 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04002108
2109 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04002110 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002111
alan-baker7150a1d2020-02-25 08:31:06 -05002112 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
2113 Ops << MkNum(arrayed);
David Neto22f144c2017-06-12 14:26:21 -04002114
2115 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04002116 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04002117
alan-baker7150a1d2020-02-25 08:31:06 -05002118 // Set up Sampled.
David Neto22f144c2017-06-12 14:26:21 -04002119 //
2120 // From Spec
2121 //
2122 // 0 indicates this is only known at run time, not at compile time
2123 // 1 indicates will be used with sampler
2124 // 2 indicates will be used without a sampler (a storage image)
2125 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002126 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002127 Sampled = 2;
2128 }
David Neto257c3892018-04-11 13:19:45 -04002129 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002130
2131 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002132 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002133
alan-bakerf67468c2019-11-25 15:51:49 -05002134 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002135 SPIRVInstList.push_back(Inst);
2136 break;
2137 }
2138 }
2139
2140 //
2141 // Generate OpTypeStruct
2142 //
2143 // Ops[0] ... Ops[n] = Member IDs
2144 SPIRVOperandList Ops;
2145
2146 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002147 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002148 }
2149
David Neto22f144c2017-06-12 14:26:21 -04002150 uint32_t STyID = nextID;
2151
alan-bakerb6b09dc2018-11-08 16:59:28 -05002152 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002153 SPIRVInstList.push_back(Inst);
2154
2155 // Generate OpMemberDecorate.
Kévin Petitbbbda972020-03-03 19:16:31 +00002156 if (TypesNeedingLayout.idFor(STy)) {
2157 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2158 MemberIdx++) {
2159 // Ops[0] = Structure Type ID
2160 // Ops[1] = Member Index(Literal Number)
2161 // Ops[2] = Decoration (Offset)
2162 // Ops[3] = Byte Offset (Literal Number)
2163 Ops.clear();
David Netoc463b372017-08-10 15:32:21 -04002164
Kévin Petitbbbda972020-03-03 19:16:31 +00002165 Ops << MkId(STyID) << MkNum(MemberIdx)
2166 << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002167
Kévin Petitbbbda972020-03-03 19:16:31 +00002168 const auto ByteOffset =
2169 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
David Neto22f144c2017-06-12 14:26:21 -04002170
Kévin Petitbbbda972020-03-03 19:16:31 +00002171 Ops << MkNum(ByteOffset);
2172
2173 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002174 getSPIRVInstList(kAnnotations).push_back(DecoInst);
Alan Bakerfcda9482018-10-02 17:09:59 -04002175 }
David Neto22f144c2017-06-12 14:26:21 -04002176 }
2177
2178 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002179 if (StructTypesNeedingBlock.idFor(STy)) {
2180 Ops.clear();
2181 // Use Block decorations with StorageBuffer storage class.
2182 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002183
David Neto862b7d82018-06-14 18:48:37 -04002184 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002185 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002186 }
2187 break;
2188 }
2189 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002190 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002191
2192 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002193 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002194 SPIRVInstList.push_back(Inst);
2195 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002196 if (!clspv::Option::Int8Support()) {
2197 // i8 is added to TypeMap as i32.
2198 // No matter what LLVM type is requested first, always alias the
2199 // second one's SPIR-V type to be the same as the one we generated
2200 // first.
2201 unsigned aliasToWidth = 0;
2202 if (BitWidth == 8) {
2203 aliasToWidth = 32;
2204 BitWidth = 32;
2205 } else if (BitWidth == 32) {
2206 aliasToWidth = 8;
2207 }
2208 if (aliasToWidth) {
2209 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2210 auto where = TypeMap.find(otherType);
2211 if (where == TypeMap.end()) {
2212 // Go ahead and make it, but also map the other type to it.
2213 TypeMap[otherType] = nextID;
2214 } else {
2215 // Alias this SPIR-V type the existing type.
2216 TypeMap[Ty] = where->second;
2217 break;
2218 }
David Neto391aeb12017-08-26 15:51:58 -04002219 }
David Neto22f144c2017-06-12 14:26:21 -04002220 }
2221
David Neto257c3892018-04-11 13:19:45 -04002222 SPIRVOperandList Ops;
2223 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002224
2225 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002226 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002227 }
2228 break;
2229 }
2230 case Type::HalfTyID:
2231 case Type::FloatTyID:
2232 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002233 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002234 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002235
2236 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002237 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002238 break;
2239 }
2240 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002241 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002242 const uint64_t Length = ArrTy->getArrayNumElements();
2243 if (Length == 0) {
2244 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002245
David Neto862b7d82018-06-14 18:48:37 -04002246 // Only generate the type once.
2247 // TODO(dneto): Can it ever be generated more than once?
2248 // Doesn't LLVM type uniqueness guarantee we'll only see this
2249 // once?
2250 Type *EleTy = ArrTy->getArrayElementType();
2251 if (OpRuntimeTyMap.count(EleTy) == 0) {
2252 uint32_t OpTypeRuntimeArrayID = nextID;
2253 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002254
David Neto862b7d82018-06-14 18:48:37 -04002255 //
2256 // Generate OpTypeRuntimeArray.
2257 //
David Neto22f144c2017-06-12 14:26:21 -04002258
David Neto862b7d82018-06-14 18:48:37 -04002259 // OpTypeRuntimeArray
2260 // Ops[0] = Element Type ID
2261 SPIRVOperandList Ops;
2262 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002263
David Neto862b7d82018-06-14 18:48:37 -04002264 SPIRVInstList.push_back(
2265 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto862b7d82018-06-14 18:48:37 -04002267 if (Hack_generate_runtime_array_stride_early) {
2268 // Generate OpDecorate.
David Neto22f144c2017-06-12 14:26:21 -04002269
David Neto862b7d82018-06-14 18:48:37 -04002270 // Ops[0] = Target ID
2271 // Ops[1] = Decoration (ArrayStride)
2272 // Ops[2] = Stride Number(Literal Number)
2273 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002274
David Neto862b7d82018-06-14 18:48:37 -04002275 Ops << MkId(OpTypeRuntimeArrayID)
2276 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002277 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002278
David Neto862b7d82018-06-14 18:48:37 -04002279 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002280 getSPIRVInstList(kAnnotations).push_back(DecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002281 }
2282 }
David Neto22f144c2017-06-12 14:26:21 -04002283
David Neto862b7d82018-06-14 18:48:37 -04002284 } else {
David Neto22f144c2017-06-12 14:26:21 -04002285
David Neto862b7d82018-06-14 18:48:37 -04002286 //
2287 // Generate OpConstant and OpTypeArray.
2288 //
2289
2290 //
2291 // Generate OpConstant for array length.
2292 //
2293 // Ops[0] = Result Type ID
2294 // Ops[1] .. Ops[n] = Values LiteralNumber
2295 SPIRVOperandList Ops;
2296
2297 Type *LengthTy = Type::getInt32Ty(Context);
2298 uint32_t ResTyID = lookupType(LengthTy);
2299 Ops << MkId(ResTyID);
2300
2301 assert(Length < UINT32_MAX);
2302 Ops << MkNum(static_cast<uint32_t>(Length));
2303
2304 // Add constant for length to constant list.
2305 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2306 AllocatedVMap[CstLength] = nextID;
2307 VMap[CstLength] = nextID;
2308 uint32_t LengthID = nextID;
2309
2310 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2311 SPIRVInstList.push_back(CstInst);
2312
2313 // Remember to generate ArrayStride later
2314 getTypesNeedingArrayStride().insert(Ty);
2315
2316 //
2317 // Generate OpTypeArray.
2318 //
2319 // Ops[0] = Element Type ID
2320 // Ops[1] = Array Length Constant ID
2321 Ops.clear();
2322
2323 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2324 Ops << MkId(EleTyID) << MkId(LengthID);
2325
2326 // Update TypeMap with nextID.
2327 TypeMap[Ty] = nextID;
2328
2329 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2330 SPIRVInstList.push_back(ArrayInst);
2331 }
David Neto22f144c2017-06-12 14:26:21 -04002332 break;
2333 }
2334 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002335 // <4 x i8> is changed to i32 if i8 is not generally supported.
2336 if (!clspv::Option::Int8Support() &&
2337 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002338 if (Ty->getVectorNumElements() == 4) {
2339 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2340 break;
2341 } else {
2342 Ty->print(errs());
2343 llvm_unreachable("Support above i8 vector type");
2344 }
2345 }
2346
2347 // Ops[0] = Component Type ID
2348 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002349 SPIRVOperandList Ops;
2350 Ops << MkId(lookupType(Ty->getVectorElementType()))
2351 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002352
alan-bakerb6b09dc2018-11-08 16:59:28 -05002353 SPIRVInstruction *inst =
2354 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002355 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002356 break;
2357 }
2358 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002359 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002360 SPIRVInstList.push_back(Inst);
2361 break;
2362 }
2363 case Type::FunctionTyID: {
2364 // Generate SPIRV instruction for function type.
2365 FunctionType *FTy = cast<FunctionType>(Ty);
2366
2367 // Ops[0] = Return Type ID
2368 // Ops[1] ... Ops[n] = Parameter Type IDs
2369 SPIRVOperandList Ops;
2370
2371 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002372 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002373
2374 // Find SPIRV instructions for parameter types
2375 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2376 // Find SPIRV instruction for parameter type.
2377 auto ParamTy = FTy->getParamType(k);
2378 if (ParamTy->isPointerTy()) {
2379 auto PointeeTy = ParamTy->getPointerElementType();
2380 if (PointeeTy->isStructTy() &&
2381 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2382 ParamTy = PointeeTy;
2383 }
2384 }
2385
David Netoc6f3ab22018-04-06 18:02:31 -04002386 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002387 }
2388
David Neto87846742018-04-11 17:36:22 -04002389 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002390 SPIRVInstList.push_back(Inst);
2391 break;
2392 }
2393 }
2394 }
2395
2396 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002397 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002398 //
2399 // Generate OpTypeSampledImage.
2400 //
2401 // Ops[0] = Image Type ID
2402 //
2403 SPIRVOperandList Ops;
2404
David Netoc6f3ab22018-04-06 18:02:31 -04002405 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002406
alan-bakerabd82722019-12-03 17:14:51 -05002407 // Update the image type map.
2408 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002409
David Neto87846742018-04-11 17:36:22 -04002410 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002411 SPIRVInstList.push_back(Inst);
2412 }
David Netoc6f3ab22018-04-06 18:02:31 -04002413
2414 // Generate types for pointer-to-local arguments.
alan-bakera1be3322020-04-20 12:48:18 -04002415 for (auto pair : clspv::GetSpecConstants(&module)) {
2416 auto kind = pair.first;
2417 auto spec_id = pair.second;
2418
2419 if (kind != SpecConstant::kLocalMemorySize)
2420 continue;
2421
alan-bakerb6b09dc2018-11-08 16:59:28 -05002422 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002423
2424 // Generate the spec constant.
2425 SPIRVOperandList Ops;
2426 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002427 SPIRVInstList.push_back(
2428 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002429
2430 // Generate the array type.
2431 Ops.clear();
2432 // The element type must have been created.
2433 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2434 assert(elem_ty_id);
2435 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2436
2437 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002438 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002439
2440 Ops.clear();
2441 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002442 SPIRVInstList.push_back(new SPIRVInstruction(
2443 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002444 }
David Neto22f144c2017-06-12 14:26:21 -04002445}
2446
2447void SPIRVProducerPass::GenerateSPIRVConstants() {
SJW69939d52020-04-16 07:29:07 -05002448 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kConstants);
David Neto22f144c2017-06-12 14:26:21 -04002449 ValueMapType &VMap = getValueMap();
2450 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2451 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002452 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002453
2454 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002455 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002456 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002457
2458 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002459 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002460 continue;
2461 }
2462
David Netofb9a7972017-08-25 17:08:24 -04002463 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002464 VMap[Cst] = nextID;
2465
2466 //
2467 // Generate OpConstant.
2468 //
2469
2470 // Ops[0] = Result Type ID
2471 // Ops[1] .. Ops[n] = Values LiteralNumber
2472 SPIRVOperandList Ops;
2473
David Neto257c3892018-04-11 13:19:45 -04002474 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002475
2476 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002477 spv::Op Opcode = spv::OpNop;
2478
2479 if (isa<UndefValue>(Cst)) {
2480 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002481 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002482 if (hack_undef && IsTypeNullable(Cst->getType())) {
2483 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002484 }
David Neto22f144c2017-06-12 14:26:21 -04002485 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2486 unsigned BitWidth = CI->getBitWidth();
2487 if (BitWidth == 1) {
2488 // If the bitwidth of constant is 1, generate OpConstantTrue or
2489 // OpConstantFalse.
2490 if (CI->getZExtValue()) {
2491 // Ops[0] = Result Type ID
2492 Opcode = spv::OpConstantTrue;
2493 } else {
2494 // Ops[0] = Result Type ID
2495 Opcode = spv::OpConstantFalse;
2496 }
David Neto22f144c2017-06-12 14:26:21 -04002497 } else {
2498 auto V = CI->getZExtValue();
2499 LiteralNum.push_back(V & 0xFFFFFFFF);
2500
2501 if (BitWidth > 32) {
2502 LiteralNum.push_back(V >> 32);
2503 }
2504
2505 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002506
David Neto257c3892018-04-11 13:19:45 -04002507 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002508 }
2509 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2510 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2511 Type *CFPTy = CFP->getType();
2512 if (CFPTy->isFloatTy()) {
2513 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002514 } else if (CFPTy->isDoubleTy()) {
2515 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2516 LiteralNum.push_back(FPVal >> 32);
alan-baker089bf932020-01-07 16:35:45 -05002517 } else if (CFPTy->isHalfTy()) {
2518 LiteralNum.push_back(FPVal & 0xFFFF);
David Neto22f144c2017-06-12 14:26:21 -04002519 } else {
2520 CFPTy->print(errs());
2521 llvm_unreachable("Implement this ConstantFP Type");
2522 }
2523
2524 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002525
David Neto257c3892018-04-11 13:19:45 -04002526 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002527 } else if (isa<ConstantDataSequential>(Cst) &&
2528 cast<ConstantDataSequential>(Cst)->isString()) {
2529 Cst->print(errs());
2530 llvm_unreachable("Implement this Constant");
2531
2532 } else if (const ConstantDataSequential *CDS =
2533 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002534 // Let's convert <4 x i8> constant to int constant specially.
2535 // This case occurs when all the values are specified as constant
2536 // ints.
2537 Type *CstTy = Cst->getType();
2538 if (is4xi8vec(CstTy)) {
2539 LLVMContext &Context = CstTy->getContext();
2540
2541 //
2542 // Generate OpConstant with OpTypeInt 32 0.
2543 //
Neil Henning39672102017-09-29 14:33:13 +01002544 uint32_t IntValue = 0;
2545 for (unsigned k = 0; k < 4; k++) {
2546 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002547 IntValue = (IntValue << 8) | (Val & 0xffu);
2548 }
2549
2550 Type *i32 = Type::getInt32Ty(Context);
2551 Constant *CstInt = ConstantInt::get(i32, IntValue);
2552 // If this constant is already registered on VMap, use it.
2553 if (VMap.count(CstInt)) {
2554 uint32_t CstID = VMap[CstInt];
2555 VMap[Cst] = CstID;
2556 continue;
2557 }
2558
David Neto257c3892018-04-11 13:19:45 -04002559 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002560
David Neto87846742018-04-11 17:36:22 -04002561 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002562 SPIRVInstList.push_back(CstInst);
2563
2564 continue;
2565 }
2566
2567 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002568 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2569 Constant *EleCst = CDS->getElementAsConstant(k);
2570 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002571 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002572 }
2573
2574 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002575 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2576 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002577 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002578 Type *CstTy = Cst->getType();
2579 if (is4xi8vec(CstTy)) {
2580 LLVMContext &Context = CstTy->getContext();
2581
2582 //
2583 // Generate OpConstant with OpTypeInt 32 0.
2584 //
Neil Henning39672102017-09-29 14:33:13 +01002585 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002586 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2587 I != E; ++I) {
2588 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002589 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002590 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2591 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002592 }
David Neto49351ac2017-08-26 17:32:20 -04002593 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002594 }
2595
David Neto49351ac2017-08-26 17:32:20 -04002596 Type *i32 = Type::getInt32Ty(Context);
2597 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002598 // If this constant is already registered on VMap, use it.
2599 if (VMap.count(CstInt)) {
2600 uint32_t CstID = VMap[CstInt];
2601 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002602 continue;
David Neto22f144c2017-06-12 14:26:21 -04002603 }
2604
David Neto257c3892018-04-11 13:19:45 -04002605 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002606
David Neto87846742018-04-11 17:36:22 -04002607 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002608 SPIRVInstList.push_back(CstInst);
2609
David Neto19a1bad2017-08-25 15:01:41 -04002610 continue;
David Neto22f144c2017-06-12 14:26:21 -04002611 }
2612
2613 // We use a constant composite in SPIR-V for our constant aggregate in
2614 // LLVM.
2615 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002616
2617 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2618 // Look up the ID of the element of this aggregate (which we will
2619 // previously have created a constant for).
2620 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2621
2622 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002623 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002624 }
2625 } else if (Cst->isNullValue()) {
2626 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002627 } else {
2628 Cst->print(errs());
2629 llvm_unreachable("Unsupported Constant???");
2630 }
2631
alan-baker5b86ed72019-02-15 08:26:50 -05002632 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2633 // Null pointer requires variable pointers.
2634 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2635 }
2636
David Neto87846742018-04-11 17:36:22 -04002637 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002638 SPIRVInstList.push_back(CstInst);
2639 }
2640}
2641
2642void SPIRVProducerPass::GenerateSamplers(Module &M) {
SJW69939d52020-04-16 07:29:07 -05002643 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04002644
alan-bakerb6b09dc2018-11-08 16:59:28 -05002645 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002646 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002647 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2648 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002649
David Neto862b7d82018-06-14 18:48:37 -04002650 // We might have samplers in the sampler map that are not used
2651 // in the translation unit. We need to allocate variables
2652 // for them and bindings too.
2653 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002654
Kévin Petitdf71de32019-04-09 14:09:50 +01002655 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002656 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002657 if (!var_fn)
2658 return;
alan-baker09cb9802019-12-10 13:16:27 -05002659
David Neto862b7d82018-06-14 18:48:37 -04002660 for (auto user : var_fn->users()) {
2661 // Populate SamplerLiteralToDescriptorSetMap and
2662 // SamplerLiteralToBindingMap.
2663 //
2664 // Look for calls like
2665 // call %opencl.sampler_t addrspace(2)*
2666 // @clspv.sampler.var.literal(
2667 // i32 descriptor,
2668 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002669 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002670 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002671 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002672 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002673 auto sampler_value = third_param;
2674 if (clspv::Option::UseSamplerMap()) {
2675 if (third_param >= sampler_map.size()) {
2676 errs() << "Out of bounds index to sampler map: " << third_param;
2677 llvm_unreachable("bad sampler init: out of bounds");
2678 }
2679 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002680 }
2681
David Neto862b7d82018-06-14 18:48:37 -04002682 const auto descriptor_set = static_cast<unsigned>(
2683 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2684 const auto binding = static_cast<unsigned>(
2685 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2686
2687 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2688 SamplerLiteralToBindingMap[sampler_value] = binding;
2689 used_bindings.insert(binding);
2690 }
2691 }
2692
alan-baker09cb9802019-12-10 13:16:27 -05002693 DenseSet<size_t> seen;
2694 for (auto user : var_fn->users()) {
2695 if (!isa<CallInst>(user))
2696 continue;
2697
2698 auto call = cast<CallInst>(user);
2699 const unsigned third_param = static_cast<unsigned>(
2700 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2701
2702 // Already allocated a variable for this value.
2703 if (!seen.insert(third_param).second)
2704 continue;
2705
2706 auto sampler_value = third_param;
2707 if (clspv::Option::UseSamplerMap()) {
2708 sampler_value = sampler_map[third_param].first;
2709 }
2710
David Neto22f144c2017-06-12 14:26:21 -04002711 // Generate OpVariable.
2712 //
2713 // GIDOps[0] : Result Type ID
2714 // GIDOps[1] : Storage Class
2715 SPIRVOperandList Ops;
2716
David Neto257c3892018-04-11 13:19:45 -04002717 Ops << MkId(lookupType(SamplerTy))
2718 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002719
David Neto862b7d82018-06-14 18:48:37 -04002720 auto sampler_var_id = nextID++;
2721 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002722 SPIRVInstList.push_back(Inst);
2723
alan-baker09cb9802019-12-10 13:16:27 -05002724 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002725
David Neto862b7d82018-06-14 18:48:37 -04002726 unsigned descriptor_set;
2727 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002728 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002729 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002730 // This sampler is not actually used. Find the next one.
2731 for (binding = 0; used_bindings.count(binding); binding++)
2732 ;
2733 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2734 used_bindings.insert(binding);
2735 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002736 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2737 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002738
alan-baker09cb9802019-12-10 13:16:27 -05002739 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002740 descriptorMapEntries->emplace_back(std::move(sampler_data),
2741 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002742 }
2743
SJW69939d52020-04-16 07:29:07 -05002744 // Ops[0] = Target ID
2745 // Ops[1] = Decoration (DescriptorSet)
2746 // Ops[2] = LiteralNumber according to Decoration
2747 Ops.clear();
2748
David Neto862b7d82018-06-14 18:48:37 -04002749 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2750 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002751
David Neto87846742018-04-11 17:36:22 -04002752 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002753 getSPIRVInstList(kAnnotations).push_back(DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002754
2755 // Ops[0] = Target ID
2756 // Ops[1] = Decoration (Binding)
2757 // Ops[2] = LiteralNumber according to Decoration
2758 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002759 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2760 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002761
David Neto87846742018-04-11 17:36:22 -04002762 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002763 getSPIRVInstList(kAnnotations).push_back(BindDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002764 }
David Neto862b7d82018-06-14 18:48:37 -04002765}
David Neto22f144c2017-06-12 14:26:21 -04002766
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002767void SPIRVProducerPass::GenerateResourceVars(Module &) {
SJW69939d52020-04-16 07:29:07 -05002768 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto862b7d82018-06-14 18:48:37 -04002769 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002770
David Neto862b7d82018-06-14 18:48:37 -04002771 // Generate variables. Make one for each of resource var info object.
2772 for (auto *info : ModuleOrderedResourceVars) {
2773 Type *type = info->var_fn->getReturnType();
2774 // Remap the address space for opaque types.
2775 switch (info->arg_kind) {
2776 case clspv::ArgKind::Sampler:
2777 case clspv::ArgKind::ReadOnlyImage:
2778 case clspv::ArgKind::WriteOnlyImage:
2779 type = PointerType::get(type->getPointerElementType(),
2780 clspv::AddressSpace::UniformConstant);
2781 break;
2782 default:
2783 break;
2784 }
David Neto22f144c2017-06-12 14:26:21 -04002785
David Neto862b7d82018-06-14 18:48:37 -04002786 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002787
David Neto862b7d82018-06-14 18:48:37 -04002788 const auto type_id = lookupType(type);
2789 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2790 SPIRVOperandList Ops;
2791 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002792
David Neto862b7d82018-06-14 18:48:37 -04002793 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2794 SPIRVInstList.push_back(Inst);
2795
2796 // Map calls to the variable-builtin-function.
2797 for (auto &U : info->var_fn->uses()) {
2798 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2799 const auto set = unsigned(
2800 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2801 const auto binding = unsigned(
2802 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2803 if (set == info->descriptor_set && binding == info->binding) {
2804 switch (info->arg_kind) {
2805 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002806 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002807 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002808 case clspv::ArgKind::PodUBO:
2809 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002810 // The call maps to the variable directly.
2811 VMap[call] = info->var_id;
2812 break;
2813 case clspv::ArgKind::Sampler:
2814 case clspv::ArgKind::ReadOnlyImage:
2815 case clspv::ArgKind::WriteOnlyImage:
2816 // The call maps to a load we generate later.
2817 ResourceVarDeferredLoadCalls[call] = info->var_id;
2818 break;
2819 default:
2820 llvm_unreachable("Unhandled arg kind");
2821 }
2822 }
David Neto22f144c2017-06-12 14:26:21 -04002823 }
David Neto862b7d82018-06-14 18:48:37 -04002824 }
2825 }
David Neto22f144c2017-06-12 14:26:21 -04002826
David Neto862b7d82018-06-14 18:48:37 -04002827 // Generate associated decorations.
SJW69939d52020-04-16 07:29:07 -05002828 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto862b7d82018-06-14 18:48:37 -04002829
2830 SPIRVOperandList Ops;
2831 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002832 // Push constants don't need descriptor set or binding decorations.
2833 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2834 continue;
2835
David Neto862b7d82018-06-14 18:48:37 -04002836 // Decorate with DescriptorSet and Binding.
2837 Ops.clear();
2838 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2839 << MkNum(info->descriptor_set);
SJW69939d52020-04-16 07:29:07 -05002840 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002841
2842 Ops.clear();
2843 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2844 << MkNum(info->binding);
SJW69939d52020-04-16 07:29:07 -05002845 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002846
alan-bakere9308012019-03-15 10:25:13 -04002847 if (info->coherent) {
2848 // Decorate with Coherent if required for the variable.
2849 Ops.clear();
2850 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05002851 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
alan-bakere9308012019-03-15 10:25:13 -04002852 }
2853
David Neto862b7d82018-06-14 18:48:37 -04002854 // Generate NonWritable and NonReadable
2855 switch (info->arg_kind) {
2856 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002857 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002858 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2859 clspv::AddressSpace::Constant) {
2860 Ops.clear();
2861 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
SJW69939d52020-04-16 07:29:07 -05002862 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002863 }
David Neto862b7d82018-06-14 18:48:37 -04002864 break;
David Neto862b7d82018-06-14 18:48:37 -04002865 case clspv::ArgKind::WriteOnlyImage:
2866 Ops.clear();
2867 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
SJW69939d52020-04-16 07:29:07 -05002868 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto862b7d82018-06-14 18:48:37 -04002869 break;
2870 default:
2871 break;
David Neto22f144c2017-06-12 14:26:21 -04002872 }
2873 }
2874}
2875
Kévin Petitbbbda972020-03-03 19:16:31 +00002876namespace {
2877
2878bool isScalarType(Type *type) {
2879 return type->isIntegerTy() || type->isFloatTy();
2880}
2881
2882uint64_t structAlignment(StructType *type,
2883 std::function<uint64_t(Type *)> alignFn) {
2884 uint64_t maxAlign = 1;
2885 for (unsigned i = 0; i < type->getStructNumElements(); i++) {
2886 uint64_t align = alignFn(type->getStructElementType(i));
2887 maxAlign = std::max(align, maxAlign);
2888 }
2889 return maxAlign;
2890}
2891
2892uint64_t scalarAlignment(Type *type) {
2893 // A scalar of size N has a scalar alignment of N.
2894 if (isScalarType(type)) {
2895 return type->getScalarSizeInBits() / 8;
2896 }
2897
2898 // A vector or matrix type has a scalar alignment equal to that of its
2899 // component type.
2900 if (type->isVectorTy()) {
2901 return scalarAlignment(type->getVectorElementType());
2902 }
2903
2904 // An array type has a scalar alignment equal to that of its element type.
2905 if (type->isArrayTy()) {
2906 return scalarAlignment(type->getArrayElementType());
2907 }
2908
2909 // A structure has a scalar alignment equal to the largest scalar alignment of
2910 // any of its members.
2911 if (type->isStructTy()) {
2912 return structAlignment(cast<StructType>(type), scalarAlignment);
2913 }
2914
2915 llvm_unreachable("Unsupported type");
2916}
2917
2918uint64_t baseAlignment(Type *type) {
2919 // A scalar has a base alignment equal to its scalar alignment.
2920 if (isScalarType(type)) {
2921 return scalarAlignment(type);
2922 }
2923
2924 if (type->isVectorTy()) {
2925 unsigned numElems = type->getVectorNumElements();
2926
2927 // A two-component vector has a base alignment equal to twice its scalar
2928 // alignment.
2929 if (numElems == 2) {
2930 return 2 * scalarAlignment(type);
2931 }
2932 // A three- or four-component vector has a base alignment equal to four
2933 // times its scalar alignment.
2934 if ((numElems == 3) || (numElems == 4)) {
2935 return 4 * scalarAlignment(type);
2936 }
2937 }
2938
2939 // An array has a base alignment equal to the base alignment of its element
2940 // type.
2941 if (type->isArrayTy()) {
2942 return baseAlignment(type->getArrayElementType());
2943 }
2944
2945 // A structure has a base alignment equal to the largest base alignment of any
2946 // of its members.
2947 if (type->isStructTy()) {
2948 return structAlignment(cast<StructType>(type), baseAlignment);
2949 }
2950
2951 // TODO A row-major matrix of C columns has a base alignment equal to the base
2952 // alignment of a vector of C matrix components.
2953 // TODO A column-major matrix has a base alignment equal to the base alignment
2954 // of the matrix column type.
2955
2956 llvm_unreachable("Unsupported type");
2957}
2958
2959uint64_t extendedAlignment(Type *type) {
2960 // A scalar, vector or matrix type has an extended alignment equal to its base
2961 // alignment.
2962 // TODO matrix type
2963 if (isScalarType(type) || type->isVectorTy()) {
2964 return baseAlignment(type);
2965 }
2966
2967 // An array or structure type has an extended alignment equal to the largest
2968 // extended alignment of any of its members, rounded up to a multiple of 16
2969 if (type->isStructTy()) {
2970 auto salign = structAlignment(cast<StructType>(type), extendedAlignment);
2971 return alignTo(salign, 16);
2972 }
2973
2974 if (type->isArrayTy()) {
2975 auto salign = extendedAlignment(type->getArrayElementType());
2976 return alignTo(salign, 16);
2977 }
2978
2979 llvm_unreachable("Unsupported type");
2980}
2981
2982uint64_t standardAlignment(Type *type, spv::StorageClass sclass) {
2983 // If the scalarBlockLayout feature is enabled on the device then every member
2984 // must be aligned according to its scalar alignment
2985 if (clspv::Option::ScalarBlockLayout()) {
2986 return scalarAlignment(type);
2987 }
2988
2989 // All vectors must be aligned according to their scalar alignment
2990 if (type->isVectorTy()) {
2991 return scalarAlignment(type);
2992 }
2993
2994 // If the uniformBufferStandardLayout feature is not enabled on the device,
2995 // then any member of an OpTypeStruct with a storage class of Uniform and a
2996 // decoration of Block must be aligned according to its extended alignment.
2997 if (!clspv::Option::Std430UniformBufferLayout() &&
2998 sclass == spv::StorageClassUniform) {
2999 return extendedAlignment(type);
3000 }
3001
3002 // Every other member must be aligned according to its base alignment
3003 return baseAlignment(type);
3004}
3005
3006bool improperlyStraddles(const DataLayout &DL, Type *type, unsigned offset) {
3007 assert(type->isVectorTy());
3008
3009 auto size = DL.getTypeStoreSize(type);
3010
3011 // It is a vector with total size less than or equal to 16 bytes, and has
3012 // Offset decorations placing its first byte at F and its last byte at L,
3013 // where floor(F / 16) != floor(L / 16).
3014 if ((size <= 16) && (offset % 16 + size > 16)) {
3015 return true;
3016 }
3017
3018 // It is a vector with total size greater than 16 bytes and has its Offset
3019 // decorations placing its first byte at a non-integer multiple of 16
3020 if ((size > 16) && (offset % 16 != 0)) {
3021 return true;
3022 }
3023
3024 return false;
3025}
3026
3027// See 14.5 Shader Resource Interface in Vulkan spec
3028bool isValidExplicitLayout(Module &M, StructType *STy, unsigned Member,
3029 spv::StorageClass SClass, unsigned Offset,
3030 unsigned PreviousMemberOffset) {
3031
3032 auto MemberType = STy->getElementType(Member);
3033 auto Align = standardAlignment(MemberType, SClass);
3034 auto &DL = M.getDataLayout();
3035
3036 // The Offset decoration of any member must be a multiple of its alignment
3037 if (Offset % Align != 0) {
3038 return false;
3039 }
3040
3041 // TODO Any ArrayStride or MatrixStride decoration must be a multiple of the
3042 // alignment of the array or matrix as defined above
3043
3044 if (!clspv::Option::ScalarBlockLayout()) {
3045 // Vectors must not improperly straddle, as defined above
3046 if (MemberType->isVectorTy() &&
3047 improperlyStraddles(DL, MemberType, Offset)) {
3048 return true;
3049 }
3050
3051 // The Offset decoration of a member must not place it between the end
3052 // of a structure or an array and the next multiple of the alignment of that
3053 // structure or array
3054 if (Member > 0) {
3055 auto PType = STy->getElementType(Member - 1);
3056 if (PType->isStructTy() || PType->isArrayTy()) {
3057 auto PAlign = standardAlignment(PType, SClass);
3058 if (Offset - PreviousMemberOffset < PAlign) {
3059 return false;
3060 }
3061 }
3062 }
3063 }
3064
3065 return true;
3066}
3067
3068} // namespace
3069
alan-bakera1be3322020-04-20 12:48:18 -04003070void SPIRVProducerPass::GeneratePushConstantDescriptorMapEntries(Module &M) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003071
3072 if (auto GV = M.getGlobalVariable(clspv::PushConstantsVariableName())) {
3073 auto const &DL = M.getDataLayout();
3074 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
3075 auto STy = cast<StructType>(GV->getValueType());
3076
3077 for (unsigned i = 0; i < STy->getNumElements(); i++) {
3078 auto pc = static_cast<clspv::PushConstant>(
3079 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
3080 auto memberType = STy->getElementType(i);
3081 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
3082 unsigned previousOffset = 0;
3083 if (i > 0) {
3084 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
3085 }
3086 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
3087 assert(isValidExplicitLayout(M, STy, i, spv::StorageClassPushConstant,
3088 offset, previousOffset));
3089 version0::DescriptorMapEntry::PushConstantData data = {pc, offset, size};
3090 descriptorMapEntries->emplace_back(std::move(data));
3091 }
3092 }
3093}
3094
alan-bakera1be3322020-04-20 12:48:18 -04003095void SPIRVProducerPass::GenerateSpecConstantDescriptorMapEntries(Module &M) {
3096 for (auto pair : clspv::GetSpecConstants(&M)) {
3097 auto kind = pair.first;
3098 auto id = pair.second;
3099
3100 // Local memory size is only used for kernel arguments.
3101 if (kind == SpecConstant::kLocalMemorySize)
3102 continue;
3103
3104 version0::DescriptorMapEntry::SpecConstantData data = {kind, id};
3105 descriptorMapEntries->emplace_back(std::move(data));
3106 }
3107}
3108
David Neto22f144c2017-06-12 14:26:21 -04003109void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003110 Module &M = *GV.getParent();
SJW69939d52020-04-16 07:29:07 -05003111 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
David Neto22f144c2017-06-12 14:26:21 -04003112 ValueMapType &VMap = getValueMap();
3113 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07003114 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003115
3116 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
3117 Type *Ty = GV.getType();
3118 PointerType *PTy = cast<PointerType>(Ty);
3119
3120 uint32_t InitializerID = 0;
3121
3122 // Workgroup size is handled differently (it goes into a constant)
3123 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3124 std::vector<bool> HasMDVec;
3125 uint32_t PrevXDimCst = 0xFFFFFFFF;
3126 uint32_t PrevYDimCst = 0xFFFFFFFF;
3127 uint32_t PrevZDimCst = 0xFFFFFFFF;
3128 for (Function &Func : *GV.getParent()) {
3129 if (Func.isDeclaration()) {
3130 continue;
3131 }
3132
3133 // We only need to check kernels.
3134 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
3135 continue;
3136 }
3137
3138 if (const MDNode *MD =
3139 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
3140 uint32_t CurXDimCst = static_cast<uint32_t>(
3141 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3142 uint32_t CurYDimCst = static_cast<uint32_t>(
3143 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3144 uint32_t CurZDimCst = static_cast<uint32_t>(
3145 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3146
3147 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
3148 PrevZDimCst == 0xFFFFFFFF) {
3149 PrevXDimCst = CurXDimCst;
3150 PrevYDimCst = CurYDimCst;
3151 PrevZDimCst = CurZDimCst;
3152 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
3153 CurZDimCst != PrevZDimCst) {
3154 llvm_unreachable(
3155 "reqd_work_group_size must be the same across all kernels");
3156 } else {
3157 continue;
3158 }
3159
3160 //
3161 // Generate OpConstantComposite.
3162 //
3163 // Ops[0] : Result Type ID
3164 // Ops[1] : Constant size for x dimension.
3165 // Ops[2] : Constant size for y dimension.
3166 // Ops[3] : Constant size for z dimension.
3167 SPIRVOperandList Ops;
3168
3169 uint32_t XDimCstID =
3170 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
3171 uint32_t YDimCstID =
3172 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
3173 uint32_t ZDimCstID =
3174 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
3175
3176 InitializerID = nextID;
3177
David Neto257c3892018-04-11 13:19:45 -04003178 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3179 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003180
David Neto87846742018-04-11 17:36:22 -04003181 auto *Inst =
3182 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003183 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003184
3185 HasMDVec.push_back(true);
3186 } else {
3187 HasMDVec.push_back(false);
3188 }
3189 }
3190
3191 // Check all kernels have same definitions for work_group_size.
3192 bool HasMD = false;
3193 if (!HasMDVec.empty()) {
3194 HasMD = HasMDVec[0];
3195 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
3196 if (HasMD != HasMDVec[i]) {
3197 llvm_unreachable(
3198 "Kernels should have consistent work group size definition");
3199 }
3200 }
3201 }
3202
3203 // If all kernels do not have metadata for reqd_work_group_size, generate
3204 // OpSpecConstants for x/y/z dimension.
3205 if (!HasMD) {
3206 //
3207 // Generate OpSpecConstants for x/y/z dimension.
3208 //
3209 // Ops[0] : Result Type ID
3210 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
3211 uint32_t XDimCstID = 0;
3212 uint32_t YDimCstID = 0;
3213 uint32_t ZDimCstID = 0;
3214
alan-bakera1be3322020-04-20 12:48:18 -04003215 // Allocate spec constants for workgroup size.
3216 clspv::AddWorkgroupSpecConstants(&M);
3217
David Neto22f144c2017-06-12 14:26:21 -04003218 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04003219 uint32_t result_type_id =
alan-baker8eb435a2020-04-08 00:42:06 -04003220 lookupType(Ty->getPointerElementType()->getVectorElementType());
David Neto22f144c2017-06-12 14:26:21 -04003221
David Neto257c3892018-04-11 13:19:45 -04003222 // X Dimension
3223 Ops << MkId(result_type_id) << MkNum(1);
3224 XDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003225 getSPIRVInstList(kConstants)
3226 .push_back(new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003227
3228 // Y Dimension
3229 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003230 Ops << MkId(result_type_id) << MkNum(1);
3231 YDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003232 getSPIRVInstList(kConstants)
3233 .push_back(new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003234
3235 // Z Dimension
3236 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003237 Ops << MkId(result_type_id) << MkNum(1);
3238 ZDimCstID = nextID++;
alan-bakera1be3322020-04-20 12:48:18 -04003239 getSPIRVInstList(kConstants)
3240 .push_back(new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003241
David Neto257c3892018-04-11 13:19:45 -04003242 BuiltinDimVec.push_back(XDimCstID);
3243 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003244 BuiltinDimVec.push_back(ZDimCstID);
3245
David Neto22f144c2017-06-12 14:26:21 -04003246 //
3247 // Generate OpSpecConstantComposite.
3248 //
3249 // Ops[0] : Result Type ID
3250 // Ops[1] : Constant size for x dimension.
3251 // Ops[2] : Constant size for y dimension.
3252 // Ops[3] : Constant size for z dimension.
3253 InitializerID = nextID;
3254
3255 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003256 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
3257 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04003258
David Neto87846742018-04-11 17:36:22 -04003259 auto *Inst =
3260 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
alan-bakera1be3322020-04-20 12:48:18 -04003261 getSPIRVInstList(kConstants).push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003262 }
3263 }
3264
David Neto22f144c2017-06-12 14:26:21 -04003265 VMap[&GV] = nextID;
3266
3267 //
3268 // Generate OpVariable.
3269 //
3270 // GIDOps[0] : Result Type ID
3271 // GIDOps[1] : Storage Class
3272 SPIRVOperandList Ops;
3273
David Neto85082642018-03-24 06:55:20 -07003274 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04003275 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04003276
David Neto85082642018-03-24 06:55:20 -07003277 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04003278 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07003279 clspv::Option::ModuleConstantsInStorageBuffer();
3280
Kévin Petit23d5f182019-08-13 16:21:29 +01003281 if (GV.hasInitializer()) {
3282 auto GVInit = GV.getInitializer();
3283 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
3284 assert(VMap.count(GVInit) == 1);
3285 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07003286 }
3287 }
Kévin Petit23d5f182019-08-13 16:21:29 +01003288
3289 if (0 != InitializerID) {
Kévin Petitbbbda972020-03-03 19:16:31 +00003290 // Emit the ID of the initializer as part of the variable definition.
Kévin Petit23d5f182019-08-13 16:21:29 +01003291 Ops << MkId(InitializerID);
3292 }
David Neto85082642018-03-24 06:55:20 -07003293 const uint32_t var_id = nextID++;
3294
David Neto87846742018-04-11 17:36:22 -04003295 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003296 SPIRVInstList.push_back(Inst);
3297
SJW69939d52020-04-16 07:29:07 -05003298 SPIRVInstructionList &Annotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003299 // If we have a builtin.
3300 if (spv::BuiltInMax != BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04003301 //
3302 // Generate OpDecorate.
3303 //
3304 // DOps[0] = Target ID
3305 // DOps[1] = Decoration (Builtin)
3306 // DOps[2] = BuiltIn ID
3307 uint32_t ResultID;
3308
3309 // WorkgroupSize is different, we decorate the constant composite that has
3310 // its value, rather than the variable that we use to access the value.
3311 if (spv::BuiltInWorkgroupSize == BuiltinType) {
3312 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04003313 // Save both the value and variable IDs for later.
3314 WorkgroupSizeValueID = InitializerID;
3315 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04003316 } else {
3317 ResultID = VMap[&GV];
3318 }
3319
3320 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003321 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3322 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003323
David Neto87846742018-04-11 17:36:22 -04003324 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
SJW69939d52020-04-16 07:29:07 -05003325 Annotations.push_back(DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003326 } else if (module_scope_constant_external_init) {
3327 // This module scope constant is initialized from a storage buffer with data
3328 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04003329 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07003330
David Neto862b7d82018-06-14 18:48:37 -04003331 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003332 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3333 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003334 std::string hexbytes;
3335 llvm::raw_string_ostream str(hexbytes);
3336 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003337 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3338 str.str()};
3339 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3340 0);
David Neto85082642018-03-24 06:55:20 -07003341
David Neto85082642018-03-24 06:55:20 -07003342 SPIRVOperandList DOps;
David Neto85082642018-03-24 06:55:20 -07003343
3344 // OpDecorate %var DescriptorSet <descriptor_set>
David Neto257c3892018-04-11 13:19:45 -04003345 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3346 << MkNum(descriptor_set);
SJW69939d52020-04-16 07:29:07 -05003347 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
3348
3349 // OpDecorate %var Binding <binding>
3350 DOps.clear();
3351 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3352 Annotations.push_back(new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003353 }
3354}
3355
alan-bakera1be3322020-04-20 12:48:18 -04003356void SPIRVProducerPass::GenerateWorkgroupVars(Module &M) {
SJW69939d52020-04-16 07:29:07 -05003357 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kGlobalVariables);
alan-bakera1be3322020-04-20 12:48:18 -04003358 auto spec_constant_md = M.getNamedMetadata(clspv::SpecConstantMetadataName());
3359 if (!spec_constant_md)
3360 return;
3361
3362 for (auto pair : clspv::GetSpecConstants(&M)) {
3363 auto kind = pair.first;
3364 auto spec_id = pair.second;
3365
3366 if (kind != SpecConstant::kLocalMemorySize)
3367 continue;
3368
alan-bakerb6b09dc2018-11-08 16:59:28 -05003369 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003370
3371 // Generate OpVariable.
3372 //
3373 // GIDOps[0] : Result Type ID
3374 // GIDOps[1] : Storage Class
3375 SPIRVOperandList Ops;
3376 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3377
3378 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003379 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003380 }
3381}
3382
David Neto862b7d82018-06-14 18:48:37 -04003383void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3384 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003385 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3386 return;
3387 }
Kévin Petit717f8572020-04-06 17:31:53 +01003388 // Add entries for each kernel
3389 version0::DescriptorMapEntry::KernelDeclData kernel_decl_data = {
3390 F.getName().str()};
3391 descriptorMapEntries->emplace_back(std::move(kernel_decl_data));
3392
David Neto862b7d82018-06-14 18:48:37 -04003393 // Gather the list of resources that are used by this function's arguments.
3394 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3395
alan-bakerf5e5f692018-11-27 08:33:24 -05003396 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3397 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003398 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003399 std::string kind =
3400 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3401 ? "pod_ubo"
alan-baker21574d32020-01-29 16:00:31 -05003402 : argKind.str();
alan-bakerf5e5f692018-11-27 08:33:24 -05003403 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003404 };
3405
3406 auto *fty = F.getType()->getPointerElementType();
3407 auto *func_ty = dyn_cast<FunctionType>(fty);
3408
alan-baker038e9242019-04-19 22:14:41 -04003409 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003410 // If an argument maps to a resource variable, then get descriptor set and
3411 // binding from the resoure variable. Other info comes from the metadata.
3412 const auto *arg_map = F.getMetadata("kernel_arg_map");
3413 if (arg_map) {
3414 for (const auto &arg : arg_map->operands()) {
3415 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003416 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003417 const auto name =
3418 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3419 const auto old_index =
3420 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3421 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003422 const size_t new_index = static_cast<size_t>(
3423 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003424 const auto offset =
3425 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003426 const auto arg_size =
3427 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003428 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003429 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003430 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003431 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003432
3433 uint32_t descriptor_set = 0;
3434 uint32_t binding = 0;
3435 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003436 F.getName().str(), name.str(), static_cast<uint32_t>(old_index),
3437 argKind, static_cast<uint32_t>(spec_id),
alan-bakerf5e5f692018-11-27 08:33:24 -05003438 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003439 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003440 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003441 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3442 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3443 DL));
David Neto862b7d82018-06-14 18:48:37 -04003444 } else {
3445 auto *info = resource_var_at_index[new_index];
3446 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003447 descriptor_set = info->descriptor_set;
3448 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003449 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003450 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3451 binding);
David Neto862b7d82018-06-14 18:48:37 -04003452 }
3453 } else {
3454 // There is no argument map.
3455 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003456 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003457
3458 SmallVector<Argument *, 4> arguments;
3459 for (auto &arg : F.args()) {
3460 arguments.push_back(&arg);
3461 }
3462
3463 unsigned arg_index = 0;
3464 for (auto *info : resource_var_at_index) {
3465 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003466 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003467 unsigned arg_size = 0;
alan-baker9b0ec3c2020-04-06 14:45:34 -04003468 if (info->arg_kind == clspv::ArgKind::Pod ||
3469 info->arg_kind == clspv::ArgKind::PodUBO ||
3470 info->arg_kind == clspv::ArgKind::PodPushConstant) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003471 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003472 }
3473
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003474 // Local pointer arguments are unused in this case. Offset is always
3475 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003476 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003477 F.getName().str(),
3478 arg->getName().str(),
3479 arg_index,
3480 remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3481 0,
3482 0,
3483 0,
3484 arg_size};
alan-bakerf5e5f692018-11-27 08:33:24 -05003485 descriptorMapEntries->emplace_back(std::move(kernel_data),
3486 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003487 }
3488 arg_index++;
3489 }
3490 // Generate mappings for pointer-to-local arguments.
3491 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3492 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003493 auto where = LocalArgSpecIds.find(arg);
3494 if (where != LocalArgSpecIds.end()) {
3495 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003496 // Pod arguments members are unused in this case.
3497 version0::DescriptorMapEntry::KernelArgData kernel_data = {
alan-baker21574d32020-01-29 16:00:31 -05003498 F.getName().str(),
3499 arg->getName().str(),
alan-bakerf5e5f692018-11-27 08:33:24 -05003500 arg_index,
3501 ArgKind::Local,
3502 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003503 static_cast<uint32_t>(
3504 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003505 0,
3506 0};
3507 // Pointer-to-local arguments do not utilize descriptor set and binding.
3508 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003509 }
3510 }
3511 }
3512}
3513
David Neto22f144c2017-06-12 14:26:21 -04003514void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003515 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003516 ValueMapType &VMap = getValueMap();
3517 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003518 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3519 auto &GlobalConstArgSet = getGlobalConstArgSet();
3520
3521 FunctionType *FTy = F.getFunctionType();
3522
3523 //
David Neto22f144c2017-06-12 14:26:21 -04003524 // Generate OPFunction.
3525 //
3526
3527 // FOps[0] : Result Type ID
3528 // FOps[1] : Function Control
3529 // FOps[2] : Function Type ID
3530 SPIRVOperandList FOps;
3531
3532 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003533 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003534
3535 // Check function attributes for SPIRV Function Control.
3536 uint32_t FuncControl = spv::FunctionControlMaskNone;
3537 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3538 FuncControl |= spv::FunctionControlInlineMask;
3539 }
3540 if (F.hasFnAttribute(Attribute::NoInline)) {
3541 FuncControl |= spv::FunctionControlDontInlineMask;
3542 }
3543 // TODO: Check llvm attribute for Function Control Pure.
3544 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3545 FuncControl |= spv::FunctionControlPureMask;
3546 }
3547 // TODO: Check llvm attribute for Function Control Const.
3548 if (F.hasFnAttribute(Attribute::ReadNone)) {
3549 FuncControl |= spv::FunctionControlConstMask;
3550 }
3551
David Neto257c3892018-04-11 13:19:45 -04003552 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003553
3554 uint32_t FTyID;
3555 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3556 SmallVector<Type *, 4> NewFuncParamTys;
3557 FunctionType *NewFTy =
3558 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3559 FTyID = lookupType(NewFTy);
3560 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003561 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003562 if (GlobalConstFuncTyMap.count(FTy)) {
3563 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3564 } else {
3565 FTyID = lookupType(FTy);
3566 }
3567 }
3568
David Neto257c3892018-04-11 13:19:45 -04003569 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003570
3571 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3572 EntryPoints.push_back(std::make_pair(&F, nextID));
3573 }
3574
3575 VMap[&F] = nextID;
3576
David Neto482550a2018-03-24 05:21:07 -07003577 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003578 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3579 }
David Neto22f144c2017-06-12 14:26:21 -04003580 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003581 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003582 SPIRVInstList.push_back(FuncInst);
3583
3584 //
3585 // Generate OpFunctionParameter for Normal function.
3586 //
3587
3588 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003589
David Neto22f144c2017-06-12 14:26:21 -04003590 // Iterate Argument for name instead of param type from function type.
3591 unsigned ArgIdx = 0;
3592 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003593 uint32_t param_id = nextID++;
3594 VMap[&Arg] = param_id;
3595
3596 if (CalledWithCoherentResource(Arg)) {
3597 // If the arg is passed a coherent resource ever, then decorate this
3598 // parameter with Coherent too.
3599 SPIRVOperandList decoration_ops;
3600 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
SJW69939d52020-04-16 07:29:07 -05003601 getSPIRVInstList(kAnnotations)
3602 .push_back(new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003603 }
David Neto22f144c2017-06-12 14:26:21 -04003604
3605 // ParamOps[0] : Result Type ID
3606 SPIRVOperandList ParamOps;
3607
3608 // Find SPIRV instruction for parameter type.
3609 uint32_t ParamTyID = lookupType(Arg.getType());
3610 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3611 if (GlobalConstFuncTyMap.count(FTy)) {
3612 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3613 Type *EleTy = PTy->getPointerElementType();
3614 Type *ArgTy =
3615 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3616 ParamTyID = lookupType(ArgTy);
3617 GlobalConstArgSet.insert(&Arg);
3618 }
3619 }
3620 }
David Neto257c3892018-04-11 13:19:45 -04003621 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003622
3623 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003624 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003625 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003626 SPIRVInstList.push_back(ParamInst);
3627
3628 ArgIdx++;
3629 }
3630 }
3631}
3632
alan-bakerb6b09dc2018-11-08 16:59:28 -05003633void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003634 EntryPointVecType &EntryPoints = getEntryPointVec();
3635 ValueMapType &VMap = getValueMap();
3636 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
David Neto22f144c2017-06-12 14:26:21 -04003637 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3638
SJW69939d52020-04-16 07:29:07 -05003639 SPIRVInstructionList &SPIRVCapabilities = getSPIRVInstList(kCapabilities);
David Neto22f144c2017-06-12 14:26:21 -04003640 //
3641 // Generate OpCapability
3642 //
3643 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3644
3645 // Ops[0] = Capability
3646 SPIRVOperandList Ops;
3647
David Neto87846742018-04-11 17:36:22 -04003648 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003649 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
SJW69939d52020-04-16 07:29:07 -05003650 SPIRVCapabilities.push_back(CapInst);
David Neto22f144c2017-06-12 14:26:21 -04003651
alan-bakerf906d2b2019-12-10 11:26:23 -05003652 bool write_without_format = false;
3653 bool sampled_1d = false;
3654 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003655 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003656 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3657 // Generate OpCapability for i8 type.
SJW69939d52020-04-16 07:29:07 -05003658 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003659 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003660 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003661 // Generate OpCapability for i16 type.
SJW69939d52020-04-16 07:29:07 -05003662 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003663 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003664 } else if (Ty->isIntegerTy(64)) {
3665 // Generate OpCapability for i64 type.
SJW69939d52020-04-16 07:29:07 -05003666 SPIRVCapabilities.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05003667 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003668 } else if (Ty->isHalfTy()) {
3669 // Generate OpCapability for half type.
SJW69939d52020-04-16 07:29:07 -05003670 SPIRVCapabilities.push_back(new SPIRVInstruction(
3671 spv::OpCapability, MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003672 } else if (Ty->isDoubleTy()) {
3673 // Generate OpCapability for double type.
SJW69939d52020-04-16 07:29:07 -05003674 SPIRVCapabilities.push_back(new SPIRVInstruction(
3675 spv::OpCapability, MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003676 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3677 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003678 if (STy->getName().startswith("opencl.image1d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003679 STy->getName().startswith("opencl.image1d_array_wo_t") ||
alan-bakerf906d2b2019-12-10 11:26:23 -05003680 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003681 STy->getName().startswith("opencl.image2d_array_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003682 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003683 write_without_format = true;
3684 }
3685 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-baker7150a1d2020-02-25 08:31:06 -05003686 STy->getName().startswith("opencl.image1d_wo_t") ||
3687 STy->getName().startswith("opencl.image1d_array_ro_t") ||
3688 STy->getName().startswith("opencl.image1d_array_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003689 if (STy->getName().contains(".sampled"))
3690 sampled_1d = true;
3691 else
3692 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003693 }
3694 }
3695 }
3696 }
3697
alan-bakerf906d2b2019-12-10 11:26:23 -05003698 if (write_without_format) {
3699 // Generate OpCapability for write only image type.
SJW69939d52020-04-16 07:29:07 -05003700 SPIRVCapabilities.push_back(new SPIRVInstruction(
3701 spv::OpCapability,
3702 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003703 }
3704 if (image_1d) {
3705 // Generate OpCapability for unsampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003706 SPIRVCapabilities.push_back(new SPIRVInstruction(
3707 spv::OpCapability, {MkNum(spv::CapabilityImage1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003708 } else if (sampled_1d) {
3709 // Generate OpCapability for sampled 1D image type.
SJW69939d52020-04-16 07:29:07 -05003710 SPIRVCapabilities.push_back(new SPIRVInstruction(
3711 spv::OpCapability, {MkNum(spv::CapabilitySampled1D)}));
alan-bakerf906d2b2019-12-10 11:26:23 -05003712 }
3713
David Neto5c22a252018-03-15 16:07:41 -04003714 { // OpCapability ImageQuery
3715 bool hasImageQuery = false;
alan-bakerf67468c2019-11-25 15:51:49 -05003716 for (const auto &SymVal : module.getValueSymbolTable()) {
3717 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
SJW173c7e92020-03-16 08:44:47 -05003718 if (IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003719 hasImageQuery = true;
3720 break;
3721 }
David Neto5c22a252018-03-15 16:07:41 -04003722 }
3723 }
alan-bakerf67468c2019-11-25 15:51:49 -05003724
David Neto5c22a252018-03-15 16:07:41 -04003725 if (hasImageQuery) {
SJW69939d52020-04-16 07:29:07 -05003726 SPIRVCapabilities.push_back(new SPIRVInstruction(
3727 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)}));
David Neto5c22a252018-03-15 16:07:41 -04003728 }
3729 }
3730
David Neto22f144c2017-06-12 14:26:21 -04003731 if (hasVariablePointers()) {
3732 //
David Neto22f144c2017-06-12 14:26:21 -04003733 // Generate OpCapability.
3734 //
3735 // Ops[0] = Capability
3736 //
3737 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003738 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003739
SJW69939d52020-04-16 07:29:07 -05003740 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003741 } else if (hasVariablePointersStorageBuffer()) {
3742 //
3743 // Generate OpCapability.
3744 //
3745 // Ops[0] = Capability
3746 //
3747 Ops.clear();
3748 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003749
SJW69939d52020-04-16 07:29:07 -05003750 SPIRVCapabilities.push_back(new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003751 }
3752
SJW69939d52020-04-16 07:29:07 -05003753 SPIRVInstructionList &SPIRVExtensions = getSPIRVInstList(kExtensions);
alan-baker5b86ed72019-02-15 08:26:50 -05003754 // Always add the storage buffer extension
3755 {
David Neto22f144c2017-06-12 14:26:21 -04003756 //
3757 // Generate OpExtension.
3758 //
3759 // Ops[0] = Name (Literal String)
3760 //
alan-baker5b86ed72019-02-15 08:26:50 -05003761 auto *ExtensionInst = new SPIRVInstruction(
3762 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
SJW69939d52020-04-16 07:29:07 -05003763 SPIRVExtensions.push_back(ExtensionInst);
alan-baker5b86ed72019-02-15 08:26:50 -05003764 }
David Neto22f144c2017-06-12 14:26:21 -04003765
alan-baker5b86ed72019-02-15 08:26:50 -05003766 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3767 //
3768 // Generate OpExtension.
3769 //
3770 // Ops[0] = Name (Literal String)
3771 //
3772 auto *ExtensionInst = new SPIRVInstruction(
3773 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
SJW69939d52020-04-16 07:29:07 -05003774 SPIRVExtensions.push_back(ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003775 }
3776
3777 //
3778 // Generate OpMemoryModel
3779 //
3780 // Memory model for Vulkan will always be GLSL450.
3781
3782 // Ops[0] = Addressing Model
3783 // Ops[1] = Memory Model
3784 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003785 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003786
David Neto87846742018-04-11 17:36:22 -04003787 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
SJW69939d52020-04-16 07:29:07 -05003788 getSPIRVInstList(kMemoryModel).push_back(MemModelInst);
David Neto22f144c2017-06-12 14:26:21 -04003789
SJW69939d52020-04-16 07:29:07 -05003790 SPIRVInstructionList &SPIRVEntryPoints = getSPIRVInstList(kEntryPoints);
David Neto22f144c2017-06-12 14:26:21 -04003791 //
3792 // Generate OpEntryPoint
3793 //
3794 for (auto EntryPoint : EntryPoints) {
3795 // Ops[0] = Execution Model
3796 // Ops[1] = EntryPoint ID
3797 // Ops[2] = Name (Literal String)
3798 // ...
3799 //
3800 // TODO: Do we need to consider Interface ID for forward references???
3801 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003802 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003803 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3804 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003805
David Neto22f144c2017-06-12 14:26:21 -04003806 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003807 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003808 }
3809
David Neto87846742018-04-11 17:36:22 -04003810 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
SJW69939d52020-04-16 07:29:07 -05003811 SPIRVEntryPoints.push_back(EntryPointInst);
David Neto22f144c2017-06-12 14:26:21 -04003812 }
3813
SJW69939d52020-04-16 07:29:07 -05003814 SPIRVInstructionList &SPIRVExecutionModes = getSPIRVInstList(kExecutionModes);
David Neto22f144c2017-06-12 14:26:21 -04003815 for (auto EntryPoint : EntryPoints) {
3816 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3817 ->getMetadata("reqd_work_group_size")) {
3818
3819 if (!BuiltinDimVec.empty()) {
3820 llvm_unreachable(
3821 "Kernels should have consistent work group size definition");
3822 }
3823
3824 //
3825 // Generate OpExecutionMode
3826 //
3827
3828 // Ops[0] = Entry Point ID
3829 // Ops[1] = Execution Mode
3830 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3831 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003832 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003833
3834 uint32_t XDim = static_cast<uint32_t>(
3835 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3836 uint32_t YDim = static_cast<uint32_t>(
3837 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3838 uint32_t ZDim = static_cast<uint32_t>(
3839 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3840
David Neto257c3892018-04-11 13:19:45 -04003841 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003842
David Neto87846742018-04-11 17:36:22 -04003843 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
SJW69939d52020-04-16 07:29:07 -05003844 SPIRVExecutionModes.push_back(ExecModeInst);
David Neto22f144c2017-06-12 14:26:21 -04003845 }
3846 }
3847
3848 //
3849 // Generate OpSource.
3850 //
3851 // Ops[0] = SourceLanguage ID
3852 // Ops[1] = Version (LiteralNum)
3853 //
3854 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003855 switch (clspv::Option::Language()) {
3856 case clspv::Option::SourceLanguage::OpenCL_C_10:
3857 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3858 break;
3859 case clspv::Option::SourceLanguage::OpenCL_C_11:
3860 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3861 break;
3862 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003863 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003864 break;
3865 case clspv::Option::SourceLanguage::OpenCL_C_20:
3866 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3867 break;
3868 case clspv::Option::SourceLanguage::OpenCL_CPP:
3869 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3870 break;
3871 default:
3872 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3873 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003874 }
David Neto22f144c2017-06-12 14:26:21 -04003875
David Neto87846742018-04-11 17:36:22 -04003876 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
SJW69939d52020-04-16 07:29:07 -05003877 getSPIRVInstList(kDebug).push_back(OpenSourceInst);
David Neto22f144c2017-06-12 14:26:21 -04003878
3879 if (!BuiltinDimVec.empty()) {
SJW69939d52020-04-16 07:29:07 -05003880 SPIRVInstructionList &SPIRVAnnotations = getSPIRVInstList(kAnnotations);
David Neto22f144c2017-06-12 14:26:21 -04003881 //
3882 // Generate OpDecorates for x/y/z dimension.
3883 //
3884 // Ops[0] = Target ID
3885 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003886 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003887
3888 // X Dimension
3889 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003890 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
SJW69939d52020-04-16 07:29:07 -05003891 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003892
3893 // Y Dimension
3894 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003895 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
SJW69939d52020-04-16 07:29:07 -05003896 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003897
3898 // Z Dimension
3899 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003900 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
SJW69939d52020-04-16 07:29:07 -05003901 SPIRVAnnotations.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003902 }
3903}
3904
David Netob6e2e062018-04-25 10:32:06 -04003905void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3906 // Work around a driver bug. Initializers on Private variables might not
3907 // work. So the start of the kernel should store the initializer value to the
3908 // variables. Yes, *every* entry point pays this cost if *any* entry point
3909 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3910 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003911 // TODO(dneto): Remove this at some point once fixed drivers are widely
3912 // available.
David Netob6e2e062018-04-25 10:32:06 -04003913 if (WorkgroupSizeVarID) {
3914 assert(WorkgroupSizeValueID);
3915
3916 SPIRVOperandList Ops;
3917 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3918
3919 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
SJW69939d52020-04-16 07:29:07 -05003920 getSPIRVInstList(kFunctions).push_back(Inst);
David Netob6e2e062018-04-25 10:32:06 -04003921 }
3922}
3923
David Neto22f144c2017-06-12 14:26:21 -04003924void SPIRVProducerPass::GenerateFuncBody(Function &F) {
SJW69939d52020-04-16 07:29:07 -05003925 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04003926 ValueMapType &VMap = getValueMap();
3927
David Netob6e2e062018-04-25 10:32:06 -04003928 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003929
3930 for (BasicBlock &BB : F) {
3931 // Register BasicBlock to ValueMap.
3932 VMap[&BB] = nextID;
3933
3934 //
3935 // Generate OpLabel for Basic Block.
3936 //
3937 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003938 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003939 SPIRVInstList.push_back(Inst);
3940
David Neto6dcd4712017-06-23 11:06:47 -04003941 // OpVariable instructions must come first.
3942 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003943 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3944 // Allocating a pointer requires variable pointers.
3945 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003946 setVariablePointersCapabilities(
3947 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003948 }
David Neto6dcd4712017-06-23 11:06:47 -04003949 GenerateInstruction(I);
3950 }
3951 }
3952
David Neto22f144c2017-06-12 14:26:21 -04003953 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003954 if (clspv::Option::HackInitializers()) {
3955 GenerateEntryPointInitialStores();
3956 }
David Neto22f144c2017-06-12 14:26:21 -04003957 }
3958
3959 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003960 if (!isa<AllocaInst>(I)) {
3961 GenerateInstruction(I);
3962 }
David Neto22f144c2017-06-12 14:26:21 -04003963 }
3964 }
3965}
3966
3967spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3968 const std::map<CmpInst::Predicate, spv::Op> Map = {
3969 {CmpInst::ICMP_EQ, spv::OpIEqual},
3970 {CmpInst::ICMP_NE, spv::OpINotEqual},
3971 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3972 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3973 {CmpInst::ICMP_ULT, spv::OpULessThan},
3974 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3975 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3976 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3977 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3978 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3979 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3980 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3981 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3982 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3983 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3984 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3985 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3986 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3987 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3988 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3989 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3990 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3991
3992 assert(0 != Map.count(I->getPredicate()));
3993
3994 return Map.at(I->getPredicate());
3995}
3996
3997spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3998 const std::map<unsigned, spv::Op> Map{
3999 {Instruction::Trunc, spv::OpUConvert},
4000 {Instruction::ZExt, spv::OpUConvert},
4001 {Instruction::SExt, spv::OpSConvert},
4002 {Instruction::FPToUI, spv::OpConvertFToU},
4003 {Instruction::FPToSI, spv::OpConvertFToS},
4004 {Instruction::UIToFP, spv::OpConvertUToF},
4005 {Instruction::SIToFP, spv::OpConvertSToF},
4006 {Instruction::FPTrunc, spv::OpFConvert},
4007 {Instruction::FPExt, spv::OpFConvert},
4008 {Instruction::BitCast, spv::OpBitcast}};
4009
4010 assert(0 != Map.count(I.getOpcode()));
4011
4012 return Map.at(I.getOpcode());
4013}
4014
4015spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00004016 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004017 switch (I.getOpcode()) {
4018 default:
4019 break;
4020 case Instruction::Or:
4021 return spv::OpLogicalOr;
4022 case Instruction::And:
4023 return spv::OpLogicalAnd;
4024 case Instruction::Xor:
4025 return spv::OpLogicalNotEqual;
4026 }
4027 }
4028
alan-bakerb6b09dc2018-11-08 16:59:28 -05004029 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04004030 {Instruction::Add, spv::OpIAdd},
4031 {Instruction::FAdd, spv::OpFAdd},
4032 {Instruction::Sub, spv::OpISub},
4033 {Instruction::FSub, spv::OpFSub},
4034 {Instruction::Mul, spv::OpIMul},
4035 {Instruction::FMul, spv::OpFMul},
4036 {Instruction::UDiv, spv::OpUDiv},
4037 {Instruction::SDiv, spv::OpSDiv},
4038 {Instruction::FDiv, spv::OpFDiv},
4039 {Instruction::URem, spv::OpUMod},
4040 {Instruction::SRem, spv::OpSRem},
4041 {Instruction::FRem, spv::OpFRem},
4042 {Instruction::Or, spv::OpBitwiseOr},
4043 {Instruction::Xor, spv::OpBitwiseXor},
4044 {Instruction::And, spv::OpBitwiseAnd},
4045 {Instruction::Shl, spv::OpShiftLeftLogical},
4046 {Instruction::LShr, spv::OpShiftRightLogical},
4047 {Instruction::AShr, spv::OpShiftRightArithmetic}};
4048
4049 assert(0 != Map.count(I.getOpcode()));
4050
4051 return Map.at(I.getOpcode());
4052}
4053
4054void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
SJW69939d52020-04-16 07:29:07 -05004055 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04004056 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04004057 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4058 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
4059
4060 // Register Instruction to ValueMap.
4061 if (0 == VMap[&I]) {
4062 VMap[&I] = nextID;
4063 }
4064
4065 switch (I.getOpcode()) {
4066 default: {
4067 if (Instruction::isCast(I.getOpcode())) {
4068 //
4069 // Generate SPIRV instructions for cast operators.
4070 //
4071
David Netod2de94a2017-08-28 17:27:47 -04004072 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004073 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04004074 auto toI8 = Ty == Type::getInt8Ty(Context);
4075 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04004076 // Handle zext, sext and uitofp with i1 type specially.
4077 if ((I.getOpcode() == Instruction::ZExt ||
4078 I.getOpcode() == Instruction::SExt ||
4079 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05004080 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04004081 //
4082 // Generate OpSelect.
4083 //
4084
4085 // Ops[0] = Result Type ID
4086 // Ops[1] = Condition ID
4087 // Ops[2] = True Constant ID
4088 // Ops[3] = False Constant ID
4089 SPIRVOperandList Ops;
4090
David Neto257c3892018-04-11 13:19:45 -04004091 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004092
David Neto22f144c2017-06-12 14:26:21 -04004093 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004094 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04004095
4096 uint32_t TrueID = 0;
4097 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004098 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04004099 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00004100 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04004101 } else {
4102 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
4103 }
David Neto257c3892018-04-11 13:19:45 -04004104 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04004105
4106 uint32_t FalseID = 0;
4107 if (I.getOpcode() == Instruction::ZExt) {
4108 FalseID = VMap[Constant::getNullValue(I.getType())];
4109 } else if (I.getOpcode() == Instruction::SExt) {
4110 FalseID = VMap[Constant::getNullValue(I.getType())];
4111 } else {
4112 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
4113 }
David Neto257c3892018-04-11 13:19:45 -04004114 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04004115
David Neto87846742018-04-11 17:36:22 -04004116 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004117 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05004118 } else if (!clspv::Option::Int8Support() &&
4119 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04004120 // The SPIR-V target type is a 32-bit int. Keep only the bottom
4121 // 8 bits.
4122 // Before:
4123 // %result = trunc i32 %a to i8
4124 // After
4125 // %result = OpBitwiseAnd %uint %a %uint_255
4126
4127 SPIRVOperandList Ops;
4128
David Neto257c3892018-04-11 13:19:45 -04004129 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04004130
4131 Type *UintTy = Type::getInt32Ty(Context);
4132 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04004133 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04004134
David Neto87846742018-04-11 17:36:22 -04004135 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04004136 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004137 } else {
4138 // Ops[0] = Result Type ID
4139 // Ops[1] = Source Value ID
4140 SPIRVOperandList Ops;
4141
David Neto257c3892018-04-11 13:19:45 -04004142 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004143
David Neto87846742018-04-11 17:36:22 -04004144 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004145 SPIRVInstList.push_back(Inst);
4146 }
4147 } else if (isa<BinaryOperator>(I)) {
4148 //
4149 // Generate SPIRV instructions for binary operators.
4150 //
4151
4152 // Handle xor with i1 type specially.
4153 if (I.getOpcode() == Instruction::Xor &&
4154 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00004155 ((isa<ConstantInt>(I.getOperand(0)) &&
4156 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
4157 (isa<ConstantInt>(I.getOperand(1)) &&
4158 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04004159 //
4160 // Generate OpLogicalNot.
4161 //
4162 // Ops[0] = Result Type ID
4163 // Ops[1] = Operand
4164 SPIRVOperandList Ops;
4165
David Neto257c3892018-04-11 13:19:45 -04004166 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004167
4168 Value *CondV = I.getOperand(0);
4169 if (isa<Constant>(I.getOperand(0))) {
4170 CondV = I.getOperand(1);
4171 }
David Neto257c3892018-04-11 13:19:45 -04004172 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04004173
David Neto87846742018-04-11 17:36:22 -04004174 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004175 SPIRVInstList.push_back(Inst);
4176 } else {
4177 // Ops[0] = Result Type ID
4178 // Ops[1] = Operand 0
4179 // Ops[2] = Operand 1
4180 SPIRVOperandList Ops;
4181
David Neto257c3892018-04-11 13:19:45 -04004182 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4183 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004184
David Neto87846742018-04-11 17:36:22 -04004185 auto *Inst =
4186 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004187 SPIRVInstList.push_back(Inst);
4188 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05004189 } else if (I.getOpcode() == Instruction::FNeg) {
4190 // The only unary operator.
4191 //
4192 // Ops[0] = Result Type ID
4193 // Ops[1] = Operand 0
4194 SPIRVOperandList ops;
4195
4196 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
4197 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
4198 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004199 } else {
4200 I.print(errs());
4201 llvm_unreachable("Unsupported instruction???");
4202 }
4203 break;
4204 }
4205 case Instruction::GetElementPtr: {
4206 auto &GlobalConstArgSet = getGlobalConstArgSet();
4207
4208 //
4209 // Generate OpAccessChain.
4210 //
4211 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
4212
4213 //
4214 // Generate OpAccessChain.
4215 //
4216
4217 // Ops[0] = Result Type ID
4218 // Ops[1] = Base ID
4219 // Ops[2] ... Ops[n] = Indexes ID
4220 SPIRVOperandList Ops;
4221
alan-bakerb6b09dc2018-11-08 16:59:28 -05004222 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04004223 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
4224 GlobalConstArgSet.count(GEP->getPointerOperand())) {
4225 // Use pointer type with private address space for global constant.
4226 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04004227 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04004228 }
David Neto257c3892018-04-11 13:19:45 -04004229
4230 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04004231
David Neto862b7d82018-06-14 18:48:37 -04004232 // Generate the base pointer.
4233 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004234
David Neto862b7d82018-06-14 18:48:37 -04004235 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04004236
4237 //
4238 // Follows below rules for gep.
4239 //
David Neto862b7d82018-06-14 18:48:37 -04004240 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
4241 // first index.
David Neto22f144c2017-06-12 14:26:21 -04004242 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
4243 // first index.
4244 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
4245 // use gep's first index.
4246 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4247 // gep's first index.
4248 //
4249 spv::Op Opcode = spv::OpAccessChain;
4250 unsigned offset = 0;
4251 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004252 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004253 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004254 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004255 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004256 }
David Neto862b7d82018-06-14 18:48:37 -04004257 } else {
David Neto22f144c2017-06-12 14:26:21 -04004258 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004259 }
4260
4261 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04004262 // Do we need to generate ArrayStride? Check against the GEP result type
4263 // rather than the pointer type of the base because when indexing into
4264 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
4265 // for something else in the SPIR-V.
4266 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05004267 auto address_space = ResultType->getAddressSpace();
4268 setVariablePointersCapabilities(address_space);
4269 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004270 case spv::StorageClassStorageBuffer:
4271 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04004272 // Save the need to generate an ArrayStride decoration. But defer
4273 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07004274 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04004275 break;
4276 default:
4277 break;
David Neto1a1a0582017-07-07 12:01:44 -04004278 }
David Neto22f144c2017-06-12 14:26:21 -04004279 }
4280
4281 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04004282 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04004283 }
4284
David Neto87846742018-04-11 17:36:22 -04004285 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004286 SPIRVInstList.push_back(Inst);
4287 break;
4288 }
4289 case Instruction::ExtractValue: {
4290 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4291 // Ops[0] = Result Type ID
4292 // Ops[1] = Composite ID
4293 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4294 SPIRVOperandList Ops;
4295
David Neto257c3892018-04-11 13:19:45 -04004296 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004297
4298 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004299 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004300
4301 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004302 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004303 }
4304
David Neto87846742018-04-11 17:36:22 -04004305 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004306 SPIRVInstList.push_back(Inst);
4307 break;
4308 }
4309 case Instruction::InsertValue: {
4310 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4311 // Ops[0] = Result Type ID
4312 // Ops[1] = Object ID
4313 // Ops[2] = Composite ID
4314 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4315 SPIRVOperandList Ops;
4316
4317 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004318 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004319
4320 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004321 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004322
4323 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004324 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004325
4326 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004327 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004328 }
4329
David Neto87846742018-04-11 17:36:22 -04004330 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004331 SPIRVInstList.push_back(Inst);
4332 break;
4333 }
4334 case Instruction::Select: {
4335 //
4336 // Generate OpSelect.
4337 //
4338
4339 // Ops[0] = Result Type ID
4340 // Ops[1] = Condition ID
4341 // Ops[2] = True Constant ID
4342 // Ops[3] = False Constant ID
4343 SPIRVOperandList Ops;
4344
4345 // Find SPIRV instruction for parameter type.
4346 auto Ty = I.getType();
4347 if (Ty->isPointerTy()) {
4348 auto PointeeTy = Ty->getPointerElementType();
4349 if (PointeeTy->isStructTy() &&
4350 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4351 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004352 } else {
4353 // Selecting between pointers requires variable pointers.
4354 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4355 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4356 setVariablePointers(true);
4357 }
David Neto22f144c2017-06-12 14:26:21 -04004358 }
4359 }
4360
David Neto257c3892018-04-11 13:19:45 -04004361 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4362 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004363
David Neto87846742018-04-11 17:36:22 -04004364 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004365 SPIRVInstList.push_back(Inst);
4366 break;
4367 }
4368 case Instruction::ExtractElement: {
4369 // Handle <4 x i8> type manually.
4370 Type *CompositeTy = I.getOperand(0)->getType();
4371 if (is4xi8vec(CompositeTy)) {
4372 //
4373 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4374 // <4 x i8>.
4375 //
4376
4377 //
4378 // Generate OpShiftRightLogical
4379 //
4380 // Ops[0] = Result Type ID
4381 // Ops[1] = Operand 0
4382 // Ops[2] = Operand 1
4383 //
4384 SPIRVOperandList Ops;
4385
David Neto257c3892018-04-11 13:19:45 -04004386 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004387
4388 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004389 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004390
4391 uint32_t Op1ID = 0;
4392 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4393 // Handle constant index.
4394 uint64_t Idx = CI->getZExtValue();
4395 Value *ShiftAmount =
4396 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4397 Op1ID = VMap[ShiftAmount];
4398 } else {
4399 // Handle variable index.
4400 SPIRVOperandList TmpOps;
4401
David Neto257c3892018-04-11 13:19:45 -04004402 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4403 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004404
4405 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004406 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004407
4408 Op1ID = nextID;
4409
David Neto87846742018-04-11 17:36:22 -04004410 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004411 SPIRVInstList.push_back(TmpInst);
4412 }
David Neto257c3892018-04-11 13:19:45 -04004413 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004414
4415 uint32_t ShiftID = nextID;
4416
David Neto87846742018-04-11 17:36:22 -04004417 auto *Inst =
4418 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004419 SPIRVInstList.push_back(Inst);
4420
4421 //
4422 // Generate OpBitwiseAnd
4423 //
4424 // Ops[0] = Result Type ID
4425 // Ops[1] = Operand 0
4426 // Ops[2] = Operand 1
4427 //
4428 Ops.clear();
4429
David Neto257c3892018-04-11 13:19:45 -04004430 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004431
4432 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004433 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004434
David Neto9b2d6252017-09-06 15:47:37 -04004435 // Reset mapping for this value to the result of the bitwise and.
4436 VMap[&I] = nextID;
4437
David Neto87846742018-04-11 17:36:22 -04004438 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004439 SPIRVInstList.push_back(Inst);
4440 break;
4441 }
4442
4443 // Ops[0] = Result Type ID
4444 // Ops[1] = Composite ID
4445 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4446 SPIRVOperandList Ops;
4447
David Neto257c3892018-04-11 13:19:45 -04004448 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004449
4450 spv::Op Opcode = spv::OpCompositeExtract;
4451 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004452 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004453 } else {
David Neto257c3892018-04-11 13:19:45 -04004454 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004455 Opcode = spv::OpVectorExtractDynamic;
4456 }
4457
David Neto87846742018-04-11 17:36:22 -04004458 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004459 SPIRVInstList.push_back(Inst);
4460 break;
4461 }
4462 case Instruction::InsertElement: {
4463 // Handle <4 x i8> type manually.
4464 Type *CompositeTy = I.getOperand(0)->getType();
4465 if (is4xi8vec(CompositeTy)) {
4466 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4467 uint32_t CstFFID = VMap[CstFF];
4468
4469 uint32_t ShiftAmountID = 0;
4470 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4471 // Handle constant index.
4472 uint64_t Idx = CI->getZExtValue();
4473 Value *ShiftAmount =
4474 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4475 ShiftAmountID = VMap[ShiftAmount];
4476 } else {
4477 // Handle variable index.
4478 SPIRVOperandList TmpOps;
4479
David Neto257c3892018-04-11 13:19:45 -04004480 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4481 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004482
4483 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004484 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004485
4486 ShiftAmountID = nextID;
4487
David Neto87846742018-04-11 17:36:22 -04004488 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004489 SPIRVInstList.push_back(TmpInst);
4490 }
4491
4492 //
4493 // Generate mask operations.
4494 //
4495
4496 // ShiftLeft mask according to index of insertelement.
4497 SPIRVOperandList Ops;
4498
David Neto257c3892018-04-11 13:19:45 -04004499 const uint32_t ResTyID = lookupType(CompositeTy);
4500 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004501
4502 uint32_t MaskID = nextID;
4503
David Neto87846742018-04-11 17:36:22 -04004504 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004505 SPIRVInstList.push_back(Inst);
4506
4507 // Inverse mask.
4508 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004509 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004510
4511 uint32_t InvMaskID = nextID;
4512
David Neto87846742018-04-11 17:36:22 -04004513 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004514 SPIRVInstList.push_back(Inst);
4515
4516 // Apply mask.
4517 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004518 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004519
4520 uint32_t OrgValID = nextID;
4521
David Neto87846742018-04-11 17:36:22 -04004522 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004523 SPIRVInstList.push_back(Inst);
4524
4525 // Create correct value according to index of insertelement.
4526 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004527 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4528 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004529
4530 uint32_t InsertValID = nextID;
4531
David Neto87846742018-04-11 17:36:22 -04004532 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004533 SPIRVInstList.push_back(Inst);
4534
4535 // Insert value to original value.
4536 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004537 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004538
David Netoa394f392017-08-26 20:45:29 -04004539 VMap[&I] = nextID;
4540
David Neto87846742018-04-11 17:36:22 -04004541 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004542 SPIRVInstList.push_back(Inst);
4543
4544 break;
4545 }
4546
David Neto22f144c2017-06-12 14:26:21 -04004547 SPIRVOperandList Ops;
4548
James Priced26efea2018-06-09 23:28:32 +01004549 // Ops[0] = Result Type ID
4550 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004551
4552 spv::Op Opcode = spv::OpCompositeInsert;
4553 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004554 const auto value = CI->getZExtValue();
4555 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004556 // Ops[1] = Object ID
4557 // Ops[2] = Composite ID
4558 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004559 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004560 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004561 } else {
James Priced26efea2018-06-09 23:28:32 +01004562 // Ops[1] = Composite ID
4563 // Ops[2] = Object ID
4564 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004565 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004566 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004567 Opcode = spv::OpVectorInsertDynamic;
4568 }
4569
David Neto87846742018-04-11 17:36:22 -04004570 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004571 SPIRVInstList.push_back(Inst);
4572 break;
4573 }
4574 case Instruction::ShuffleVector: {
4575 // Ops[0] = Result Type ID
4576 // Ops[1] = Vector 1 ID
4577 // Ops[2] = Vector 2 ID
4578 // Ops[3] ... Ops[n] = Components (Literal Number)
4579 SPIRVOperandList Ops;
4580
David Neto257c3892018-04-11 13:19:45 -04004581 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4582 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004583
alan-bakerc9666712020-04-01 16:31:21 -04004584 auto shuffle = cast<ShuffleVectorInst>(&I);
4585 SmallVector<int, 4> mask;
4586 shuffle->getShuffleMask(mask);
4587 for (auto i : mask) {
4588 if (i == UndefMaskElem) {
4589 if (clspv::Option::HackUndef())
4590 // Use 0 instead of undef.
David Neto257c3892018-04-11 13:19:45 -04004591 Ops << MkNum(0);
alan-bakerc9666712020-04-01 16:31:21 -04004592 else
4593 // Undef for shuffle in SPIR-V.
4594 Ops << MkNum(0xffffffff);
David Neto22f144c2017-06-12 14:26:21 -04004595 } else {
alan-bakerc9666712020-04-01 16:31:21 -04004596 Ops << MkNum(i);
David Neto22f144c2017-06-12 14:26:21 -04004597 }
4598 }
4599
David Neto87846742018-04-11 17:36:22 -04004600 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004601 SPIRVInstList.push_back(Inst);
4602 break;
4603 }
4604 case Instruction::ICmp:
4605 case Instruction::FCmp: {
4606 CmpInst *CmpI = cast<CmpInst>(&I);
4607
David Netod4ca2e62017-07-06 18:47:35 -04004608 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004609 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004610 if (isa<PointerType>(ArgTy)) {
4611 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004612 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004613 errs()
4614 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4615 << "in function " << name << "\n";
4616 llvm_unreachable("Pointer equality check is invalid");
4617 break;
4618 }
4619
David Neto257c3892018-04-11 13:19:45 -04004620 // Ops[0] = Result Type ID
4621 // Ops[1] = Operand 1 ID
4622 // Ops[2] = Operand 2 ID
4623 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004624
David Neto257c3892018-04-11 13:19:45 -04004625 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4626 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004627
4628 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004629 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004630 SPIRVInstList.push_back(Inst);
4631 break;
4632 }
4633 case Instruction::Br: {
4634 // Branch instrucion is deferred because it needs label's ID. Record slot's
4635 // location on SPIRVInstructionList.
4636 DeferredInsts.push_back(
4637 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4638 break;
4639 }
4640 case Instruction::Switch: {
4641 I.print(errs());
4642 llvm_unreachable("Unsupported instruction???");
4643 break;
4644 }
4645 case Instruction::IndirectBr: {
4646 I.print(errs());
4647 llvm_unreachable("Unsupported instruction???");
4648 break;
4649 }
4650 case Instruction::PHI: {
4651 // Branch instrucion is deferred because it needs label's ID. Record slot's
4652 // location on SPIRVInstructionList.
4653 DeferredInsts.push_back(
4654 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4655 break;
4656 }
4657 case Instruction::Alloca: {
4658 //
4659 // Generate OpVariable.
4660 //
4661 // Ops[0] : Result Type ID
4662 // Ops[1] : Storage Class
4663 SPIRVOperandList Ops;
4664
David Neto257c3892018-04-11 13:19:45 -04004665 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004666
David Neto87846742018-04-11 17:36:22 -04004667 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004668 SPIRVInstList.push_back(Inst);
4669 break;
4670 }
4671 case Instruction::Load: {
4672 LoadInst *LD = cast<LoadInst>(&I);
4673 //
4674 // Generate OpLoad.
4675 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004676
alan-baker5b86ed72019-02-15 08:26:50 -05004677 if (LD->getType()->isPointerTy()) {
4678 // Loading a pointer requires variable pointers.
4679 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4680 }
David Neto22f144c2017-06-12 14:26:21 -04004681
David Neto0a2f98d2017-09-15 19:38:40 -04004682 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004683 uint32_t PointerID = VMap[LD->getPointerOperand()];
4684
4685 // This is a hack to work around what looks like a driver bug.
4686 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004687 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4688 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004689 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004690 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004691 // Generate a bitwise-and of the original value with itself.
4692 // We should have been able to get away with just an OpCopyObject,
4693 // but we need something more complex to get past certain driver bugs.
4694 // This is ridiculous, but necessary.
4695 // TODO(dneto): Revisit this once drivers fix their bugs.
4696
4697 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004698 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4699 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004700
David Neto87846742018-04-11 17:36:22 -04004701 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004702 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004703 break;
4704 }
4705
4706 // This is the normal path. Generate a load.
4707
David Neto22f144c2017-06-12 14:26:21 -04004708 // Ops[0] = Result Type ID
4709 // Ops[1] = Pointer ID
4710 // Ops[2] ... Ops[n] = Optional Memory Access
4711 //
4712 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004713
David Neto22f144c2017-06-12 14:26:21 -04004714 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004715 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004716
David Neto87846742018-04-11 17:36:22 -04004717 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004718 SPIRVInstList.push_back(Inst);
4719 break;
4720 }
4721 case Instruction::Store: {
4722 StoreInst *ST = cast<StoreInst>(&I);
4723 //
4724 // Generate OpStore.
4725 //
4726
alan-baker5b86ed72019-02-15 08:26:50 -05004727 if (ST->getValueOperand()->getType()->isPointerTy()) {
4728 // Storing a pointer requires variable pointers.
4729 setVariablePointersCapabilities(
4730 ST->getValueOperand()->getType()->getPointerAddressSpace());
4731 }
4732
David Neto22f144c2017-06-12 14:26:21 -04004733 // Ops[0] = Pointer ID
4734 // Ops[1] = Object ID
4735 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4736 //
4737 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004738 SPIRVOperandList Ops;
4739 Ops << MkId(VMap[ST->getPointerOperand()])
4740 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004741
David Neto87846742018-04-11 17:36:22 -04004742 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004743 SPIRVInstList.push_back(Inst);
4744 break;
4745 }
4746 case Instruction::AtomicCmpXchg: {
4747 I.print(errs());
4748 llvm_unreachable("Unsupported instruction???");
4749 break;
4750 }
4751 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004752 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4753
4754 spv::Op opcode;
4755
4756 switch (AtomicRMW->getOperation()) {
4757 default:
4758 I.print(errs());
4759 llvm_unreachable("Unsupported instruction???");
4760 case llvm::AtomicRMWInst::Add:
4761 opcode = spv::OpAtomicIAdd;
4762 break;
4763 case llvm::AtomicRMWInst::Sub:
4764 opcode = spv::OpAtomicISub;
4765 break;
4766 case llvm::AtomicRMWInst::Xchg:
4767 opcode = spv::OpAtomicExchange;
4768 break;
4769 case llvm::AtomicRMWInst::Min:
4770 opcode = spv::OpAtomicSMin;
4771 break;
4772 case llvm::AtomicRMWInst::Max:
4773 opcode = spv::OpAtomicSMax;
4774 break;
4775 case llvm::AtomicRMWInst::UMin:
4776 opcode = spv::OpAtomicUMin;
4777 break;
4778 case llvm::AtomicRMWInst::UMax:
4779 opcode = spv::OpAtomicUMax;
4780 break;
4781 case llvm::AtomicRMWInst::And:
4782 opcode = spv::OpAtomicAnd;
4783 break;
4784 case llvm::AtomicRMWInst::Or:
4785 opcode = spv::OpAtomicOr;
4786 break;
4787 case llvm::AtomicRMWInst::Xor:
4788 opcode = spv::OpAtomicXor;
4789 break;
4790 }
4791
4792 //
4793 // Generate OpAtomic*.
4794 //
4795 SPIRVOperandList Ops;
4796
David Neto257c3892018-04-11 13:19:45 -04004797 Ops << MkId(lookupType(I.getType()))
4798 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004799
4800 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004801 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004802 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004803
4804 const auto ConstantMemorySemantics = ConstantInt::get(
4805 IntTy, spv::MemorySemanticsUniformMemoryMask |
4806 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004807 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004808
David Neto257c3892018-04-11 13:19:45 -04004809 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004810
4811 VMap[&I] = nextID;
4812
David Neto87846742018-04-11 17:36:22 -04004813 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004814 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004815 break;
4816 }
4817 case Instruction::Fence: {
4818 I.print(errs());
4819 llvm_unreachable("Unsupported instruction???");
4820 break;
4821 }
4822 case Instruction::Call: {
4823 CallInst *Call = dyn_cast<CallInst>(&I);
4824 Function *Callee = Call->getCalledFunction();
4825
Alan Baker202c8c72018-08-13 13:47:44 -04004826 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004827 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4828 // Generate an OpLoad
4829 SPIRVOperandList Ops;
4830 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004831
David Neto862b7d82018-06-14 18:48:37 -04004832 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4833 << MkId(ResourceVarDeferredLoadCalls[Call]);
4834
4835 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4836 SPIRVInstList.push_back(Inst);
4837 VMap[Call] = load_id;
4838 break;
4839
4840 } else {
4841 // This maps to an OpVariable we've already generated.
4842 // No code is generated for the call.
4843 }
4844 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004845 } else if (Callee->getName().startswith(
4846 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004847 // Don't codegen an instruction here, but instead map this call directly
4848 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004849 int spec_id = static_cast<int>(
4850 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004851 const auto &info = LocalSpecIdInfoMap[spec_id];
4852 VMap[Call] = info.variable_id;
4853 break;
David Neto862b7d82018-06-14 18:48:37 -04004854 }
4855
4856 // Sampler initializers become a load of the corresponding sampler.
4857
Kévin Petitdf71de32019-04-09 14:09:50 +01004858 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004859 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004860 const auto third_param = static_cast<unsigned>(
4861 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4862 auto sampler_value = third_param;
4863 if (clspv::Option::UseSamplerMap()) {
4864 sampler_value = getSamplerMap()[third_param].first;
4865 }
David Neto862b7d82018-06-14 18:48:37 -04004866
4867 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004868 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004869 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004870
David Neto257c3892018-04-11 13:19:45 -04004871 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004872 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004873
David Neto862b7d82018-06-14 18:48:37 -04004874 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004875 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004876 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004877 break;
4878 }
4879
Kévin Petit349c9502019-03-28 17:24:14 +00004880 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004881 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4882 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4883 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004884
Kévin Petit617a76d2019-04-04 13:54:16 +01004885 // If the switch above didn't have an entry maybe the intrinsic
4886 // is using the name mangling logic.
4887 bool usesMangler = false;
4888 if (opcode == spv::OpNop) {
4889 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4890 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4891 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4892 usesMangler = true;
4893 }
4894 }
4895
Kévin Petit349c9502019-03-28 17:24:14 +00004896 if (opcode != spv::OpNop) {
4897
David Neto22f144c2017-06-12 14:26:21 -04004898 SPIRVOperandList Ops;
4899
Kévin Petit349c9502019-03-28 17:24:14 +00004900 if (!I.getType()->isVoidTy()) {
4901 Ops << MkId(lookupType(I.getType()));
4902 }
David Neto22f144c2017-06-12 14:26:21 -04004903
Kévin Petit617a76d2019-04-04 13:54:16 +01004904 unsigned firstOperand = usesMangler ? 1 : 0;
4905 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004906 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004907 }
4908
Kévin Petit349c9502019-03-28 17:24:14 +00004909 if (!I.getType()->isVoidTy()) {
4910 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004911 }
4912
Kévin Petit349c9502019-03-28 17:24:14 +00004913 SPIRVInstruction *Inst;
4914 if (!I.getType()->isVoidTy()) {
4915 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4916 } else {
4917 Inst = new SPIRVInstruction(opcode, Ops);
4918 }
Kévin Petit8a560882019-03-21 15:24:34 +00004919 SPIRVInstList.push_back(Inst);
4920 break;
4921 }
4922
David Neto22f144c2017-06-12 14:26:21 -04004923 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4924 if (Callee->getName().startswith("spirv.copy_memory")) {
4925 //
4926 // Generate OpCopyMemory.
4927 //
4928
4929 // Ops[0] = Dst ID
4930 // Ops[1] = Src ID
4931 // Ops[2] = Memory Access
4932 // Ops[3] = Alignment
4933
4934 auto IsVolatile =
4935 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4936
4937 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4938 : spv::MemoryAccessMaskNone;
4939
4940 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4941
4942 auto Alignment =
4943 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4944
David Neto257c3892018-04-11 13:19:45 -04004945 SPIRVOperandList Ops;
4946 Ops << MkId(VMap[Call->getArgOperand(0)])
4947 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4948 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004949
David Neto87846742018-04-11 17:36:22 -04004950 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004951
4952 SPIRVInstList.push_back(Inst);
4953
4954 break;
4955 }
4956
SJW2c317da2020-03-23 07:39:13 -05004957 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4958 // Additionally, OpTypeSampledImage is generated.
SJW173c7e92020-03-16 08:44:47 -05004959 if (IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004960 //
4961 // Generate OpSampledImage.
4962 //
4963 // Ops[0] = Result Type ID
4964 // Ops[1] = Image ID
4965 // Ops[2] = Sampler ID
4966 //
4967 SPIRVOperandList Ops;
4968
4969 Value *Image = Call->getArgOperand(0);
4970 Value *Sampler = Call->getArgOperand(1);
4971 Value *Coordinate = Call->getArgOperand(2);
4972
4973 TypeMapType &OpImageTypeMap = getImageTypeMap();
4974 Type *ImageTy = Image->getType()->getPointerElementType();
4975 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004976 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004977 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004978
4979 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004980
4981 uint32_t SampledImageID = nextID;
4982
David Neto87846742018-04-11 17:36:22 -04004983 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004984 SPIRVInstList.push_back(Inst);
4985
4986 //
4987 // Generate OpImageSampleExplicitLod.
4988 //
4989 // Ops[0] = Result Type ID
4990 // Ops[1] = Sampled Image ID
4991 // Ops[2] = Coordinate ID
4992 // Ops[3] = Image Operands Type ID
4993 // Ops[4] ... Ops[n] = Operands ID
4994 //
4995 Ops.clear();
4996
alan-bakerf67468c2019-11-25 15:51:49 -05004997 const bool is_int_image = IsIntImageType(Image->getType());
4998 uint32_t result_type = 0;
4999 if (is_int_image) {
5000 result_type = v4int32ID;
5001 } else {
5002 result_type = lookupType(Call->getType());
5003 }
5004
5005 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
5006 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04005007
5008 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04005009 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04005010
alan-bakerf67468c2019-11-25 15:51:49 -05005011 uint32_t final_id = nextID++;
5012 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04005013
alan-bakerf67468c2019-11-25 15:51:49 -05005014 uint32_t image_id = final_id;
5015 if (is_int_image) {
5016 // Int image requires a bitcast from v4int to v4uint.
5017 image_id = nextID++;
5018 }
5019
5020 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005021 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05005022
5023 if (is_int_image) {
5024 // Generate the bitcast.
5025 Ops.clear();
5026 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5027 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5028 SPIRVInstList.push_back(Inst);
5029 }
David Neto22f144c2017-06-12 14:26:21 -04005030 break;
5031 }
5032
alan-baker75090e42020-02-20 11:21:04 -05005033 // read_image (without a sampler) is mapped to OpImageFetch.
SJW173c7e92020-03-16 08:44:47 -05005034 if (IsUnsampledImageRead(Callee)) {
alan-baker75090e42020-02-20 11:21:04 -05005035 Value *Image = Call->getArgOperand(0);
5036 Value *Coordinate = Call->getArgOperand(1);
5037
5038 //
5039 // Generate OpImageFetch
5040 //
5041 // Ops[0] = Result Type ID
5042 // Ops[1] = Image ID
5043 // Ops[2] = Coordinate ID
5044 // Ops[3] = Lod
5045 // Ops[4] = 0
5046 //
5047 SPIRVOperandList Ops;
5048
5049 const bool is_int_image = IsIntImageType(Image->getType());
5050 uint32_t result_type = 0;
5051 if (is_int_image) {
5052 result_type = v4int32ID;
5053 } else {
5054 result_type = lookupType(Call->getType());
5055 }
5056
5057 Ops << MkId(result_type) << MkId(VMap[Image]) << MkId(VMap[Coordinate])
5058 << MkNum(spv::ImageOperandsLodMask);
5059
5060 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5061 Ops << MkId(VMap[CstInt0]);
5062
5063 uint32_t final_id = nextID++;
5064 VMap[&I] = final_id;
5065
5066 uint32_t image_id = final_id;
5067 if (is_int_image) {
5068 // Int image requires a bitcast from v4int to v4uint.
5069 image_id = nextID++;
5070 }
5071
5072 auto *Inst = new SPIRVInstruction(spv::OpImageFetch, image_id, Ops);
5073 SPIRVInstList.push_back(Inst);
5074
5075 if (is_int_image) {
5076 // Generate the bitcast.
5077 Ops.clear();
5078 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
5079 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
5080 SPIRVInstList.push_back(Inst);
5081 }
5082 break;
5083 }
5084
alan-bakerf67468c2019-11-25 15:51:49 -05005085 // write_image is mapped to OpImageWrite.
SJW173c7e92020-03-16 08:44:47 -05005086 if (IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04005087 //
5088 // Generate OpImageWrite.
5089 //
5090 // Ops[0] = Image ID
5091 // Ops[1] = Coordinate ID
5092 // Ops[2] = Texel ID
5093 // Ops[3] = (Optional) Image Operands Type (Literal Number)
5094 // Ops[4] ... Ops[n] = (Optional) Operands ID
5095 //
5096 SPIRVOperandList Ops;
5097
5098 Value *Image = Call->getArgOperand(0);
5099 Value *Coordinate = Call->getArgOperand(1);
5100 Value *Texel = Call->getArgOperand(2);
5101
5102 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04005103 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04005104 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05005105
5106 const bool is_int_image = IsIntImageType(Image->getType());
5107 if (is_int_image) {
5108 // Generate a bitcast to v4int and use it as the texel value.
5109 uint32_t castID = nextID++;
5110 Ops << MkId(v4int32ID) << MkId(TexelID);
5111 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
5112 SPIRVInstList.push_back(cast);
5113 Ops.clear();
5114 TexelID = castID;
5115 }
David Neto257c3892018-04-11 13:19:45 -04005116 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04005117
David Neto87846742018-04-11 17:36:22 -04005118 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005119 SPIRVInstList.push_back(Inst);
5120 break;
5121 }
5122
alan-bakerce179f12019-12-06 19:02:22 -05005123 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
SJW173c7e92020-03-16 08:44:47 -05005124 if (IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04005125 //
alan-bakerce179f12019-12-06 19:02:22 -05005126 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04005127 //
5128 // Ops[0] = Image ID
5129 //
alan-bakerce179f12019-12-06 19:02:22 -05005130 // Result type has components equal to the dimensionality of the image,
5131 // plus 1 if the image is arrayed.
5132 //
alan-bakerf906d2b2019-12-10 11:26:23 -05005133 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04005134 SPIRVOperandList Ops;
5135
5136 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05005137 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
5138 uint32_t SizesTypeID = 0;
5139
David Neto5c22a252018-03-15 16:07:41 -04005140 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05005141 const uint32_t dim = ImageDimensionality(Image->getType());
alan-baker7150a1d2020-02-25 08:31:06 -05005142 const uint32_t components =
5143 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
alan-bakerce179f12019-12-06 19:02:22 -05005144 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05005145 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
5146 } else {
alan-baker7150a1d2020-02-25 08:31:06 -05005147 SizesTypeID =
5148 TypeMap[VectorType::get(Type::getInt32Ty(Context), components)];
alan-bakerce179f12019-12-06 19:02:22 -05005149 }
David Neto5c22a252018-03-15 16:07:41 -04005150 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04005151 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05005152 spv::Op query_opcode = spv::OpImageQuerySize;
SJW173c7e92020-03-16 08:44:47 -05005153 if (IsSampledImageType(Image->getType())) {
alan-bakerce179f12019-12-06 19:02:22 -05005154 query_opcode = spv::OpImageQuerySizeLod;
5155 // Need explicit 0 for Lod operand.
5156 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5157 Ops << MkId(VMap[CstInt0]);
5158 }
David Neto5c22a252018-03-15 16:07:41 -04005159
5160 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05005161 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04005162 SPIRVInstList.push_back(QueryInst);
5163
alan-bakerce179f12019-12-06 19:02:22 -05005164 // May require an extra instruction to create the appropriate result of
5165 // the builtin function.
SJW173c7e92020-03-16 08:44:47 -05005166 if (IsGetImageDim(Callee)) {
alan-bakerce179f12019-12-06 19:02:22 -05005167 if (dim == 3) {
5168 // get_image_dim returns an int4 for 3D images.
5169 //
5170 // Reset value map entry since we generated an intermediate
5171 // instruction.
5172 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04005173
alan-bakerce179f12019-12-06 19:02:22 -05005174 // Implement:
5175 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
5176 Ops.clear();
5177 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
5178 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04005179
alan-bakerce179f12019-12-06 19:02:22 -05005180 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
5181 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04005182
alan-bakerce179f12019-12-06 19:02:22 -05005183 auto *Inst =
5184 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
5185 SPIRVInstList.push_back(Inst);
5186 } else if (dim != components) {
5187 // get_image_dim return an int2 regardless of the arrayedness of the
5188 // image. If the image is arrayed an element must be dropped from the
5189 // query result.
5190 //
5191 // Reset value map entry since we generated an intermediate
5192 // instruction.
5193 VMap[&I] = nextID;
5194
5195 // Implement:
5196 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
5197 Ops.clear();
5198 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
5199 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
5200
5201 auto *Inst =
5202 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
5203 SPIRVInstList.push_back(Inst);
5204 }
5205 } else if (components > 1) {
5206 // Reset value map entry since we generated an intermediate instruction.
5207 VMap[&I] = nextID;
5208
5209 // Implement:
5210 // %result = OpCompositeExtract %uint %sizes <component number>
5211 Ops.clear();
5212 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
5213
5214 uint32_t component = 0;
5215 if (IsGetImageHeight(Callee))
5216 component = 1;
5217 else if (IsGetImageDepth(Callee))
5218 component = 2;
5219 Ops << MkNum(component);
5220
5221 auto *Inst =
5222 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
5223 SPIRVInstList.push_back(Inst);
5224 }
David Neto5c22a252018-03-15 16:07:41 -04005225 break;
5226 }
5227
David Neto22f144c2017-06-12 14:26:21 -04005228 // Call instrucion is deferred because it needs function's ID. Record
5229 // slot's location on SPIRVInstructionList.
5230 DeferredInsts.push_back(
5231 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5232
David Neto3fbb4072017-10-16 11:28:14 -04005233 // Check whether the implementation of this call uses an extended
5234 // instruction plus one more value-producing instruction. If so, then
5235 // reserve the id for the extra value-producing slot.
5236 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5237 if (EInst != kGlslExtInstBad) {
5238 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005239 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005240 VMap[&I] = nextID;
5241 nextID++;
5242 }
5243 break;
5244 }
5245 case Instruction::Ret: {
5246 unsigned NumOps = I.getNumOperands();
5247 if (NumOps == 0) {
5248 //
5249 // Generate OpReturn.
5250 //
David Netoef5ba2b2019-12-20 08:35:54 -05005251 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04005252 } else {
5253 //
5254 // Generate OpReturnValue.
5255 //
5256
5257 // Ops[0] = Return Value ID
5258 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04005259
5260 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005261
David Neto87846742018-04-11 17:36:22 -04005262 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005263 SPIRVInstList.push_back(Inst);
5264 break;
5265 }
5266 break;
5267 }
5268 }
5269}
5270
5271void SPIRVProducerPass::GenerateFuncEpilogue() {
SJW69939d52020-04-16 07:29:07 -05005272 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005273
5274 //
5275 // Generate OpFunctionEnd
5276 //
5277
David Netoef5ba2b2019-12-20 08:35:54 -05005278 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04005279 SPIRVInstList.push_back(Inst);
5280}
5281
5282bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05005283 // Don't specialize <4 x i8> if i8 is generally supported.
5284 if (clspv::Option::Int8Support())
5285 return false;
5286
David Neto22f144c2017-06-12 14:26:21 -04005287 LLVMContext &Context = Ty->getContext();
5288 if (Ty->isVectorTy()) {
5289 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
5290 Ty->getVectorNumElements() == 4) {
5291 return true;
5292 }
5293 }
5294
5295 return false;
5296}
5297
5298void SPIRVProducerPass::HandleDeferredInstruction() {
SJW69939d52020-04-16 07:29:07 -05005299 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kFunctions);
David Neto22f144c2017-06-12 14:26:21 -04005300 ValueMapType &VMap = getValueMap();
5301 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5302
5303 for (auto DeferredInst = DeferredInsts.rbegin();
5304 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5305 Value *Inst = std::get<0>(*DeferredInst);
5306 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5307 if (InsertPoint != SPIRVInstList.end()) {
5308 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5309 ++InsertPoint;
5310 }
5311 }
5312
5313 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05005314 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04005315 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05005316 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04005317 //
5318 // Generate OpLoopMerge.
5319 //
5320 // Ops[0] = Merge Block ID
5321 // Ops[1] = Continue Target ID
5322 // Ops[2] = Selection Control
5323 SPIRVOperandList Ops;
5324
alan-baker06cad652019-12-03 17:56:47 -05005325 auto MergeBB = MergeBlocks[BrBB];
5326 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04005327 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005328 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005329 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05005330 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005331
David Neto87846742018-04-11 17:36:22 -04005332 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005333 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005334 } else if (MergeBlocks.count(BrBB)) {
5335 //
5336 // Generate OpSelectionMerge.
5337 //
5338 // Ops[0] = Merge Block ID
5339 // Ops[1] = Selection Control
5340 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005341
alan-baker06cad652019-12-03 17:56:47 -05005342 auto MergeBB = MergeBlocks[BrBB];
5343 uint32_t MergeBBID = VMap[MergeBB];
5344 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005345
alan-baker06cad652019-12-03 17:56:47 -05005346 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5347 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005348 }
5349
5350 if (Br->isConditional()) {
5351 //
5352 // Generate OpBranchConditional.
5353 //
5354 // Ops[0] = Condition ID
5355 // Ops[1] = True Label ID
5356 // Ops[2] = False Label ID
5357 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5358 SPIRVOperandList Ops;
5359
5360 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005361 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005362 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005363
5364 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005365
David Neto87846742018-04-11 17:36:22 -04005366 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005367 SPIRVInstList.insert(InsertPoint, BrInst);
5368 } else {
5369 //
5370 // Generate OpBranch.
5371 //
5372 // Ops[0] = Target Label ID
5373 SPIRVOperandList Ops;
5374
5375 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005376 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005377
David Neto87846742018-04-11 17:36:22 -04005378 SPIRVInstList.insert(InsertPoint,
5379 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005380 }
5381 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04005382 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
5383 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05005384 // OpPhi on pointers requires variable pointers.
5385 setVariablePointersCapabilities(
5386 PHI->getType()->getPointerAddressSpace());
5387 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5388 setVariablePointers(true);
5389 }
5390 }
5391
David Neto22f144c2017-06-12 14:26:21 -04005392 //
5393 // Generate OpPhi.
5394 //
5395 // Ops[0] = Result Type ID
5396 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5397 SPIRVOperandList Ops;
5398
David Neto257c3892018-04-11 13:19:45 -04005399 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005400
David Neto22f144c2017-06-12 14:26:21 -04005401 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5402 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005403 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005404 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005405 }
5406
5407 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005408 InsertPoint,
5409 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005410 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5411 Function *Callee = Call->getCalledFunction();
SJW2c317da2020-03-23 07:39:13 -05005412 LLVMContext &Context = Callee->getContext();
5413 auto IntTy = Type::getInt32Ty(Context);
5414 auto callee_code = Builtins::Lookup(Callee);
David Neto3fbb4072017-10-16 11:28:14 -04005415 auto callee_name = Callee->getName();
5416 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005417
5418 if (EInst) {
5419 uint32_t &ExtInstImportID = getOpExtInstImportID();
5420
5421 //
5422 // Generate OpExtInst.
5423 //
5424
5425 // Ops[0] = Result Type ID
5426 // Ops[1] = Set ID (OpExtInstImport ID)
5427 // Ops[2] = Instruction Number (Literal Number)
5428 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5429 SPIRVOperandList Ops;
5430
David Neto862b7d82018-06-14 18:48:37 -04005431 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5432 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005433
David Neto22f144c2017-06-12 14:26:21 -04005434 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5435 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005436 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005437 }
5438
David Neto87846742018-04-11 17:36:22 -04005439 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5440 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005441 SPIRVInstList.insert(InsertPoint, ExtInst);
5442
David Neto3fbb4072017-10-16 11:28:14 -04005443 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5444 if (IndirectExtInst != kGlslExtInstBad) {
5445 // Generate one more instruction that uses the result of the extended
5446 // instruction. Its result id is one more than the id of the
5447 // extended instruction.
David Neto3fbb4072017-10-16 11:28:14 -04005448 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5449 &VMap, &SPIRVInstList, &InsertPoint](
5450 spv::Op opcode, Constant *constant) {
5451 //
5452 // Generate instruction like:
5453 // result = opcode constant <extinst-result>
5454 //
5455 // Ops[0] = Result Type ID
5456 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5457 // Ops[2] = Operand 1 ;; the result of the extended instruction
5458 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005459
David Neto3fbb4072017-10-16 11:28:14 -04005460 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005461 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005462
5463 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5464 constant = ConstantVector::getSplat(
alan-baker7261e062020-03-15 14:35:48 -04005465 {static_cast<unsigned>(vectorTy->getNumElements()), false},
5466 constant);
David Neto3fbb4072017-10-16 11:28:14 -04005467 }
David Neto257c3892018-04-11 13:19:45 -04005468 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005469
5470 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005471 InsertPoint, new SPIRVInstruction(
5472 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005473 };
5474
5475 switch (IndirectExtInst) {
5476 case glsl::ExtInstFindUMsb: // Implementing clz
SJW2c317da2020-03-23 07:39:13 -05005477 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
David Neto3fbb4072017-10-16 11:28:14 -04005478 break;
5479 case glsl::ExtInstAcos: // Implementing acospi
5480 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005481 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005482 case glsl::ExtInstAtan2: // Implementing atan2pi
5483 generate_extra_inst(
5484 spv::OpFMul,
5485 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5486 break;
5487
5488 default:
5489 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005490 }
David Neto22f144c2017-06-12 14:26:21 -04005491 }
David Neto3fbb4072017-10-16 11:28:14 -04005492
SJW2c317da2020-03-23 07:39:13 -05005493 } else if (callee_code == Builtins::kPopcount) {
David Neto22f144c2017-06-12 14:26:21 -04005494 //
5495 // Generate OpBitCount
5496 //
5497 // Ops[0] = Result Type ID
5498 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005499 SPIRVOperandList Ops;
5500 Ops << MkId(lookupType(Call->getType()))
5501 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005502
5503 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005504 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005505 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005506
David Neto862b7d82018-06-14 18:48:37 -04005507 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005508
5509 // Generate an OpCompositeConstruct
5510 SPIRVOperandList Ops;
5511
5512 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005513 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005514
5515 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005516 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005517 }
5518
5519 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005520 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5521 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005522
Alan Baker202c8c72018-08-13 13:47:44 -04005523 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5524
5525 // We have already mapped the call's result value to an ID.
5526 // Don't generate any code now.
5527
5528 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005529
5530 // We have already mapped the call's result value to an ID.
5531 // Don't generate any code now.
5532
David Neto22f144c2017-06-12 14:26:21 -04005533 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005534 if (Call->getType()->isPointerTy()) {
5535 // Functions returning pointers require variable pointers.
5536 setVariablePointersCapabilities(
5537 Call->getType()->getPointerAddressSpace());
5538 }
5539
David Neto22f144c2017-06-12 14:26:21 -04005540 //
5541 // Generate OpFunctionCall.
5542 //
5543
5544 // Ops[0] = Result Type ID
5545 // Ops[1] = Callee Function ID
5546 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5547 SPIRVOperandList Ops;
5548
David Neto862b7d82018-06-14 18:48:37 -04005549 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005550
5551 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005552 if (CalleeID == 0) {
5553 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005554 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005555 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5556 // causes an infinite loop. Instead, go ahead and generate
5557 // the bad function call. A validator will catch the 0-Id.
5558 // llvm_unreachable("Can't translate function call");
5559 }
David Neto22f144c2017-06-12 14:26:21 -04005560
David Neto257c3892018-04-11 13:19:45 -04005561 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005562
David Neto22f144c2017-06-12 14:26:21 -04005563 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5564 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005565 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005566 auto *operand_type = operand->getType();
5567 // Images and samplers can be passed as function parameters without
5568 // variable pointers.
5569 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5570 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005571 auto sc =
5572 GetStorageClass(operand->getType()->getPointerAddressSpace());
5573 if (sc == spv::StorageClassStorageBuffer) {
5574 // Passing SSBO by reference requires variable pointers storage
5575 // buffer.
5576 setVariablePointersStorageBuffer(true);
5577 } else if (sc == spv::StorageClassWorkgroup) {
5578 // Workgroup references require variable pointers if they are not
5579 // memory object declarations.
5580 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5581 // Workgroup accessor represents a variable reference.
5582 if (!operand_call->getCalledFunction()->getName().startswith(
5583 clspv::WorkgroupAccessorFunction()))
5584 setVariablePointers(true);
5585 } else {
5586 // Arguments are function parameters.
5587 if (!isa<Argument>(operand))
5588 setVariablePointers(true);
5589 }
5590 }
5591 }
5592 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005593 }
5594
David Neto87846742018-04-11 17:36:22 -04005595 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5596 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005597 SPIRVInstList.insert(InsertPoint, CallInst);
5598 }
5599 }
5600 }
5601}
5602
alan-bakera1be3322020-04-20 12:48:18 -04005603void SPIRVProducerPass::HandleDeferredDecorations(Module &module) {
5604 const auto &DL = module.getDataLayout();
Alan Baker202c8c72018-08-13 13:47:44 -04005605 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005606 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005607 }
David Neto1a1a0582017-07-07 12:01:44 -04005608
SJW69939d52020-04-16 07:29:07 -05005609 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList(kAnnotations);
David Neto1a1a0582017-07-07 12:01:44 -04005610
David Netoc6f3ab22018-04-06 18:02:31 -04005611 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5612 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005613 for (auto *type : getTypesNeedingArrayStride()) {
5614 Type *elemTy = nullptr;
5615 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5616 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005617 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04005618 elemTy = arrayTy->getElementType();
5619 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
5620 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07005621 } else {
5622 errs() << "Unhandled strided type " << *type << "\n";
5623 llvm_unreachable("Unhandled strided type");
5624 }
David Neto1a1a0582017-07-07 12:01:44 -04005625
5626 // Ops[0] = Target ID
5627 // Ops[1] = Decoration (ArrayStride)
5628 // Ops[2] = Stride number (Literal Number)
5629 SPIRVOperandList Ops;
5630
David Neto85082642018-03-24 06:55:20 -07005631 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005632 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005633
5634 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5635 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005636
David Neto87846742018-04-11 17:36:22 -04005637 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05005638 SPIRVInstList.push_back(DecoInst);
David Neto1a1a0582017-07-07 12:01:44 -04005639 }
David Netoc6f3ab22018-04-06 18:02:31 -04005640
5641 // Emit SpecId decorations targeting the array size value.
alan-bakera1be3322020-04-20 12:48:18 -04005642 for (auto pair : clspv::GetSpecConstants(&module)) {
5643 auto kind = pair.first;
5644 auto spec_id = pair.second;
5645
5646 if (kind != SpecConstant::kLocalMemorySize)
5647 continue;
5648
alan-bakerb6b09dc2018-11-08 16:59:28 -05005649 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005650 SPIRVOperandList Ops;
5651 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5652 << MkNum(arg_info.spec_id);
SJW69939d52020-04-16 07:29:07 -05005653 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005654 }
David Neto1a1a0582017-07-07 12:01:44 -04005655}
5656
David Neto22f144c2017-06-12 14:26:21 -04005657glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005658
5659 const auto &fi = Builtins::Lookup(Name);
5660 switch (fi) {
5661 case Builtins::kClamp: {
5662 auto param_type = fi.getParameter(0);
5663 if (param_type.type_id == Type::FloatTyID) {
5664 return glsl::ExtInst::ExtInstFClamp;
5665 }
5666 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
5667 : glsl::ExtInst::ExtInstUClamp;
5668 }
5669 case Builtins::kMax: {
5670 auto param_type = fi.getParameter(0);
5671 if (param_type.type_id == Type::FloatTyID) {
5672 return glsl::ExtInst::ExtInstFMax;
5673 }
5674 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
5675 : glsl::ExtInst::ExtInstUMax;
5676 }
5677 case Builtins::kMin: {
5678 auto param_type = fi.getParameter(0);
5679 if (param_type.type_id == Type::FloatTyID) {
5680 return glsl::ExtInst::ExtInstFMin;
5681 }
5682 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
5683 : glsl::ExtInst::ExtInstUMin;
5684 }
5685 case Builtins::kAbs:
5686 return glsl::ExtInst::ExtInstSAbs;
5687 case Builtins::kFmax:
5688 return glsl::ExtInst::ExtInstFMax;
5689 case Builtins::kFmin:
5690 return glsl::ExtInst::ExtInstFMin;
5691 case Builtins::kDegrees:
5692 return glsl::ExtInst::ExtInstDegrees;
5693 case Builtins::kRadians:
5694 return glsl::ExtInst::ExtInstRadians;
5695 case Builtins::kMix:
5696 return glsl::ExtInst::ExtInstFMix;
5697 case Builtins::kAcos:
5698 case Builtins::kAcospi:
5699 return glsl::ExtInst::ExtInstAcos;
5700 case Builtins::kAcosh:
5701 return glsl::ExtInst::ExtInstAcosh;
5702 case Builtins::kAsin:
5703 case Builtins::kAsinpi:
5704 return glsl::ExtInst::ExtInstAsin;
5705 case Builtins::kAsinh:
5706 return glsl::ExtInst::ExtInstAsinh;
5707 case Builtins::kAtan:
5708 case Builtins::kAtanpi:
5709 return glsl::ExtInst::ExtInstAtan;
5710 case Builtins::kAtanh:
5711 return glsl::ExtInst::ExtInstAtanh;
5712 case Builtins::kAtan2:
5713 case Builtins::kAtan2pi:
5714 return glsl::ExtInst::ExtInstAtan2;
5715 case Builtins::kCeil:
5716 return glsl::ExtInst::ExtInstCeil;
5717 case Builtins::kSin:
5718 case Builtins::kHalfSin:
5719 case Builtins::kNativeSin:
5720 return glsl::ExtInst::ExtInstSin;
5721 case Builtins::kSinh:
5722 return glsl::ExtInst::ExtInstSinh;
5723 case Builtins::kCos:
5724 case Builtins::kHalfCos:
5725 case Builtins::kNativeCos:
5726 return glsl::ExtInst::ExtInstCos;
5727 case Builtins::kCosh:
5728 return glsl::ExtInst::ExtInstCosh;
5729 case Builtins::kTan:
5730 case Builtins::kHalfTan:
5731 case Builtins::kNativeTan:
5732 return glsl::ExtInst::ExtInstTan;
5733 case Builtins::kTanh:
5734 return glsl::ExtInst::ExtInstTanh;
5735 case Builtins::kExp:
5736 case Builtins::kHalfExp:
5737 case Builtins::kNativeExp:
5738 return glsl::ExtInst::ExtInstExp;
5739 case Builtins::kExp2:
5740 case Builtins::kHalfExp2:
5741 case Builtins::kNativeExp2:
5742 return glsl::ExtInst::ExtInstExp2;
5743 case Builtins::kLog:
5744 case Builtins::kHalfLog:
5745 case Builtins::kNativeLog:
5746 return glsl::ExtInst::ExtInstLog;
5747 case Builtins::kLog2:
5748 case Builtins::kHalfLog2:
5749 case Builtins::kNativeLog2:
5750 return glsl::ExtInst::ExtInstLog2;
5751 case Builtins::kFabs:
5752 return glsl::ExtInst::ExtInstFAbs;
5753 case Builtins::kFma:
5754 return glsl::ExtInst::ExtInstFma;
5755 case Builtins::kFloor:
5756 return glsl::ExtInst::ExtInstFloor;
5757 case Builtins::kLdexp:
5758 return glsl::ExtInst::ExtInstLdexp;
5759 case Builtins::kPow:
5760 case Builtins::kPowr:
5761 case Builtins::kHalfPowr:
5762 case Builtins::kNativePowr:
5763 return glsl::ExtInst::ExtInstPow;
5764 case Builtins::kRound:
5765 return glsl::ExtInst::ExtInstRound;
5766 case Builtins::kSqrt:
5767 case Builtins::kHalfSqrt:
5768 case Builtins::kNativeSqrt:
5769 return glsl::ExtInst::ExtInstSqrt;
5770 case Builtins::kRsqrt:
5771 case Builtins::kHalfRsqrt:
5772 case Builtins::kNativeRsqrt:
5773 return glsl::ExtInst::ExtInstInverseSqrt;
5774 case Builtins::kTrunc:
5775 return glsl::ExtInst::ExtInstTrunc;
5776 case Builtins::kFrexp:
5777 return glsl::ExtInst::ExtInstFrexp;
5778 case Builtins::kFract:
5779 return glsl::ExtInst::ExtInstFract;
5780 case Builtins::kSign:
5781 return glsl::ExtInst::ExtInstFSign;
5782 case Builtins::kLength:
5783 case Builtins::kFastLength:
5784 return glsl::ExtInst::ExtInstLength;
5785 case Builtins::kDistance:
5786 case Builtins::kFastDistance:
5787 return glsl::ExtInst::ExtInstDistance;
5788 case Builtins::kStep:
5789 return glsl::ExtInst::ExtInstStep;
5790 case Builtins::kSmoothstep:
5791 return glsl::ExtInst::ExtInstSmoothStep;
5792 case Builtins::kCross:
5793 return glsl::ExtInst::ExtInstCross;
5794 case Builtins::kNormalize:
5795 case Builtins::kFastNormalize:
5796 return glsl::ExtInst::ExtInstNormalize;
5797 default:
5798 break;
5799 }
5800
David Neto22f144c2017-06-12 14:26:21 -04005801 return StringSwitch<glsl::ExtInst>(Name)
David Neto22f144c2017-06-12 14:26:21 -04005802 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5803 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5804 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto3fbb4072017-10-16 11:28:14 -04005805 .Default(kGlslExtInstBad);
5806}
5807
5808glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
SJW2c317da2020-03-23 07:39:13 -05005809 switch (Builtins::Lookup(Name)) {
5810 case Builtins::kClz:
5811 return glsl::ExtInst::ExtInstFindUMsb;
5812 case Builtins::kAcospi:
5813 return glsl::ExtInst::ExtInstAcos;
5814 case Builtins::kAsinpi:
5815 return glsl::ExtInst::ExtInstAsin;
5816 case Builtins::kAtanpi:
5817 return glsl::ExtInst::ExtInstAtan;
5818 case Builtins::kAtan2pi:
5819 return glsl::ExtInst::ExtInstAtan2;
5820 default:
5821 break;
5822 }
5823 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04005824}
5825
alan-bakerb6b09dc2018-11-08 16:59:28 -05005826glsl::ExtInst
5827SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005828 auto direct = getExtInstEnum(Name);
5829 if (direct != kGlslExtInstBad)
5830 return direct;
5831 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005832}
5833
David Neto22f144c2017-06-12 14:26:21 -04005834void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005835 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005836}
5837
5838void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5839 WriteOneWord(Inst->getResultID());
5840}
5841
5842void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5843 // High 16 bit : Word Count
5844 // Low 16 bit : Opcode
5845 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005846 const uint32_t count = Inst->getWordCount();
5847 if (count > 65535) {
5848 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5849 llvm_unreachable("Word count too high");
5850 }
David Neto22f144c2017-06-12 14:26:21 -04005851 Word |= Inst->getWordCount() << 16;
5852 WriteOneWord(Word);
5853}
5854
David Netoef5ba2b2019-12-20 08:35:54 -05005855void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005856 SPIRVOperandType OpTy = Op->getType();
5857 switch (OpTy) {
5858 default: {
5859 llvm_unreachable("Unsupported SPIRV Operand Type???");
5860 break;
5861 }
5862 case SPIRVOperandType::NUMBERID: {
5863 WriteOneWord(Op->getNumID());
5864 break;
5865 }
5866 case SPIRVOperandType::LITERAL_STRING: {
5867 std::string Str = Op->getLiteralStr();
5868 const char *Data = Str.c_str();
5869 size_t WordSize = Str.size() / 4;
5870 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5871 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5872 }
5873
5874 uint32_t Remainder = Str.size() % 4;
5875 uint32_t LastWord = 0;
5876 if (Remainder) {
5877 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5878 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5879 }
5880 }
5881
5882 WriteOneWord(LastWord);
5883 break;
5884 }
5885 case SPIRVOperandType::LITERAL_INTEGER:
5886 case SPIRVOperandType::LITERAL_FLOAT: {
5887 auto LiteralNum = Op->getLiteralNum();
5888 // TODO: Handle LiteranNum carefully.
5889 for (auto Word : LiteralNum) {
5890 WriteOneWord(Word);
5891 }
5892 break;
5893 }
5894 }
5895}
5896
5897void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005898 for (int i = 0; i < kSectionCount; ++i) {
5899 WriteSPIRVBinary(SPIRVSections[i]);
5900 }
5901}
5902
5903void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
David Neto22f144c2017-06-12 14:26:21 -04005904
5905 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005906 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005907 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5908
5909 switch (Opcode) {
5910 default: {
David Neto5c22a252018-03-15 16:07:41 -04005911 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005912 llvm_unreachable("Unsupported SPIRV instruction");
5913 break;
5914 }
5915 case spv::OpCapability:
5916 case spv::OpExtension:
5917 case spv::OpMemoryModel:
5918 case spv::OpEntryPoint:
5919 case spv::OpExecutionMode:
5920 case spv::OpSource:
5921 case spv::OpDecorate:
5922 case spv::OpMemberDecorate:
5923 case spv::OpBranch:
5924 case spv::OpBranchConditional:
5925 case spv::OpSelectionMerge:
5926 case spv::OpLoopMerge:
5927 case spv::OpStore:
5928 case spv::OpImageWrite:
5929 case spv::OpReturnValue:
5930 case spv::OpControlBarrier:
5931 case spv::OpMemoryBarrier:
5932 case spv::OpReturn:
5933 case spv::OpFunctionEnd:
5934 case spv::OpCopyMemory: {
5935 WriteWordCountAndOpcode(Inst);
5936 for (uint32_t i = 0; i < Ops.size(); i++) {
5937 WriteOperand(Ops[i]);
5938 }
5939 break;
5940 }
5941 case spv::OpTypeBool:
5942 case spv::OpTypeVoid:
5943 case spv::OpTypeSampler:
5944 case spv::OpLabel:
5945 case spv::OpExtInstImport:
5946 case spv::OpTypePointer:
5947 case spv::OpTypeRuntimeArray:
5948 case spv::OpTypeStruct:
5949 case spv::OpTypeImage:
5950 case spv::OpTypeSampledImage:
5951 case spv::OpTypeInt:
5952 case spv::OpTypeFloat:
5953 case spv::OpTypeArray:
5954 case spv::OpTypeVector:
5955 case spv::OpTypeFunction: {
5956 WriteWordCountAndOpcode(Inst);
5957 WriteResultID(Inst);
5958 for (uint32_t i = 0; i < Ops.size(); i++) {
5959 WriteOperand(Ops[i]);
5960 }
5961 break;
5962 }
5963 case spv::OpFunction:
5964 case spv::OpFunctionParameter:
5965 case spv::OpAccessChain:
5966 case spv::OpPtrAccessChain:
5967 case spv::OpInBoundsAccessChain:
5968 case spv::OpUConvert:
5969 case spv::OpSConvert:
5970 case spv::OpConvertFToU:
5971 case spv::OpConvertFToS:
5972 case spv::OpConvertUToF:
5973 case spv::OpConvertSToF:
5974 case spv::OpFConvert:
5975 case spv::OpConvertPtrToU:
5976 case spv::OpConvertUToPtr:
5977 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005978 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005979 case spv::OpIAdd:
5980 case spv::OpFAdd:
5981 case spv::OpISub:
5982 case spv::OpFSub:
5983 case spv::OpIMul:
5984 case spv::OpFMul:
5985 case spv::OpUDiv:
5986 case spv::OpSDiv:
5987 case spv::OpFDiv:
5988 case spv::OpUMod:
5989 case spv::OpSRem:
5990 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005991 case spv::OpUMulExtended:
5992 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005993 case spv::OpBitwiseOr:
5994 case spv::OpBitwiseXor:
5995 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005996 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005997 case spv::OpShiftLeftLogical:
5998 case spv::OpShiftRightLogical:
5999 case spv::OpShiftRightArithmetic:
6000 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006001 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006002 case spv::OpCompositeExtract:
6003 case spv::OpVectorExtractDynamic:
6004 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006005 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006006 case spv::OpVectorInsertDynamic:
6007 case spv::OpVectorShuffle:
6008 case spv::OpIEqual:
6009 case spv::OpINotEqual:
6010 case spv::OpUGreaterThan:
6011 case spv::OpUGreaterThanEqual:
6012 case spv::OpULessThan:
6013 case spv::OpULessThanEqual:
6014 case spv::OpSGreaterThan:
6015 case spv::OpSGreaterThanEqual:
6016 case spv::OpSLessThan:
6017 case spv::OpSLessThanEqual:
6018 case spv::OpFOrdEqual:
6019 case spv::OpFOrdGreaterThan:
6020 case spv::OpFOrdGreaterThanEqual:
6021 case spv::OpFOrdLessThan:
6022 case spv::OpFOrdLessThanEqual:
6023 case spv::OpFOrdNotEqual:
6024 case spv::OpFUnordEqual:
6025 case spv::OpFUnordGreaterThan:
6026 case spv::OpFUnordGreaterThanEqual:
6027 case spv::OpFUnordLessThan:
6028 case spv::OpFUnordLessThanEqual:
6029 case spv::OpFUnordNotEqual:
6030 case spv::OpExtInst:
6031 case spv::OpIsInf:
6032 case spv::OpIsNan:
6033 case spv::OpAny:
6034 case spv::OpAll:
6035 case spv::OpUndef:
6036 case spv::OpConstantNull:
6037 case spv::OpLogicalOr:
6038 case spv::OpLogicalAnd:
6039 case spv::OpLogicalNot:
6040 case spv::OpLogicalNotEqual:
6041 case spv::OpConstantComposite:
6042 case spv::OpSpecConstantComposite:
6043 case spv::OpConstantTrue:
6044 case spv::OpConstantFalse:
6045 case spv::OpConstant:
6046 case spv::OpSpecConstant:
6047 case spv::OpVariable:
6048 case spv::OpFunctionCall:
6049 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05006050 case spv::OpImageFetch:
David Neto22f144c2017-06-12 14:26:21 -04006051 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006052 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05006053 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04006054 case spv::OpSelect:
6055 case spv::OpPhi:
6056 case spv::OpLoad:
6057 case spv::OpAtomicIAdd:
6058 case spv::OpAtomicISub:
6059 case spv::OpAtomicExchange:
6060 case spv::OpAtomicIIncrement:
6061 case spv::OpAtomicIDecrement:
6062 case spv::OpAtomicCompareExchange:
6063 case spv::OpAtomicUMin:
6064 case spv::OpAtomicSMin:
6065 case spv::OpAtomicUMax:
6066 case spv::OpAtomicSMax:
6067 case spv::OpAtomicAnd:
6068 case spv::OpAtomicOr:
6069 case spv::OpAtomicXor:
6070 case spv::OpDot: {
6071 WriteWordCountAndOpcode(Inst);
6072 WriteOperand(Ops[0]);
6073 WriteResultID(Inst);
6074 for (uint32_t i = 1; i < Ops.size(); i++) {
6075 WriteOperand(Ops[i]);
6076 }
6077 break;
6078 }
6079 }
6080 }
6081}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006082
alan-bakerb6b09dc2018-11-08 16:59:28 -05006083bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006084 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006085 case Type::HalfTyID:
6086 case Type::FloatTyID:
6087 case Type::DoubleTyID:
6088 case Type::IntegerTyID:
6089 case Type::VectorTyID:
6090 return true;
6091 case Type::PointerTyID: {
6092 const PointerType *pointer_type = cast<PointerType>(type);
6093 if (pointer_type->getPointerAddressSpace() !=
6094 AddressSpace::UniformConstant) {
6095 auto pointee_type = pointer_type->getPointerElementType();
6096 if (pointee_type->isStructTy() &&
6097 cast<StructType>(pointee_type)->isOpaque()) {
6098 // Images and samplers are not nullable.
6099 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006100 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006101 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006102 return true;
6103 }
6104 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04006105 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05006106 case Type::StructTyID: {
6107 const StructType *struct_type = cast<StructType>(type);
6108 // Images and samplers are not nullable.
6109 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006110 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006111 for (const auto element : struct_type->elements()) {
6112 if (!IsTypeNullable(element))
6113 return false;
6114 }
6115 return true;
6116 }
6117 default:
6118 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006119 }
6120}
Alan Bakerfcda9482018-10-02 17:09:59 -04006121
6122void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6123 if (auto *offsets_md =
6124 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6125 // Metdata is stored as key-value pair operands. The first element of each
6126 // operand is the type and the second is a vector of offsets.
6127 for (const auto *operand : offsets_md->operands()) {
6128 const auto *pair = cast<MDTuple>(operand);
6129 auto *type =
6130 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6131 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6132 std::vector<uint32_t> offsets;
6133 for (const Metadata *offset_md : offset_vector->operands()) {
6134 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006135 offsets.push_back(static_cast<uint32_t>(
6136 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006137 }
6138 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6139 }
6140 }
6141
6142 if (auto *sizes_md =
6143 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6144 // Metadata is stored as key-value pair operands. The first element of each
6145 // operand is the type and the second is a triple of sizes: type size in
6146 // bits, store size and alloc size.
6147 for (const auto *operand : sizes_md->operands()) {
6148 const auto *pair = cast<MDTuple>(operand);
6149 auto *type =
6150 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6151 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6152 uint64_t type_size_in_bits =
6153 cast<ConstantInt>(
6154 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6155 ->getZExtValue();
6156 uint64_t type_store_size =
6157 cast<ConstantInt>(
6158 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6159 ->getZExtValue();
6160 uint64_t type_alloc_size =
6161 cast<ConstantInt>(
6162 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6163 ->getZExtValue();
6164 RemappedUBOTypeSizes.insert(std::make_pair(
6165 type, std::make_tuple(type_size_in_bits, type_store_size,
6166 type_alloc_size)));
6167 }
6168 }
6169}
6170
6171uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6172 const DataLayout &DL) {
6173 auto iter = RemappedUBOTypeSizes.find(type);
6174 if (iter != RemappedUBOTypeSizes.end()) {
6175 return std::get<0>(iter->second);
6176 }
6177
6178 return DL.getTypeSizeInBits(type);
6179}
6180
6181uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6182 auto iter = RemappedUBOTypeSizes.find(type);
6183 if (iter != RemappedUBOTypeSizes.end()) {
6184 return std::get<1>(iter->second);
6185 }
6186
6187 return DL.getTypeStoreSize(type);
6188}
6189
6190uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6191 auto iter = RemappedUBOTypeSizes.find(type);
6192 if (iter != RemappedUBOTypeSizes.end()) {
6193 return std::get<2>(iter->second);
6194 }
6195
6196 return DL.getTypeAllocSize(type);
6197}
alan-baker5b86ed72019-02-15 08:26:50 -05006198
Kévin Petitbbbda972020-03-03 19:16:31 +00006199uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
6200 StructType *type, unsigned member, const DataLayout &DL) {
6201 const auto StructLayout = DL.getStructLayout(type);
6202 // Search for the correct offsets if this type was remapped.
6203 std::vector<uint32_t> *offsets = nullptr;
6204 auto iter = RemappedUBOTypeOffsets.find(type);
6205 if (iter != RemappedUBOTypeOffsets.end()) {
6206 offsets = &iter->second;
6207 }
6208 auto ByteOffset =
6209 static_cast<uint32_t>(StructLayout->getElementOffset(member));
6210 if (offsets) {
6211 ByteOffset = (*offsets)[member];
6212 }
6213
6214 return ByteOffset;
6215}
6216
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006217void SPIRVProducerPass::setVariablePointersCapabilities(
6218 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006219 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6220 setVariablePointersStorageBuffer(true);
6221 } else {
6222 setVariablePointers(true);
6223 }
6224}
6225
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006226Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006227 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6228 return GetBasePointer(gep->getPointerOperand());
6229 }
6230
6231 // Conservatively return |v|.
6232 return v;
6233}
6234
6235bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6236 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6237 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6238 if (lhs_call->getCalledFunction()->getName().startswith(
6239 clspv::ResourceAccessorFunction()) &&
6240 rhs_call->getCalledFunction()->getName().startswith(
6241 clspv::ResourceAccessorFunction())) {
6242 // For resource accessors, match descriptor set and binding.
6243 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6244 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6245 return true;
6246 } else if (lhs_call->getCalledFunction()->getName().startswith(
6247 clspv::WorkgroupAccessorFunction()) &&
6248 rhs_call->getCalledFunction()->getName().startswith(
6249 clspv::WorkgroupAccessorFunction())) {
6250 // For workgroup resources, match spec id.
6251 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6252 return true;
6253 }
6254 }
6255 }
6256
6257 return false;
6258}
6259
6260bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6261 assert(inst->getType()->isPointerTy());
6262 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6263 spv::StorageClassStorageBuffer);
6264 const bool hack_undef = clspv::Option::HackUndef();
6265 if (auto *select = dyn_cast<SelectInst>(inst)) {
6266 auto *true_base = GetBasePointer(select->getTrueValue());
6267 auto *false_base = GetBasePointer(select->getFalseValue());
6268
6269 if (true_base == false_base)
6270 return true;
6271
6272 // If either the true or false operand is a null, then we satisfy the same
6273 // object constraint.
6274 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6275 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6276 return true;
6277 }
6278
6279 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6280 if (false_cst->isNullValue() ||
6281 (hack_undef && isa<UndefValue>(false_base)))
6282 return true;
6283 }
6284
6285 if (sameResource(true_base, false_base))
6286 return true;
6287 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6288 Value *value = nullptr;
6289 bool ok = true;
6290 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6291 auto *base = GetBasePointer(phi->getIncomingValue(i));
6292 // Null values satisfy the constraint of selecting of selecting from the
6293 // same object.
6294 if (!value) {
6295 if (auto *cst = dyn_cast<Constant>(base)) {
6296 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6297 value = base;
6298 } else {
6299 value = base;
6300 }
6301 } else if (base != value) {
6302 if (auto *base_cst = dyn_cast<Constant>(base)) {
6303 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6304 continue;
6305 }
6306
6307 if (sameResource(value, base))
6308 continue;
6309
6310 // Values don't represent the same base.
6311 ok = false;
6312 }
6313 }
6314
6315 return ok;
6316 }
6317
6318 // Conservatively return false.
6319 return false;
6320}
alan-bakere9308012019-03-15 10:25:13 -04006321
6322bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6323 if (!Arg.getType()->isPointerTy() ||
6324 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6325 // Only SSBOs need to be annotated as coherent.
6326 return false;
6327 }
6328
6329 DenseSet<Value *> visited;
6330 std::vector<Value *> stack;
6331 for (auto *U : Arg.getParent()->users()) {
6332 if (auto *call = dyn_cast<CallInst>(U)) {
6333 stack.push_back(call->getOperand(Arg.getArgNo()));
6334 }
6335 }
6336
6337 while (!stack.empty()) {
6338 Value *v = stack.back();
6339 stack.pop_back();
6340
6341 if (!visited.insert(v).second)
6342 continue;
6343
6344 auto *resource_call = dyn_cast<CallInst>(v);
6345 if (resource_call &&
6346 resource_call->getCalledFunction()->getName().startswith(
6347 clspv::ResourceAccessorFunction())) {
6348 // If this is a resource accessor function, check if the coherent operand
6349 // is set.
6350 const auto coherent =
6351 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6352 ->getZExtValue());
6353 if (coherent == 1)
6354 return true;
6355 } else if (auto *arg = dyn_cast<Argument>(v)) {
6356 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006357 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006358 if (auto *call = dyn_cast<CallInst>(U)) {
6359 stack.push_back(call->getOperand(arg->getArgNo()));
6360 }
6361 }
6362 } else if (auto *user = dyn_cast<User>(v)) {
6363 // If this is a user, traverse all operands that could lead to resource
6364 // variables.
6365 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6366 Value *operand = user->getOperand(i);
6367 if (operand->getType()->isPointerTy() &&
6368 operand->getType()->getPointerAddressSpace() ==
6369 clspv::AddressSpace::Global) {
6370 stack.push_back(operand);
6371 }
6372 }
6373 }
6374 }
6375
6376 // No coherent resource variables encountered.
6377 return false;
6378}
alan-baker06cad652019-12-03 17:56:47 -05006379
6380void SPIRVProducerPass::PopulateStructuredCFGMaps(Module &module) {
6381 // First, track loop merges and continues.
6382 DenseSet<BasicBlock *> LoopMergesAndContinues;
6383 for (auto &F : module) {
6384 if (F.isDeclaration())
6385 continue;
6386
6387 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6388 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6389 std::deque<BasicBlock *> order;
6390 DenseSet<BasicBlock *> visited;
6391 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6392
6393 for (auto BB : order) {
6394 auto terminator = BB->getTerminator();
6395 auto branch = dyn_cast<BranchInst>(terminator);
6396 if (LI.isLoopHeader(BB)) {
6397 auto L = LI.getLoopFor(BB);
6398 BasicBlock *ContinueBB = nullptr;
6399 BasicBlock *MergeBB = nullptr;
6400
6401 MergeBB = L->getExitBlock();
6402 if (!MergeBB) {
6403 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6404 // has regions with single entry/exit. As a result, loop should not
6405 // have multiple exits.
6406 llvm_unreachable("Loop has multiple exits???");
6407 }
6408
6409 if (L->isLoopLatch(BB)) {
6410 ContinueBB = BB;
6411 } else {
6412 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6413 // block.
6414 BasicBlock *Header = L->getHeader();
6415 BasicBlock *Latch = L->getLoopLatch();
6416 for (auto *loop_block : L->blocks()) {
6417 if (loop_block == Header) {
6418 continue;
6419 }
6420
6421 // Check whether block dominates block with back-edge.
6422 // The loop latch is the single block with a back-edge. If it was
6423 // possible, StructurizeCFG made the loop conform to this
6424 // requirement, otherwise |Latch| is a nullptr.
6425 if (DT.dominates(loop_block, Latch)) {
6426 ContinueBB = loop_block;
6427 }
6428 }
6429
6430 if (!ContinueBB) {
6431 llvm_unreachable("Wrong continue block from loop");
6432 }
6433 }
6434
6435 // Record the continue and merge blocks.
6436 MergeBlocks[BB] = MergeBB;
6437 ContinueBlocks[BB] = ContinueBB;
6438 LoopMergesAndContinues.insert(MergeBB);
6439 LoopMergesAndContinues.insert(ContinueBB);
6440 } else if (branch && branch->isConditional()) {
6441 auto L = LI.getLoopFor(BB);
6442 bool HasBackedge = false;
6443 while (L && !HasBackedge) {
6444 if (L->isLoopLatch(BB)) {
6445 HasBackedge = true;
6446 }
6447 L = L->getParentLoop();
6448 }
6449
6450 if (!HasBackedge) {
6451 // Only need a merge if the branch doesn't include a loop break or
6452 // continue.
6453 auto true_bb = branch->getSuccessor(0);
6454 auto false_bb = branch->getSuccessor(1);
6455 if (!LoopMergesAndContinues.count(true_bb) &&
6456 !LoopMergesAndContinues.count(false_bb)) {
6457 // StructurizeCFG pass already manipulated CFG. Just use false block
6458 // of branch instruction as merge block.
6459 MergeBlocks[BB] = false_bb;
6460 }
6461 }
6462 }
6463 }
6464 }
6465}